a2c4794d6d4642dfd2da75eef7747e87849904ca
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 char *sstrncpy (char *dest, const char *src, size_t n)
56 {
57 strncpy (dest, src, n);
58 dest[n - 1] = '\0';
60 return (dest);
61 } /* char *sstrncpy */
63 char *sstrdup (const char *s)
64 {
65 char *r;
67 if (s == NULL)
68 return (NULL);
70 if((r = strdup (s)) == NULL)
71 {
72 DEBUG ("Not enough memory.");
73 exit(3);
74 }
76 return (r);
77 }
79 /* Even though Posix requires "strerror_r" to return an "int",
80 * some systems (e.g. the GNU libc) return a "char *" _and_
81 * ignore the second argument ... -tokkee */
82 char *sstrerror (int errnum, char *buf, size_t buflen)
83 {
84 buf[0] = '\0';
86 #if !HAVE_STRERROR_R
87 {
88 char *temp;
90 pthread_mutex_lock (&strerror_r_lock);
92 temp = strerror (errnum);
93 strncpy (buf, temp, buflen);
95 pthread_mutex_unlock (&strerror_r_lock);
96 }
97 /* #endif !HAVE_STRERROR_R */
99 #elif STRERROR_R_CHAR_P
100 {
101 char *temp;
102 temp = strerror_r (errnum, buf, buflen);
103 if (buf[0] == '\0')
104 {
105 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
106 strncpy (buf, temp, buflen);
107 else
108 strncpy (buf, "strerror_r did not return "
109 "an error message", buflen);
110 }
111 }
112 /* #endif STRERROR_R_CHAR_P */
114 #else
115 if (strerror_r (errnum, buf, buflen) != 0)
116 {
117 snprintf (buf, buflen, "Error #%i; "
118 "Additionally, strerror_r failed.",
119 errnum);
120 }
121 #endif /* STRERROR_R_CHAR_P */
123 buf[buflen - 1] = '\0';
124 return (buf);
125 } /* char *sstrerror */
127 void *smalloc (size_t size)
128 {
129 void *r;
131 if ((r = malloc (size)) == NULL)
132 {
133 DEBUG("Not enough memory.");
134 exit(3);
135 }
137 return r;
138 }
140 #if 0
141 void sfree (void **ptr)
142 {
143 if (ptr == NULL)
144 return;
146 if (*ptr != NULL)
147 free (*ptr);
149 *ptr = NULL;
150 }
151 #endif
153 ssize_t sread (int fd, void *buf, size_t count)
154 {
155 char *ptr;
156 size_t nleft;
157 ssize_t status;
159 ptr = (char *) buf;
160 nleft = count;
162 while (nleft > 0)
163 {
164 status = read (fd, (void *) ptr, nleft);
166 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
167 continue;
169 if (status < 0)
170 return (status);
172 if (status == 0)
173 {
174 DEBUG ("Received EOF from fd %i. "
175 "Closing fd and returning error.",
176 fd);
177 close (fd);
178 return (-1);
179 }
181 assert ((0 > status) || (nleft >= (size_t)status));
183 nleft = nleft - status;
184 ptr = ptr + status;
185 }
187 return (0);
188 }
191 ssize_t swrite (int fd, const void *buf, size_t count)
192 {
193 const char *ptr;
194 size_t nleft;
195 ssize_t status;
197 ptr = (const char *) buf;
198 nleft = count;
200 while (nleft > 0)
201 {
202 status = write (fd, (const void *) ptr, nleft);
204 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
205 continue;
207 if (status < 0)
208 return (status);
210 nleft = nleft - status;
211 ptr = ptr + status;
212 }
214 return (0);
215 }
217 int strsplit (char *string, char **fields, size_t size)
218 {
219 size_t i;
220 char *ptr;
221 char *saveptr;
223 i = 0;
224 ptr = string;
225 saveptr = NULL;
226 while ((fields[i] = strtok_r (ptr, " \t", &saveptr)) != NULL)
227 {
228 ptr = NULL;
229 i++;
231 if (i >= size)
232 break;
233 }
235 return (i);
236 }
238 int strjoin (char *dst, size_t dst_len,
239 char **fields, size_t fields_num,
240 const char *sep)
241 {
242 size_t field_len;
243 size_t sep_len;
244 int i;
246 memset (dst, '\0', dst_len);
248 if (fields_num <= 0)
249 return (-1);
251 sep_len = 0;
252 if (sep != NULL)
253 sep_len = strlen (sep);
255 for (i = 0; i < (int)fields_num; i++)
256 {
257 if ((i > 0) && (sep_len > 0))
258 {
259 if (dst_len <= sep_len)
260 return (-1);
262 strncat (dst, sep, dst_len);
263 dst_len -= sep_len;
264 }
266 field_len = strlen (fields[i]);
268 if (dst_len <= field_len)
269 return (-1);
271 strncat (dst, fields[i], dst_len);
272 dst_len -= field_len;
273 }
275 return (strlen (dst));
276 }
278 int strsubstitute (char *str, char c_from, char c_to)
279 {
280 int ret;
282 if (str == NULL)
283 return (-1);
285 ret = 0;
286 while (*str != '\0')
287 {
288 if (*str == c_from)
289 {
290 *str = c_to;
291 ret++;
292 }
293 str++;
294 }
296 return (ret);
297 } /* int strsubstitute */
299 int escape_slashes (char *buf, int buf_len)
300 {
301 int i;
303 if (strcmp (buf, "/") == 0)
304 {
305 if (buf_len < 5)
306 return (-1);
308 strncpy (buf, "root", buf_len);
309 return (0);
310 }
312 if (buf_len <= 1)
313 return (0);
315 /* Move one to the left */
316 if (buf[0] == '/')
317 memmove (buf, buf + 1, buf_len - 1);
319 for (i = 0; i < buf_len - 1; i++)
320 {
321 if (buf[i] == '\0')
322 break;
323 else if (buf[i] == '/')
324 buf[i] = '_';
325 }
326 buf[i] = '\0';
328 return (0);
329 } /* int escape_slashes */
331 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
332 {
333 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
334 return (-2);
336 if ((tv0->tv_sec < tv1->tv_sec)
337 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
338 return (-1);
340 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
341 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
343 if (ret->tv_nsec < 0)
344 {
345 assert (ret->tv_sec > 0);
347 ret->tv_nsec += 1000000000;
348 ret->tv_sec -= 1;
349 }
351 return (0);
352 }
354 int check_create_dir (const char *file_orig)
355 {
356 struct stat statbuf;
358 char file_copy[512];
359 char dir[512];
360 int dir_len = 512;
361 char *fields[16];
362 int fields_num;
363 char *ptr;
364 char *saveptr;
365 int last_is_file = 1;
366 int path_is_absolute = 0;
367 int len;
368 int i;
370 /*
371 * Sanity checks first
372 */
373 if (file_orig == NULL)
374 return (-1);
376 if ((len = strlen (file_orig)) < 1)
377 return (-1);
378 else if (len >= 512)
379 return (-1);
381 /*
382 * If `file_orig' ends in a slash the last component is a directory,
383 * otherwise it's a file. Act accordingly..
384 */
385 if (file_orig[len - 1] == '/')
386 last_is_file = 0;
387 if (file_orig[0] == '/')
388 path_is_absolute = 1;
390 /*
391 * Create a copy for `strtok_r' to destroy
392 */
393 strncpy (file_copy, file_orig, 512);
394 file_copy[511] = '\0';
396 /*
397 * Break into components. This will eat up several slashes in a row and
398 * remove leading and trailing slashes..
399 */
400 ptr = file_copy;
401 saveptr = NULL;
402 fields_num = 0;
403 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
404 {
405 ptr = NULL;
406 fields_num++;
408 if (fields_num >= 16)
409 break;
410 }
412 /*
413 * For each component, do..
414 */
415 for (i = 0; i < (fields_num - last_is_file); i++)
416 {
417 /*
418 * Do not create directories that start with a dot. This
419 * prevents `../../' attacks and other likely malicious
420 * behavior.
421 */
422 if (fields[i][0] == '.')
423 {
424 ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
425 return (-2);
426 }
428 /*
429 * Join the components together again
430 */
431 dir[0] = '/';
432 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
433 fields, i + 1, "/") < 0)
434 {
435 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
436 return (-1);
437 }
439 if (stat (dir, &statbuf) == -1)
440 {
441 if (errno == ENOENT)
442 {
443 if (mkdir (dir, 0755) == -1)
444 {
445 char errbuf[1024];
446 ERROR ("check_create_dir: mkdir (%s): %s", dir,
447 sstrerror (errno,
448 errbuf, sizeof (errbuf)));
449 return (-1);
450 }
451 }
452 else
453 {
454 char errbuf[1024];
455 ERROR ("stat (%s): %s", dir,
456 sstrerror (errno, errbuf,
457 sizeof (errbuf)));
458 return (-1);
459 }
460 }
461 else if (!S_ISDIR (statbuf.st_mode))
462 {
463 ERROR ("stat (%s): Not a directory!", dir);
464 return (-1);
465 }
466 }
468 return (0);
469 } /* check_create_dir */
471 #ifdef HAVE_LIBKSTAT
472 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
473 {
474 char ident[128];
476 if (kc == NULL)
477 return (-1);
479 snprintf (ident, 128, "%s,%i,%s", module, instance, name);
480 ident[127] = '\0';
482 if (*ksp_ptr == NULL)
483 {
484 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
485 {
486 ERROR ("Cound not find kstat %s", ident);
487 return (-1);
488 }
490 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
491 {
492 WARNING ("kstat %s has wrong type", ident);
493 *ksp_ptr = NULL;
494 return (-1);
495 }
496 }
498 #ifdef assert
499 assert (*ksp_ptr != NULL);
500 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
501 #endif
503 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
504 {
505 WARNING ("kstat %s could not be read", ident);
506 return (-1);
507 }
509 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
510 {
511 WARNING ("kstat %s has wrong type", ident);
512 return (-1);
513 }
515 return (0);
516 }
518 long long get_kstat_value (kstat_t *ksp, char *name)
519 {
520 kstat_named_t *kn;
521 long long retval = -1LL;
523 #ifdef assert
524 assert (ksp != NULL);
525 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
526 #else
527 if (ksp == NULL)
528 {
529 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
530 return (-1LL);
531 }
532 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
533 {
534 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
535 return (-1LL);
536 }
537 #endif
539 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
540 return (retval);
542 if (kn->data_type == KSTAT_DATA_INT32)
543 retval = (long long) kn->value.i32;
544 else if (kn->data_type == KSTAT_DATA_UINT32)
545 retval = (long long) kn->value.ui32;
546 else if (kn->data_type == KSTAT_DATA_INT64)
547 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
548 else if (kn->data_type == KSTAT_DATA_UINT64)
549 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
550 else
551 WARNING ("get_kstat_value: Not a numeric value: %s", name);
553 return (retval);
554 }
555 #endif /* HAVE_LIBKSTAT */
557 unsigned long long ntohll (unsigned long long n)
558 {
559 #if __BYTE_ORDER == __BIG_ENDIAN
560 return (n);
561 #else
562 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
563 #endif
564 } /* unsigned long long ntohll */
566 unsigned long long htonll (unsigned long long n)
567 {
568 #if __BYTE_ORDER == __BIG_ENDIAN
569 return (n);
570 #else
571 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
572 #endif
573 } /* unsigned long long htonll */
575 #if FP_LAYOUT_NEED_NOTHING
576 /* Well, we need nothing.. */
577 /* #endif FP_LAYOUT_NEED_NOTHING */
579 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
580 # if FP_LAYOUT_NEED_ENDIANFLIP
581 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
582 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
583 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
584 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
585 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
586 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
587 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
588 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
589 # else
590 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
591 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
592 # endif
594 double ntohd (double d)
595 {
596 union
597 {
598 uint8_t byte[8];
599 uint64_t integer;
600 double floating;
601 } ret;
603 ret.floating = d;
605 /* NAN in x86 byte order */
606 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
607 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
608 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
609 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
610 {
611 return (NAN);
612 }
613 else
614 {
615 uint64_t tmp;
617 tmp = ret.integer;
618 ret.integer = FP_CONVERT (tmp);
619 return (ret.floating);
620 }
621 } /* double ntohd */
623 double htond (double d)
624 {
625 union
626 {
627 uint8_t byte[8];
628 uint64_t integer;
629 double floating;
630 } ret;
632 if (isnan (d))
633 {
634 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
635 ret.byte[4] = ret.byte[5] = 0x00;
636 ret.byte[6] = 0xf8;
637 ret.byte[7] = 0x7f;
638 return (ret.floating);
639 }
640 else
641 {
642 uint64_t tmp;
644 ret.floating = d;
645 tmp = FP_CONVERT (ret.integer);
646 ret.integer = tmp;
647 return (ret.floating);
648 }
649 } /* double htond */
650 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
652 int format_name (char *ret, int ret_len,
653 const char *hostname,
654 const char *plugin, const char *plugin_instance,
655 const char *type, const char *type_instance)
656 {
657 int status;
659 assert (plugin != NULL);
660 assert (type != NULL);
662 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
663 {
664 if ((type_instance == NULL) || (strlen (type_instance) == 0))
665 status = snprintf (ret, ret_len, "%s/%s/%s",
666 hostname, plugin, type);
667 else
668 status = snprintf (ret, ret_len, "%s/%s/%s-%s",
669 hostname, plugin, type,
670 type_instance);
671 }
672 else
673 {
674 if ((type_instance == NULL) || (strlen (type_instance) == 0))
675 status = snprintf (ret, ret_len, "%s/%s-%s/%s",
676 hostname, plugin, plugin_instance,
677 type);
678 else
679 status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
680 hostname, plugin, plugin_instance,
681 type, type_instance);
682 }
684 if ((status < 1) || (status >= ret_len))
685 return (-1);
686 return (0);
687 } /* int format_name */
689 int parse_identifier (char *str, char **ret_host,
690 char **ret_plugin, char **ret_plugin_instance,
691 char **ret_type, char **ret_type_instance)
692 {
693 char *hostname = NULL;
694 char *plugin = NULL;
695 char *plugin_instance = NULL;
696 char *type = NULL;
697 char *type_instance = NULL;
699 hostname = str;
700 if (hostname == NULL)
701 return (-1);
703 plugin = strchr (hostname, '/');
704 if (plugin == NULL)
705 return (-1);
706 *plugin = '\0'; plugin++;
708 type = strchr (plugin, '/');
709 if (type == NULL)
710 return (-1);
711 *type = '\0'; type++;
713 plugin_instance = strchr (plugin, '-');
714 if (plugin_instance != NULL)
715 {
716 *plugin_instance = '\0';
717 plugin_instance++;
718 }
720 type_instance = strchr (type, '-');
721 if (type_instance != NULL)
722 {
723 *type_instance = '\0';
724 type_instance++;
725 }
727 *ret_host = hostname;
728 *ret_plugin = plugin;
729 *ret_plugin_instance = plugin_instance;
730 *ret_type = type;
731 *ret_type_instance = type_instance;
732 return (0);
733 } /* int parse_identifier */
735 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
736 {
737 int i;
738 char *dummy;
739 char *ptr;
740 char *saveptr;
742 i = -1;
743 dummy = buffer;
744 saveptr = NULL;
745 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
746 {
747 dummy = NULL;
749 if (i >= vl->values_len)
750 break;
752 if (i == -1)
753 {
754 if (strcmp ("N", ptr) == 0)
755 vl->time = time (NULL);
756 else
757 vl->time = (time_t) atoi (ptr);
758 }
759 else
760 {
761 if (strcmp ("U", ptr) == 0)
762 vl->values[i].gauge = NAN;
763 else if (ds->ds[i].type == DS_TYPE_COUNTER)
764 vl->values[i].counter = atoll (ptr);
765 else if (ds->ds[i].type == DS_TYPE_GAUGE)
766 vl->values[i].gauge = atof (ptr);
767 }
769 i++;
770 } /* while (strtok_r) */
772 if ((ptr != NULL) || (i != vl->values_len))
773 return (-1);
774 return (0);
775 } /* int parse_values */
777 #if !HAVE_GETPWNAM_R
778 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
779 size_t buflen, struct passwd **pwbufp)
780 {
781 int status = 0;
782 struct passwd *pw;
784 memset (pwbuf, '\0', sizeof (struct passwd));
786 pthread_mutex_lock (&getpwnam_r_lock);
788 do
789 {
790 pw = getpwnam (name);
791 if (pw == NULL)
792 {
793 status = (errno != 0) ? errno : ENOENT;
794 break;
795 }
797 #define GETPWNAM_COPY_MEMBER(member) \
798 if (pw->member != NULL) \
799 { \
800 int len = strlen (pw->member); \
801 if (len >= buflen) \
802 { \
803 status = ENOMEM; \
804 break; \
805 } \
806 sstrncpy (buf, pw->member, buflen); \
807 pwbuf->member = buf; \
808 buf += (len + 1); \
809 buflen -= (len + 1); \
810 }
811 GETPWNAM_COPY_MEMBER(pw_name);
812 GETPWNAM_COPY_MEMBER(pw_passwd);
813 GETPWNAM_COPY_MEMBER(pw_gecos);
814 GETPWNAM_COPY_MEMBER(pw_dir);
815 GETPWNAM_COPY_MEMBER(pw_shell);
817 pwbuf->pw_uid = pw->pw_uid;
818 pwbuf->pw_gid = pw->pw_gid;
820 if (pwbufp != NULL)
821 *pwbufp = pwbuf;
822 } while (0);
824 pthread_mutex_unlock (&getpwnam_r_lock);
826 return (status);
827 } /* int getpwnam_r */
828 #endif /* !HAVE_GETPWNAM_R */
830 int notification_init (notification_t *n, int severity, const char *message,
831 const char *host,
832 const char *plugin, const char *plugin_instance,
833 const char *type, const char *type_instance)
834 {
835 memset (n, '\0', sizeof (notification_t));
837 n->severity = severity;
839 if (message != NULL)
840 strncpy (n->message, message, sizeof (n->message));
841 if (host != NULL)
842 strncpy (n->host, host, sizeof (n->host));
843 if (plugin != NULL)
844 strncpy (n->plugin, plugin, sizeof (n->plugin));
845 if (plugin_instance != NULL)
846 strncpy (n->plugin_instance, plugin_instance,
847 sizeof (n->plugin_instance));
848 if (type != NULL)
849 strncpy (n->type, type, sizeof (n->type));
850 if (type_instance != NULL)
851 strncpy (n->type_instance, type_instance,
852 sizeof (n->type_instance));
854 n->message[sizeof (n->message) - 1] = '\0';
855 n->host[sizeof (n->host) - 1] = '\0';
856 n->plugin[sizeof (n->plugin) - 1] = '\0';
857 n->plugin_instance[sizeof (n->plugin_instance) - 1] = '\0';
858 n->type[sizeof (n->type) - 1] = '\0';
859 n->type_instance[sizeof (n->type_instance) - 1] = '\0';
861 return (0);
862 } /* int notification_init */