3489e8d55bf4cad23a0cf7898aa96c2591d6e234
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 "common.h"
28 #include "plugin.h"
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
34 #ifdef HAVE_MATH_H
35 # include <math.h>
36 #endif
38 /* for ntohl and htonl */
39 #if HAVE_ARPA_INET_H
40 # include <arpa/inet.h>
41 #endif
43 #ifdef HAVE_LIBKSTAT
44 extern kstat_ctl_t *kc;
45 #endif
47 #if !HAVE_GETPWNAM_R
48 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
49 #endif
51 #if !HAVE_STRERROR_R
52 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
53 #endif
55 void sstrncpy (char *d, const char *s, int len)
56 {
57 strncpy (d, s, len);
58 d[len - 1] = '\0';
59 }
61 char *sstrdup (const char *s)
62 {
63 char *r;
65 if (s == NULL)
66 return (NULL);
68 if((r = strdup (s)) == NULL)
69 {
70 DEBUG ("Not enough memory.");
71 exit(3);
72 }
74 return (r);
75 }
77 /* Even though Posix requires "strerror_r" to return an "int",
78 * some systems (e.g. the GNU libc) return a "char *" _and_
79 * ignore the second argument ... -tokkee */
80 char *sstrerror (int errnum, char *buf, size_t buflen)
81 {
82 buf[0] = '\0';
84 #if !HAVE_STRERROR_R
85 {
86 char *temp;
88 pthread_mutex_lock (&strerror_r_lock);
90 temp = strerror (errnum);
91 strncpy (buf, temp, buflen);
93 pthread_mutex_unlock (&strerror_r_lock);
94 }
95 /* #endif !HAVE_STRERROR_R */
97 #elif STRERROR_R_CHAR_P
98 {
99 char *temp;
100 temp = strerror_r (errnum, buf, buflen);
101 if (buf[0] == '\0')
102 {
103 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
104 strncpy (buf, temp, buflen);
105 else
106 strncpy (buf, "strerror_r did not return "
107 "an error message", buflen);
108 }
109 }
110 /* #endif STRERROR_R_CHAR_P */
112 #else
113 if (strerror_r (errnum, buf, buflen) != 0)
114 {
115 snprintf (buf, buflen, "Error #%i; "
116 "Additionally, strerror_r failed.",
117 errnum);
118 }
119 #endif /* STRERROR_R_CHAR_P */
121 buf[buflen - 1] = '\0';
122 return (buf);
123 } /* char *sstrerror */
125 void *smalloc (size_t size)
126 {
127 void *r;
129 if ((r = malloc (size)) == NULL)
130 {
131 DEBUG("Not enough memory.");
132 exit(3);
133 }
135 return r;
136 }
138 #if 0
139 void sfree (void **ptr)
140 {
141 if (ptr == NULL)
142 return;
144 if (*ptr != NULL)
145 free (*ptr);
147 *ptr = NULL;
148 }
149 #endif
151 ssize_t sread (int fd, void *buf, size_t count)
152 {
153 char *ptr;
154 size_t nleft;
155 ssize_t status;
157 ptr = (char *) buf;
158 nleft = count;
160 while (nleft > 0)
161 {
162 status = read (fd, (void *) ptr, nleft);
164 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
165 continue;
167 if (status < 0)
168 return (status);
170 if (status == 0)
171 {
172 DEBUG ("Received EOF from fd %i. "
173 "Closing fd and returning error.",
174 fd);
175 close (fd);
176 return (-1);
177 }
179 assert ((0 > status) || (nleft >= (size_t)status));
181 nleft = nleft - status;
182 ptr = ptr + status;
183 }
185 return (0);
186 }
189 ssize_t swrite (int fd, const void *buf, size_t count)
190 {
191 const char *ptr;
192 size_t nleft;
193 ssize_t status;
195 ptr = (const char *) buf;
196 nleft = count;
198 while (nleft > 0)
199 {
200 status = write (fd, (const void *) ptr, nleft);
202 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
203 continue;
205 if (status < 0)
206 return (status);
208 nleft = nleft - status;
209 ptr = ptr + status;
210 }
212 return (0);
213 }
215 int strsplit (char *string, char **fields, size_t size)
216 {
217 size_t i;
218 char *ptr;
219 char *saveptr;
221 i = 0;
222 ptr = string;
223 saveptr = NULL;
224 while ((fields[i] = strtok_r (ptr, " \t", &saveptr)) != NULL)
225 {
226 ptr = NULL;
227 i++;
229 if (i >= size)
230 break;
231 }
233 return (i);
234 }
236 int strjoin (char *dst, size_t dst_len,
237 char **fields, size_t fields_num,
238 const char *sep)
239 {
240 size_t field_len;
241 size_t sep_len;
242 int i;
244 memset (dst, '\0', dst_len);
246 if (fields_num <= 0)
247 return (-1);
249 sep_len = 0;
250 if (sep != NULL)
251 sep_len = strlen (sep);
253 for (i = 0; i < (int)fields_num; i++)
254 {
255 if ((i > 0) && (sep_len > 0))
256 {
257 if (dst_len <= sep_len)
258 return (-1);
260 strncat (dst, sep, dst_len);
261 dst_len -= sep_len;
262 }
264 field_len = strlen (fields[i]);
266 if (dst_len <= field_len)
267 return (-1);
269 strncat (dst, fields[i], dst_len);
270 dst_len -= field_len;
271 }
273 return (strlen (dst));
274 }
276 int strsubstitute (char *str, char c_from, char c_to)
277 {
278 int ret;
280 if (str == NULL)
281 return (-1);
283 ret = 0;
284 while (*str != '\0')
285 {
286 if (*str == c_from)
287 {
288 *str = c_to;
289 ret++;
290 }
291 str++;
292 }
294 return (ret);
295 } /* int strsubstitute */
297 int escape_slashes (char *buf, int buf_len)
298 {
299 int i;
301 if (strcmp (buf, "/") == 0)
302 {
303 if (buf_len < 5)
304 return (-1);
306 strncpy (buf, "root", buf_len);
307 return (0);
308 }
310 if (buf_len <= 1)
311 return (0);
313 /* Move one to the left */
314 if (buf[0] == '/')
315 memmove (buf, buf + 1, buf_len - 1);
317 for (i = 0; i < buf_len - 1; i++)
318 {
319 if (buf[i] == '\0')
320 break;
321 else if (buf[i] == '/')
322 buf[i] = '_';
323 }
324 buf[i] = '\0';
326 return (0);
327 } /* int escape_slashes */
329 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
330 {
331 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
332 return (-2);
334 if ((tv0->tv_sec < tv1->tv_sec)
335 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
336 return (-1);
338 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
339 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
341 if (ret->tv_nsec < 0)
342 {
343 assert (ret->tv_sec > 0);
345 ret->tv_nsec += 1000000000;
346 ret->tv_sec -= 1;
347 }
349 return (0);
350 }
352 int check_create_dir (const char *file_orig)
353 {
354 struct stat statbuf;
356 char file_copy[512];
357 char dir[512];
358 int dir_len = 512;
359 char *fields[16];
360 int fields_num;
361 char *ptr;
362 char *saveptr;
363 int last_is_file = 1;
364 int path_is_absolute = 0;
365 int len;
366 int i;
368 /*
369 * Sanity checks first
370 */
371 if (file_orig == NULL)
372 return (-1);
374 if ((len = strlen (file_orig)) < 1)
375 return (-1);
376 else if (len >= 512)
377 return (-1);
379 /*
380 * If `file_orig' ends in a slash the last component is a directory,
381 * otherwise it's a file. Act accordingly..
382 */
383 if (file_orig[len - 1] == '/')
384 last_is_file = 0;
385 if (file_orig[0] == '/')
386 path_is_absolute = 1;
388 /*
389 * Create a copy for `strtok_r' to destroy
390 */
391 strncpy (file_copy, file_orig, 512);
392 file_copy[511] = '\0';
394 /*
395 * Break into components. This will eat up several slashes in a row and
396 * remove leading and trailing slashes..
397 */
398 ptr = file_copy;
399 saveptr = NULL;
400 fields_num = 0;
401 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
402 {
403 ptr = NULL;
404 fields_num++;
406 if (fields_num >= 16)
407 break;
408 }
410 /*
411 * For each component, do..
412 */
413 for (i = 0; i < (fields_num - last_is_file); i++)
414 {
415 /*
416 * Do not create directories that start with a dot. This
417 * prevents `../../' attacks and other likely malicious
418 * behavior.
419 */
420 if (fields[i][0] == '.')
421 {
422 ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
423 return (-2);
424 }
426 /*
427 * Join the components together again
428 */
429 dir[0] = '/';
430 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
431 fields, i + 1, "/") < 0)
432 {
433 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
434 return (-1);
435 }
437 if (stat (dir, &statbuf) == -1)
438 {
439 if (errno == ENOENT)
440 {
441 if (mkdir (dir, 0755) == -1)
442 {
443 char errbuf[1024];
444 ERROR ("check_create_dir: mkdir (%s): %s", dir,
445 sstrerror (errno,
446 errbuf, sizeof (errbuf)));
447 return (-1);
448 }
449 }
450 else
451 {
452 char errbuf[1024];
453 ERROR ("stat (%s): %s", dir,
454 sstrerror (errno, errbuf,
455 sizeof (errbuf)));
456 return (-1);
457 }
458 }
459 else if (!S_ISDIR (statbuf.st_mode))
460 {
461 ERROR ("stat (%s): Not a directory!", dir);
462 return (-1);
463 }
464 }
466 return (0);
467 } /* check_create_dir */
469 #ifdef HAVE_LIBKSTAT
470 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
471 {
472 char ident[128];
474 if (kc == NULL)
475 return (-1);
477 snprintf (ident, 128, "%s,%i,%s", module, instance, name);
478 ident[127] = '\0';
480 if (*ksp_ptr == NULL)
481 {
482 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
483 {
484 ERROR ("Cound not find kstat %s", ident);
485 return (-1);
486 }
488 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
489 {
490 WARNING ("kstat %s has wrong type", ident);
491 *ksp_ptr = NULL;
492 return (-1);
493 }
494 }
496 #ifdef assert
497 assert (*ksp_ptr != NULL);
498 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
499 #endif
501 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
502 {
503 WARNING ("kstat %s could not be read", ident);
504 return (-1);
505 }
507 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
508 {
509 WARNING ("kstat %s has wrong type", ident);
510 return (-1);
511 }
513 return (0);
514 }
516 long long get_kstat_value (kstat_t *ksp, char *name)
517 {
518 kstat_named_t *kn;
519 long long retval = -1LL;
521 #ifdef assert
522 assert (ksp != NULL);
523 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
524 #else
525 if (ksp == NULL)
526 {
527 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
528 return (-1LL);
529 }
530 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
531 {
532 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
533 return (-1LL);
534 }
535 #endif
537 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
538 return (retval);
540 if (kn->data_type == KSTAT_DATA_INT32)
541 retval = (long long) kn->value.i32;
542 else if (kn->data_type == KSTAT_DATA_UINT32)
543 retval = (long long) kn->value.ui32;
544 else if (kn->data_type == KSTAT_DATA_INT64)
545 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
546 else if (kn->data_type == KSTAT_DATA_UINT64)
547 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
548 else
549 WARNING ("get_kstat_value: Not a numeric value: %s", name);
551 return (retval);
552 }
553 #endif /* HAVE_LIBKSTAT */
555 unsigned long long ntohll (unsigned long long n)
556 {
557 #if __BYTE_ORDER == __BIG_ENDIAN
558 return (n);
559 #else
560 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
561 #endif
562 } /* unsigned long long ntohll */
564 unsigned long long htonll (unsigned long long n)
565 {
566 #if __BYTE_ORDER == __BIG_ENDIAN
567 return (n);
568 #else
569 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
570 #endif
571 } /* unsigned long long htonll */
573 #if FP_LAYOUT_NEED_NOTHING
574 /* Well, we need nothing.. */
575 /* #endif FP_LAYOUT_NEED_NOTHING */
577 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
578 # if FP_LAYOUT_NEED_ENDIANFLIP
579 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
580 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
581 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
582 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
583 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
584 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
585 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
586 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
587 # else
588 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
589 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
590 # endif
592 double ntohd (double d)
593 {
594 union
595 {
596 uint8_t byte[8];
597 uint64_t integer;
598 double floating;
599 } ret;
601 ret.floating = d;
603 /* NAN in x86 byte order */
604 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
605 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
606 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
607 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
608 {
609 return (NAN);
610 }
611 else
612 {
613 uint64_t tmp;
615 tmp = ret.integer;
616 ret.integer = FP_CONVERT (tmp);
617 return (ret.floating);
618 }
619 } /* double ntohd */
621 double htond (double d)
622 {
623 union
624 {
625 uint8_t byte[8];
626 uint64_t integer;
627 double floating;
628 } ret;
630 if (isnan (d))
631 {
632 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
633 ret.byte[4] = ret.byte[5] = 0x00;
634 ret.byte[6] = 0xf8;
635 ret.byte[7] = 0x7f;
636 return (ret.floating);
637 }
638 else
639 {
640 uint64_t tmp;
642 ret.floating = d;
643 tmp = FP_CONVERT (ret.integer);
644 ret.integer = tmp;
645 return (ret.floating);
646 }
647 } /* double htond */
648 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
650 int format_name (char *ret, int ret_len,
651 const char *hostname,
652 const char *plugin, const char *plugin_instance,
653 const char *type, const char *type_instance)
654 {
655 int status;
657 assert (plugin != NULL);
658 assert (type != NULL);
660 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
661 {
662 if ((type_instance == NULL) || (strlen (type_instance) == 0))
663 status = snprintf (ret, ret_len, "%s/%s/%s",
664 hostname, plugin, type);
665 else
666 status = snprintf (ret, ret_len, "%s/%s/%s-%s",
667 hostname, plugin, type,
668 type_instance);
669 }
670 else
671 {
672 if ((type_instance == NULL) || (strlen (type_instance) == 0))
673 status = snprintf (ret, ret_len, "%s/%s-%s/%s",
674 hostname, plugin, plugin_instance,
675 type);
676 else
677 status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
678 hostname, plugin, plugin_instance,
679 type, type_instance);
680 }
682 if ((status < 1) || (status >= ret_len))
683 return (-1);
684 return (0);
685 } /* int format_name */
687 int parse_identifier (char *str, char **ret_host,
688 char **ret_plugin, char **ret_plugin_instance,
689 char **ret_type, char **ret_type_instance)
690 {
691 char *hostname = NULL;
692 char *plugin = NULL;
693 char *plugin_instance = NULL;
694 char *type = NULL;
695 char *type_instance = NULL;
697 hostname = str;
698 if (hostname == NULL)
699 return (-1);
701 plugin = strchr (hostname, '/');
702 if (plugin == NULL)
703 return (-1);
704 *plugin = '\0'; plugin++;
706 type = strchr (plugin, '/');
707 if (type == NULL)
708 return (-1);
709 *type = '\0'; type++;
711 plugin_instance = strchr (plugin, '-');
712 if (plugin_instance != NULL)
713 {
714 *plugin_instance = '\0';
715 plugin_instance++;
716 }
718 type_instance = strchr (type, '-');
719 if (type_instance != NULL)
720 {
721 *type_instance = '\0';
722 type_instance++;
723 }
725 *ret_host = hostname;
726 *ret_plugin = plugin;
727 *ret_plugin_instance = plugin_instance;
728 *ret_type = type;
729 *ret_type_instance = type_instance;
730 return (0);
731 } /* int parse_identifier */
733 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
734 {
735 int i;
736 char *dummy;
737 char *ptr;
738 char *saveptr;
740 i = -1;
741 dummy = buffer;
742 saveptr = NULL;
743 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
744 {
745 dummy = NULL;
747 if (i >= vl->values_len)
748 break;
750 if (i == -1)
751 {
752 if (strcmp ("N", ptr) == 0)
753 vl->time = time (NULL);
754 else
755 vl->time = (time_t) atoi (ptr);
756 }
757 else
758 {
759 if (strcmp ("U", ptr) == 0)
760 vl->values[i].gauge = NAN;
761 else if (ds->ds[i].type == DS_TYPE_COUNTER)
762 vl->values[i].counter = atoll (ptr);
763 else if (ds->ds[i].type == DS_TYPE_GAUGE)
764 vl->values[i].gauge = atof (ptr);
765 }
767 i++;
768 } /* while (strtok_r) */
770 if ((ptr != NULL) || (i != vl->values_len))
771 return (-1);
772 return (0);
773 } /* int parse_values */
775 #if !HAVE_GETPWNAM_R
776 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
777 size_t buflen, struct passwd **pwbufp)
778 {
779 int status = 0;
780 struct passwd *pw;
782 memset (pwbuf, '\0', sizeof (struct passwd));
784 pthread_mutex_lock (&getpwnam_r_lock);
786 do
787 {
788 pw = getpwnam (name);
789 if (pw == NULL)
790 {
791 status = (errno != 0) ? errno : ENOENT;
792 break;
793 }
795 #define GETPWNAM_COPY_MEMBER(member) \
796 if (pw->member != NULL) \
797 { \
798 int len = strlen (pw->member); \
799 if (len >= buflen) \
800 { \
801 status = ENOMEM; \
802 break; \
803 } \
804 sstrncpy (buf, pw->member, buflen); \
805 pwbuf->member = buf; \
806 buf += (len + 1); \
807 buflen -= (len + 1); \
808 }
809 GETPWNAM_COPY_MEMBER(pw_name);
810 GETPWNAM_COPY_MEMBER(pw_passwd);
811 GETPWNAM_COPY_MEMBER(pw_gecos);
812 GETPWNAM_COPY_MEMBER(pw_dir);
813 GETPWNAM_COPY_MEMBER(pw_shell);
815 pwbuf->pw_uid = pw->pw_uid;
816 pwbuf->pw_gid = pw->pw_gid;
818 if (pwbufp != NULL)
819 *pwbufp = pwbuf;
820 } while (0);
822 pthread_mutex_unlock (&getpwnam_r_lock);
824 return (status);
825 } /* int getpwnam_r */
826 #endif /* !HAVE_GETPWNAM_R */
828 int notification_init (notification_t *n, int severity, const char *message,
829 const char *host,
830 const char *plugin, const char *plugin_instance,
831 const char *type, const char *type_instance)
832 {
833 memset (n, '\0', sizeof (notification_t));
835 n->severity = severity;
837 if (message != NULL)
838 strncpy (n->message, message, sizeof (n->message));
839 if (host != NULL)
840 strncpy (n->host, host, sizeof (n->host));
841 if (plugin != NULL)
842 strncpy (n->plugin, plugin, sizeof (n->plugin));
843 if (plugin_instance != NULL)
844 strncpy (n->plugin_instance, plugin_instance,
845 sizeof (n->plugin_instance));
846 if (type != NULL)
847 strncpy (n->type, type, sizeof (n->type));
848 if (type_instance != NULL)
849 strncpy (n->type_instance, type_instance,
850 sizeof (n->type_instance));
852 n->message[sizeof (n->message) - 1] = '\0';
853 n->host[sizeof (n->host) - 1] = '\0';
854 n->plugin[sizeof (n->plugin) - 1] = '\0';
855 n->plugin_instance[sizeof (n->plugin_instance) - 1] = '\0';
856 n->type[sizeof (n->type) - 1] = '\0';
857 n->type_instance[sizeof (n->type_instance) - 1] = '\0';
859 return (0);
860 } /* int notification_init */