1 /**
2 * collectd - src/common.c
3 * Copyright (C) 2005-2010 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 collectd.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>
23 **/
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32 #include "utils_cache.h"
34 #if HAVE_PTHREAD_H
35 # include <pthread.h>
36 #endif
38 #ifdef HAVE_MATH_H
39 # include <math.h>
40 #endif
42 /* for getaddrinfo */
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netdb.h>
47 #if HAVE_NETINET_IN_H
48 # include <netinet/in.h>
49 #endif
51 /* for ntohl and htonl */
52 #if HAVE_ARPA_INET_H
53 # include <arpa/inet.h>
54 #endif
56 #ifdef HAVE_LIBKSTAT
57 extern kstat_ctl_t *kc;
58 #endif
60 #if !HAVE_GETPWNAM_R
61 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
62 #endif
64 #if !HAVE_STRERROR_R
65 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
66 #endif
68 char *sstrncpy (char *dest, const char *src, size_t n)
69 {
70 strncpy (dest, src, n);
71 dest[n - 1] = '\0';
73 return (dest);
74 } /* char *sstrncpy */
76 int ssnprintf (char *dest, size_t n, const char *format, ...)
77 {
78 int ret = 0;
79 va_list ap;
81 va_start (ap, format);
82 ret = vsnprintf (dest, n, format, ap);
83 dest[n - 1] = '\0';
84 va_end (ap);
86 return (ret);
87 } /* int ssnprintf */
89 char *ssnprintf_alloc (char const *format, ...) /* {{{ */
90 {
91 char static_buffer[1024] = "";
92 char *alloc_buffer;
93 size_t alloc_buffer_size;
94 int status;
95 va_list ap;
97 /* Try printing into the static buffer. In many cases it will be
98 * sufficiently large and we can simply return a strdup() of this
99 * buffer. */
100 va_start (ap, format);
101 status = vsnprintf (static_buffer, sizeof (static_buffer), format, ap);
102 va_end (ap);
103 if (status < 0)
104 return (NULL);
106 /* "status" does not include the null byte. */
107 alloc_buffer_size = (size_t) (status + 1);
108 if (alloc_buffer_size <= sizeof (static_buffer))
109 return (strdup (static_buffer));
111 /* Allocate a buffer large enough to hold the string. */
112 alloc_buffer = malloc (alloc_buffer_size);
113 if (alloc_buffer == NULL)
114 return (NULL);
115 memset (alloc_buffer, 0, alloc_buffer_size);
117 /* Print again into this new buffer. */
118 va_start (ap, format);
119 status = vsnprintf (alloc_buffer, alloc_buffer_size, format, ap);
120 va_end (ap);
121 if (status < 0)
122 {
123 sfree (alloc_buffer);
124 return (NULL);
125 }
127 return (alloc_buffer);
128 } /* }}} char *ssnprintf_alloc */
130 char *sstrdup (const char *s)
131 {
132 char *r;
133 size_t sz;
135 if (s == NULL)
136 return (NULL);
138 /* Do not use `strdup' here, because it's not specified in POSIX. It's
139 * ``only'' an XSI extension. */
140 sz = strlen (s) + 1;
141 r = (char *) malloc (sizeof (char) * sz);
142 if (r == NULL)
143 {
144 ERROR ("sstrdup: Out of memory.");
145 exit (3);
146 }
147 memcpy (r, s, sizeof (char) * sz);
149 return (r);
150 } /* char *sstrdup */
152 /* Even though Posix requires "strerror_r" to return an "int",
153 * some systems (e.g. the GNU libc) return a "char *" _and_
154 * ignore the second argument ... -tokkee */
155 char *sstrerror (int errnum, char *buf, size_t buflen)
156 {
157 buf[0] = '\0';
159 #if !HAVE_STRERROR_R
160 {
161 char *temp;
163 pthread_mutex_lock (&strerror_r_lock);
165 temp = strerror (errnum);
166 sstrncpy (buf, temp, buflen);
168 pthread_mutex_unlock (&strerror_r_lock);
169 }
170 /* #endif !HAVE_STRERROR_R */
172 #elif STRERROR_R_CHAR_P
173 {
174 char *temp;
175 temp = strerror_r (errnum, buf, buflen);
176 if (buf[0] == '\0')
177 {
178 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
179 sstrncpy (buf, temp, buflen);
180 else
181 sstrncpy (buf, "strerror_r did not return "
182 "an error message", buflen);
183 }
184 }
185 /* #endif STRERROR_R_CHAR_P */
187 #else
188 if (strerror_r (errnum, buf, buflen) != 0)
189 {
190 ssnprintf (buf, buflen, "Error #%i; "
191 "Additionally, strerror_r failed.",
192 errnum);
193 }
194 #endif /* STRERROR_R_CHAR_P */
196 return (buf);
197 } /* char *sstrerror */
199 void *smalloc (size_t size)
200 {
201 void *r;
203 if ((r = malloc (size)) == NULL)
204 {
205 ERROR ("Not enough memory.");
206 exit (3);
207 }
209 return (r);
210 } /* void *smalloc */
212 #if 0
213 void sfree (void **ptr)
214 {
215 if (ptr == NULL)
216 return;
218 if (*ptr != NULL)
219 free (*ptr);
221 *ptr = NULL;
222 }
223 #endif
225 ssize_t sread (int fd, void *buf, size_t count)
226 {
227 char *ptr;
228 size_t nleft;
229 ssize_t status;
231 ptr = (char *) buf;
232 nleft = count;
234 while (nleft > 0)
235 {
236 status = read (fd, (void *) ptr, nleft);
238 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
239 continue;
241 if (status < 0)
242 return (status);
244 if (status == 0)
245 {
246 DEBUG ("Received EOF from fd %i. "
247 "Closing fd and returning error.",
248 fd);
249 close (fd);
250 return (-1);
251 }
253 assert ((0 > status) || (nleft >= (size_t)status));
255 nleft = nleft - status;
256 ptr = ptr + status;
257 }
259 return (0);
260 }
263 ssize_t swrite (int fd, const void *buf, size_t count)
264 {
265 const char *ptr;
266 size_t nleft;
267 ssize_t status;
269 ptr = (const char *) buf;
270 nleft = count;
272 while (nleft > 0)
273 {
274 status = write (fd, (const void *) ptr, nleft);
276 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
277 continue;
279 if (status < 0)
280 return (status);
282 nleft = nleft - status;
283 ptr = ptr + status;
284 }
286 return (0);
287 }
289 int strsplit (char *string, char **fields, size_t size)
290 {
291 size_t i;
292 char *ptr;
293 char *saveptr;
295 i = 0;
296 ptr = string;
297 saveptr = NULL;
298 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
299 {
300 ptr = NULL;
301 i++;
303 if (i >= size)
304 break;
305 }
307 return ((int) i);
308 }
310 int strjoin (char *dst, size_t dst_len,
311 char **fields, size_t fields_num,
312 const char *sep)
313 {
314 size_t field_len;
315 size_t sep_len;
316 int i;
318 memset (dst, '\0', dst_len);
320 if (fields_num <= 0)
321 return (-1);
323 sep_len = 0;
324 if (sep != NULL)
325 sep_len = strlen (sep);
327 for (i = 0; i < (int)fields_num; i++)
328 {
329 if ((i > 0) && (sep_len > 0))
330 {
331 if (dst_len <= sep_len)
332 return (-1);
334 strncat (dst, sep, dst_len);
335 dst_len -= sep_len;
336 }
338 field_len = strlen (fields[i]);
340 if (dst_len <= field_len)
341 return (-1);
343 strncat (dst, fields[i], dst_len);
344 dst_len -= field_len;
345 }
347 return (strlen (dst));
348 }
350 int strsubstitute (char *str, char c_from, char c_to)
351 {
352 int ret;
354 if (str == NULL)
355 return (-1);
357 ret = 0;
358 while (*str != '\0')
359 {
360 if (*str == c_from)
361 {
362 *str = c_to;
363 ret++;
364 }
365 str++;
366 }
368 return (ret);
369 } /* int strsubstitute */
371 int strunescape (char *buf, size_t buf_len)
372 {
373 size_t i;
375 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
376 {
377 if (buf[i] != '\\')
378 continue;
380 if ((i >= buf_len) || (buf[i + 1] == '\0')) {
381 ERROR ("string unescape: backslash found at end of string.");
382 return (-1);
383 }
385 switch (buf[i + 1]) {
386 case 't':
387 buf[i] = '\t';
388 break;
389 case 'n':
390 buf[i] = '\n';
391 break;
392 case 'r':
393 buf[i] = '\r';
394 break;
395 default:
396 buf[i] = buf[i + 1];
397 break;
398 }
400 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
401 }
402 return (0);
403 } /* int strunescape */
405 size_t strstripnewline (char *buffer)
406 {
407 size_t buffer_len = strlen (buffer);
409 while (buffer_len > 0)
410 {
411 if ((buffer[buffer_len - 1] != '\n')
412 && (buffer[buffer_len - 1] != '\r'))
413 break;
414 buffer[buffer_len] = 0;
415 buffer_len--;
416 }
418 return (buffer_len);
419 } /* size_t strstripnewline */
421 int escape_slashes (char *buf, int buf_len)
422 {
423 int i;
425 if (strcmp (buf, "/") == 0)
426 {
427 if (buf_len < 5)
428 return (-1);
430 strncpy (buf, "root", buf_len);
431 return (0);
432 }
434 if (buf_len <= 1)
435 return (0);
437 /* Move one to the left */
438 if (buf[0] == '/')
439 memmove (buf, buf + 1, buf_len - 1);
441 for (i = 0; i < buf_len - 1; i++)
442 {
443 if (buf[i] == '\0')
444 break;
445 else if (buf[i] == '/')
446 buf[i] = '_';
447 }
448 buf[i] = '\0';
450 return (0);
451 } /* int escape_slashes */
453 void replace_special (char *buffer, size_t buffer_size)
454 {
455 size_t i;
457 for (i = 0; i < buffer_size; i++)
458 {
459 if (buffer[i] == 0)
460 return;
461 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
462 buffer[i] = '_';
463 }
464 } /* void replace_special */
466 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
467 {
468 struct timeval *larger;
469 struct timeval *smaller;
471 int status;
473 NORMALIZE_TIMEVAL (tv0);
474 NORMALIZE_TIMEVAL (tv1);
476 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
477 {
478 if (delta != NULL) {
479 delta->tv_sec = 0;
480 delta->tv_usec = 0;
481 }
482 return (0);
483 }
485 if ((tv0.tv_sec < tv1.tv_sec)
486 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
487 {
488 larger = &tv1;
489 smaller = &tv0;
490 status = -1;
491 }
492 else
493 {
494 larger = &tv0;
495 smaller = &tv1;
496 status = 1;
497 }
499 if (delta != NULL) {
500 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
502 if (smaller->tv_usec <= larger->tv_usec)
503 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
504 else
505 {
506 --delta->tv_sec;
507 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
508 }
509 }
511 assert ((delta == NULL)
512 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
514 return (status);
515 } /* int timeval_cmp */
517 int check_create_dir (const char *file_orig)
518 {
519 struct stat statbuf;
521 char file_copy[512];
522 char dir[512];
523 int dir_len = 512;
524 char *fields[16];
525 int fields_num;
526 char *ptr;
527 char *saveptr;
528 int last_is_file = 1;
529 int path_is_absolute = 0;
530 size_t len;
531 int i;
533 /*
534 * Sanity checks first
535 */
536 if (file_orig == NULL)
537 return (-1);
539 if ((len = strlen (file_orig)) < 1)
540 return (-1);
541 else if (len >= sizeof (file_copy))
542 return (-1);
544 /*
545 * If `file_orig' ends in a slash the last component is a directory,
546 * otherwise it's a file. Act accordingly..
547 */
548 if (file_orig[len - 1] == '/')
549 last_is_file = 0;
550 if (file_orig[0] == '/')
551 path_is_absolute = 1;
553 /*
554 * Create a copy for `strtok_r' to destroy
555 */
556 sstrncpy (file_copy, file_orig, sizeof (file_copy));
558 /*
559 * Break into components. This will eat up several slashes in a row and
560 * remove leading and trailing slashes..
561 */
562 ptr = file_copy;
563 saveptr = NULL;
564 fields_num = 0;
565 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
566 {
567 ptr = NULL;
568 fields_num++;
570 if (fields_num >= 16)
571 break;
572 }
574 /*
575 * For each component, do..
576 */
577 for (i = 0; i < (fields_num - last_is_file); i++)
578 {
579 /*
580 * Do not create directories that start with a dot. This
581 * prevents `../../' attacks and other likely malicious
582 * behavior.
583 */
584 if (fields[i][0] == '.')
585 {
586 ERROR ("Cowardly refusing to create a directory that "
587 "begins with a `.' (dot): `%s'", file_orig);
588 return (-2);
589 }
591 /*
592 * Join the components together again
593 */
594 dir[0] = '/';
595 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
596 fields, i + 1, "/") < 0)
597 {
598 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
599 return (-1);
600 }
602 while (42) {
603 if ((stat (dir, &statbuf) == -1)
604 && (lstat (dir, &statbuf) == -1))
605 {
606 if (errno == ENOENT)
607 {
608 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
609 break;
611 /* this might happen, if a different thread created
612 * the directory in the meantime
613 * => call stat() again to check for S_ISDIR() */
614 if (EEXIST == errno)
615 continue;
617 char errbuf[1024];
618 ERROR ("check_create_dir: mkdir (%s): %s", dir,
619 sstrerror (errno,
620 errbuf, sizeof (errbuf)));
621 return (-1);
622 }
623 else
624 {
625 char errbuf[1024];
626 ERROR ("check_create_dir: stat (%s): %s", dir,
627 sstrerror (errno, errbuf,
628 sizeof (errbuf)));
629 return (-1);
630 }
631 }
632 else if (!S_ISDIR (statbuf.st_mode))
633 {
634 ERROR ("check_create_dir: `%s' exists but is not "
635 "a directory!", dir);
636 return (-1);
637 }
638 break;
639 }
640 }
642 return (0);
643 } /* check_create_dir */
645 #ifdef HAVE_LIBKSTAT
646 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
647 {
648 char ident[128];
650 *ksp_ptr = NULL;
652 if (kc == NULL)
653 return (-1);
655 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
657 *ksp_ptr = kstat_lookup (kc, module, instance, name);
658 if (*ksp_ptr == NULL)
659 {
660 ERROR ("get_kstat: Cound not find kstat %s", ident);
661 return (-1);
662 }
664 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
665 {
666 ERROR ("get_kstat: kstat %s has wrong type", ident);
667 *ksp_ptr = NULL;
668 return (-1);
669 }
671 #ifdef assert
672 assert (*ksp_ptr != NULL);
673 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
674 #endif
676 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
677 {
678 ERROR ("get_kstat: kstat %s could not be read", ident);
679 return (-1);
680 }
682 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
683 {
684 ERROR ("get_kstat: kstat %s has wrong type", ident);
685 return (-1);
686 }
688 return (0);
689 }
691 long long get_kstat_value (kstat_t *ksp, char *name)
692 {
693 kstat_named_t *kn;
694 long long retval = -1LL;
696 if (ksp == NULL)
697 {
698 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
699 return (-1LL);
700 }
701 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
702 {
703 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
704 "is not KSTAT_TYPE_NAMED (%#x).",
705 name,
706 (unsigned int) ksp->ks_type,
707 (unsigned int) KSTAT_TYPE_NAMED);
708 return (-1LL);
709 }
711 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
712 return (-1LL);
714 if (kn->data_type == KSTAT_DATA_INT32)
715 retval = (long long) kn->value.i32;
716 else if (kn->data_type == KSTAT_DATA_UINT32)
717 retval = (long long) kn->value.ui32;
718 else if (kn->data_type == KSTAT_DATA_INT64)
719 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
720 else if (kn->data_type == KSTAT_DATA_UINT64)
721 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
722 else
723 WARNING ("get_kstat_value: Not a numeric value: %s", name);
725 return (retval);
726 }
727 #endif /* HAVE_LIBKSTAT */
729 #ifndef HAVE_HTONLL
730 unsigned long long ntohll (unsigned long long n)
731 {
732 #if BYTE_ORDER == BIG_ENDIAN
733 return (n);
734 #else
735 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
736 #endif
737 } /* unsigned long long ntohll */
739 unsigned long long htonll (unsigned long long n)
740 {
741 #if BYTE_ORDER == BIG_ENDIAN
742 return (n);
743 #else
744 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
745 #endif
746 } /* unsigned long long htonll */
747 #endif /* HAVE_HTONLL */
749 #if FP_LAYOUT_NEED_NOTHING
750 /* Well, we need nothing.. */
751 /* #endif FP_LAYOUT_NEED_NOTHING */
753 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
754 # if FP_LAYOUT_NEED_ENDIANFLIP
755 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
756 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
757 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
758 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
759 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
760 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
761 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
762 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
763 # else
764 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
765 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
766 # endif
768 double ntohd (double d)
769 {
770 union
771 {
772 uint8_t byte[8];
773 uint64_t integer;
774 double floating;
775 } ret;
777 ret.floating = d;
779 /* NAN in x86 byte order */
780 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
781 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
782 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
783 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
784 {
785 return (NAN);
786 }
787 else
788 {
789 uint64_t tmp;
791 tmp = ret.integer;
792 ret.integer = FP_CONVERT (tmp);
793 return (ret.floating);
794 }
795 } /* double ntohd */
797 double htond (double d)
798 {
799 union
800 {
801 uint8_t byte[8];
802 uint64_t integer;
803 double floating;
804 } ret;
806 if (isnan (d))
807 {
808 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
809 ret.byte[4] = ret.byte[5] = 0x00;
810 ret.byte[6] = 0xf8;
811 ret.byte[7] = 0x7f;
812 return (ret.floating);
813 }
814 else
815 {
816 uint64_t tmp;
818 ret.floating = d;
819 tmp = FP_CONVERT (ret.integer);
820 ret.integer = tmp;
821 return (ret.floating);
822 }
823 } /* double htond */
824 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
826 int format_name (char *ret, int ret_len,
827 const char *hostname,
828 const char *plugin, const char *plugin_instance,
829 const char *type, const char *type_instance)
830 {
831 char *buffer;
832 size_t buffer_size;
834 buffer = ret;
835 buffer_size = (size_t) ret_len;
837 #define APPEND(str) do { \
838 size_t l = strlen (str); \
839 if (l >= buffer_size) \
840 return (ENOBUFS); \
841 memcpy (buffer, (str), l); \
842 buffer += l; buffer_size -= l; \
843 } while (0)
845 assert (plugin != NULL);
846 assert (type != NULL);
848 APPEND (hostname);
849 APPEND ("/");
850 APPEND (plugin);
851 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
852 {
853 APPEND ("-");
854 APPEND (plugin_instance);
855 }
856 APPEND ("/");
857 APPEND (type);
858 if ((type_instance != NULL) && (type_instance[0] != 0))
859 {
860 APPEND ("-");
861 APPEND (type_instance);
862 }
863 assert (buffer_size > 0);
864 buffer[0] = 0;
866 #undef APPEND
867 return (0);
868 } /* int format_name */
870 int format_values (char *ret, size_t ret_len, /* {{{ */
871 const data_set_t *ds, const value_list_t *vl,
872 _Bool store_rates)
873 {
874 size_t offset = 0;
875 int status;
876 int i;
877 gauge_t *rates = NULL;
879 assert (0 == strcmp (ds->type, vl->type));
881 memset (ret, 0, ret_len);
883 #define BUFFER_ADD(...) do { \
884 status = ssnprintf (ret + offset, ret_len - offset, \
885 __VA_ARGS__); \
886 if (status < 1) \
887 { \
888 sfree (rates); \
889 return (-1); \
890 } \
891 else if (((size_t) status) >= (ret_len - offset)) \
892 { \
893 sfree (rates); \
894 return (-1); \
895 } \
896 else \
897 offset += ((size_t) status); \
898 } while (0)
900 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
902 for (i = 0; i < ds->ds_num; i++)
903 {
904 if (ds->ds[i].type == DS_TYPE_GAUGE)
905 BUFFER_ADD (":%f", vl->values[i].gauge);
906 else if (store_rates)
907 {
908 if (rates == NULL)
909 rates = uc_get_rate (ds, vl);
910 if (rates == NULL)
911 {
912 WARNING ("format_values: "
913 "uc_get_rate failed.");
914 return (-1);
915 }
916 BUFFER_ADD (":%g", rates[i]);
917 }
918 else if (ds->ds[i].type == DS_TYPE_COUNTER)
919 BUFFER_ADD (":%llu", vl->values[i].counter);
920 else if (ds->ds[i].type == DS_TYPE_DERIVE)
921 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
922 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
923 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
924 else
925 {
926 ERROR ("format_values plugin: Unknown data source type: %i",
927 ds->ds[i].type);
928 sfree (rates);
929 return (-1);
930 }
931 } /* for ds->ds_num */
933 #undef BUFFER_ADD
935 sfree (rates);
936 return (0);
937 } /* }}} int format_values */
939 int parse_identifier (char *str, char **ret_host,
940 char **ret_plugin, char **ret_plugin_instance,
941 char **ret_type, char **ret_type_instance)
942 {
943 char *hostname = NULL;
944 char *plugin = NULL;
945 char *plugin_instance = NULL;
946 char *type = NULL;
947 char *type_instance = NULL;
949 hostname = str;
950 if (hostname == NULL)
951 return (-1);
953 plugin = strchr (hostname, '/');
954 if (plugin == NULL)
955 return (-1);
956 *plugin = '\0'; plugin++;
958 type = strchr (plugin, '/');
959 if (type == NULL)
960 return (-1);
961 *type = '\0'; type++;
963 plugin_instance = strchr (plugin, '-');
964 if (plugin_instance != NULL)
965 {
966 *plugin_instance = '\0';
967 plugin_instance++;
968 }
970 type_instance = strchr (type, '-');
971 if (type_instance != NULL)
972 {
973 *type_instance = '\0';
974 type_instance++;
975 }
977 *ret_host = hostname;
978 *ret_plugin = plugin;
979 *ret_plugin_instance = plugin_instance;
980 *ret_type = type;
981 *ret_type_instance = type_instance;
982 return (0);
983 } /* int parse_identifier */
985 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
986 {
987 char str_copy[6 * DATA_MAX_NAME_LEN];
988 char *host = NULL;
989 char *plugin = NULL;
990 char *plugin_instance = NULL;
991 char *type = NULL;
992 char *type_instance = NULL;
993 int status;
995 if ((str == NULL) || (vl == NULL))
996 return (EINVAL);
998 sstrncpy (str_copy, str, sizeof (str_copy));
1000 status = parse_identifier (str_copy, &host,
1001 &plugin, &plugin_instance,
1002 &type, &type_instance);
1003 if (status != 0)
1004 return (status);
1006 sstrncpy (vl->host, host, sizeof (vl->host));
1007 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1008 sstrncpy (vl->plugin_instance,
1009 (plugin_instance != NULL) ? plugin_instance : "",
1010 sizeof (vl->plugin_instance));
1011 sstrncpy (vl->type, type, sizeof (vl->type));
1012 sstrncpy (vl->type_instance,
1013 (type_instance != NULL) ? type_instance : "",
1014 sizeof (vl->type_instance));
1016 return (0);
1017 } /* }}} int parse_identifier_vl */
1019 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1020 {
1021 char *value;
1022 char *endptr = NULL;
1023 size_t value_len;
1025 if (value_orig == NULL)
1026 return (EINVAL);
1028 value = strdup (value_orig);
1029 if (value == NULL)
1030 return (ENOMEM);
1031 value_len = strlen (value);
1033 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1034 {
1035 value[value_len - 1] = 0;
1036 value_len--;
1037 }
1039 switch (ds_type)
1040 {
1041 case DS_TYPE_COUNTER:
1042 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1043 break;
1045 case DS_TYPE_GAUGE:
1046 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1047 break;
1049 case DS_TYPE_DERIVE:
1050 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1051 break;
1053 case DS_TYPE_ABSOLUTE:
1054 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1055 break;
1057 default:
1058 sfree (value);
1059 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1060 return -1;
1061 }
1063 if (value == endptr) {
1064 sfree (value);
1065 ERROR ("parse_value: Failed to parse string as %s: %s.",
1066 DS_TYPE_TO_STRING (ds_type), value);
1067 return -1;
1068 }
1069 else if ((NULL != endptr) && ('\0' != *endptr))
1070 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1071 "Input string was \"%s\".",
1072 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1074 sfree (value);
1075 return 0;
1076 } /* int parse_value */
1078 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1079 {
1080 int i;
1081 char *dummy;
1082 char *ptr;
1083 char *saveptr;
1085 i = -1;
1086 dummy = buffer;
1087 saveptr = NULL;
1088 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1089 {
1090 dummy = NULL;
1092 if (i >= vl->values_len)
1093 {
1094 /* Make sure i is invalid. */
1095 i = vl->values_len + 1;
1096 break;
1097 }
1099 if (i == -1)
1100 {
1101 if (strcmp ("N", ptr) == 0)
1102 vl->time = cdtime ();
1103 else
1104 {
1105 char *endptr = NULL;
1106 double tmp;
1108 errno = 0;
1109 tmp = strtod (ptr, &endptr);
1110 if ((errno != 0) /* Overflow */
1111 || (endptr == ptr) /* Invalid string */
1112 || (endptr == NULL) /* This should not happen */
1113 || (*endptr != 0)) /* Trailing chars */
1114 return (-1);
1116 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1117 }
1118 }
1119 else
1120 {
1121 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1122 vl->values[i].gauge = NAN;
1123 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1124 return -1;
1125 }
1127 i++;
1128 } /* while (strtok_r) */
1130 if ((ptr != NULL) || (i != vl->values_len))
1131 return (-1);
1132 return (0);
1133 } /* int parse_values */
1135 #if !HAVE_GETPWNAM_R
1136 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1137 size_t buflen, struct passwd **pwbufp)
1138 {
1139 int status = 0;
1140 struct passwd *pw;
1142 memset (pwbuf, '\0', sizeof (struct passwd));
1144 pthread_mutex_lock (&getpwnam_r_lock);
1146 do
1147 {
1148 pw = getpwnam (name);
1149 if (pw == NULL)
1150 {
1151 status = (errno != 0) ? errno : ENOENT;
1152 break;
1153 }
1155 #define GETPWNAM_COPY_MEMBER(member) \
1156 if (pw->member != NULL) \
1157 { \
1158 int len = strlen (pw->member); \
1159 if (len >= buflen) \
1160 { \
1161 status = ENOMEM; \
1162 break; \
1163 } \
1164 sstrncpy (buf, pw->member, buflen); \
1165 pwbuf->member = buf; \
1166 buf += (len + 1); \
1167 buflen -= (len + 1); \
1168 }
1169 GETPWNAM_COPY_MEMBER(pw_name);
1170 GETPWNAM_COPY_MEMBER(pw_passwd);
1171 GETPWNAM_COPY_MEMBER(pw_gecos);
1172 GETPWNAM_COPY_MEMBER(pw_dir);
1173 GETPWNAM_COPY_MEMBER(pw_shell);
1175 pwbuf->pw_uid = pw->pw_uid;
1176 pwbuf->pw_gid = pw->pw_gid;
1178 if (pwbufp != NULL)
1179 *pwbufp = pwbuf;
1180 } while (0);
1182 pthread_mutex_unlock (&getpwnam_r_lock);
1184 return (status);
1185 } /* int getpwnam_r */
1186 #endif /* !HAVE_GETPWNAM_R */
1188 int notification_init (notification_t *n, int severity, const char *message,
1189 const char *host,
1190 const char *plugin, const char *plugin_instance,
1191 const char *type, const char *type_instance)
1192 {
1193 memset (n, '\0', sizeof (notification_t));
1195 n->severity = severity;
1197 if (message != NULL)
1198 sstrncpy (n->message, message, sizeof (n->message));
1199 if (host != NULL)
1200 sstrncpy (n->host, host, sizeof (n->host));
1201 if (plugin != NULL)
1202 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1203 if (plugin_instance != NULL)
1204 sstrncpy (n->plugin_instance, plugin_instance,
1205 sizeof (n->plugin_instance));
1206 if (type != NULL)
1207 sstrncpy (n->type, type, sizeof (n->type));
1208 if (type_instance != NULL)
1209 sstrncpy (n->type_instance, type_instance,
1210 sizeof (n->type_instance));
1212 return (0);
1213 } /* int notification_init */
1215 int walk_directory (const char *dir, dirwalk_callback_f callback,
1216 void *user_data, int include_hidden)
1217 {
1218 struct dirent *ent;
1219 DIR *dh;
1220 int success;
1221 int failure;
1223 success = 0;
1224 failure = 0;
1226 if ((dh = opendir (dir)) == NULL)
1227 {
1228 char errbuf[1024];
1229 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1230 sstrerror (errno, errbuf, sizeof (errbuf)));
1231 return -1;
1232 }
1234 while ((ent = readdir (dh)) != NULL)
1235 {
1236 int status;
1238 if (include_hidden)
1239 {
1240 if ((strcmp (".", ent->d_name) == 0)
1241 || (strcmp ("..", ent->d_name) == 0))
1242 continue;
1243 }
1244 else /* if (!include_hidden) */
1245 {
1246 if (ent->d_name[0]=='.')
1247 continue;
1248 }
1250 status = (*callback) (dir, ent->d_name, user_data);
1251 if (status != 0)
1252 failure++;
1253 else
1254 success++;
1255 }
1257 closedir (dh);
1259 if ((success == 0) && (failure > 0))
1260 return (-1);
1261 return (0);
1262 }
1264 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1265 {
1266 FILE *fh;
1267 ssize_t ret;
1269 fh = fopen (filename, "r");
1270 if (fh == NULL)
1271 return (-1);
1273 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1274 if ((ret == 0) && (ferror (fh) != 0))
1275 {
1276 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1277 filename);
1278 ret = -1;
1279 }
1281 fclose(fh);
1282 return (ret);
1283 }
1285 counter_t counter_diff (counter_t old_value, counter_t new_value)
1286 {
1287 counter_t diff;
1289 if (old_value > new_value)
1290 {
1291 if (old_value <= 4294967295U)
1292 diff = (4294967295U - old_value) + new_value;
1293 else
1294 diff = (18446744073709551615ULL - old_value)
1295 + new_value;
1296 }
1297 else
1298 {
1299 diff = new_value - old_value;
1300 }
1302 return (diff);
1303 } /* counter_t counter_diff */
1305 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1306 rate_to_value_state_t *state,
1307 int ds_type, cdtime_t t)
1308 {
1309 gauge_t delta_gauge;
1310 cdtime_t delta_t;
1312 if (ds_type == DS_TYPE_GAUGE)
1313 {
1314 state->last_value.gauge = rate;
1315 state->last_time = t;
1317 *ret_value = state->last_value;
1318 return (0);
1319 }
1321 /* Counter and absolute can't handle negative rates. Reset "last time"
1322 * to zero, so that the next valid rate will re-initialize the
1323 * structure. */
1324 if ((rate < 0.0)
1325 && ((ds_type == DS_TYPE_COUNTER)
1326 || (ds_type == DS_TYPE_ABSOLUTE)))
1327 {
1328 memset (state, 0, sizeof (*state));
1329 return (EINVAL);
1330 }
1332 /* Another invalid state: The time is not increasing. */
1333 if (t <= state->last_time)
1334 {
1335 memset (state, 0, sizeof (*state));
1336 return (EINVAL);
1337 }
1339 delta_t = t - state->last_time;
1340 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1342 /* Previous value is invalid. */
1343 if (state->last_time == 0) /* {{{ */
1344 {
1345 if (ds_type == DS_TYPE_DERIVE)
1346 {
1347 state->last_value.derive = (derive_t) rate;
1348 state->residual = rate - ((gauge_t) state->last_value.derive);
1349 }
1350 else if (ds_type == DS_TYPE_COUNTER)
1351 {
1352 state->last_value.counter = (counter_t) rate;
1353 state->residual = rate - ((gauge_t) state->last_value.counter);
1354 }
1355 else if (ds_type == DS_TYPE_ABSOLUTE)
1356 {
1357 state->last_value.absolute = (absolute_t) rate;
1358 state->residual = rate - ((gauge_t) state->last_value.absolute);
1359 }
1360 else
1361 {
1362 assert (23 == 42);
1363 }
1365 state->last_time = t;
1366 return (EAGAIN);
1367 } /* }}} */
1369 if (ds_type == DS_TYPE_DERIVE)
1370 {
1371 derive_t delta_derive = (derive_t) delta_gauge;
1373 state->last_value.derive += delta_derive;
1374 state->residual = delta_gauge - ((gauge_t) delta_derive);
1375 }
1376 else if (ds_type == DS_TYPE_COUNTER)
1377 {
1378 counter_t delta_counter = (counter_t) delta_gauge;
1380 state->last_value.counter += delta_counter;
1381 state->residual = delta_gauge - ((gauge_t) delta_counter);
1382 }
1383 else if (ds_type == DS_TYPE_ABSOLUTE)
1384 {
1385 absolute_t delta_absolute = (absolute_t) delta_gauge;
1387 state->last_value.absolute = delta_absolute;
1388 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1389 }
1390 else
1391 {
1392 assert (23 == 42);
1393 }
1395 state->last_time = t;
1396 *ret_value = state->last_value;
1397 return (0);
1398 } /* }}} value_t rate_to_value */
1400 int service_name_to_port_number (const char *service_name)
1401 {
1402 struct addrinfo *ai_list;
1403 struct addrinfo *ai_ptr;
1404 struct addrinfo ai_hints;
1405 int status;
1406 int service_number;
1408 if (service_name == NULL)
1409 return (-1);
1411 ai_list = NULL;
1412 memset (&ai_hints, 0, sizeof (ai_hints));
1413 ai_hints.ai_family = AF_UNSPEC;
1415 status = getaddrinfo (/* node = */ NULL, service_name,
1416 &ai_hints, &ai_list);
1417 if (status != 0)
1418 {
1419 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1420 gai_strerror (status));
1421 return (-1);
1422 }
1424 service_number = -1;
1425 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1426 {
1427 if (ai_ptr->ai_family == AF_INET)
1428 {
1429 struct sockaddr_in *sa;
1431 sa = (void *) ai_ptr->ai_addr;
1432 service_number = (int) ntohs (sa->sin_port);
1433 }
1434 else if (ai_ptr->ai_family == AF_INET6)
1435 {
1436 struct sockaddr_in6 *sa;
1438 sa = (void *) ai_ptr->ai_addr;
1439 service_number = (int) ntohs (sa->sin6_port);
1440 }
1442 if ((service_number > 0) && (service_number <= 65535))
1443 break;
1444 }
1446 freeaddrinfo (ai_list);
1448 if ((service_number > 0) && (service_number <= 65535))
1449 return (service_number);
1450 return (-1);
1451 } /* int service_name_to_port_number */
1453 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1454 {
1455 derive_t tmp;
1456 char *endptr;
1458 if ((string == NULL) || (ret_value == NULL))
1459 return (EINVAL);
1461 errno = 0;
1462 endptr = NULL;
1463 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1464 if ((endptr == string) || (errno != 0))
1465 return (-1);
1467 *ret_value = tmp;
1468 return (0);
1469 } /* }}} int strtoderive */
1471 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1472 {
1473 char **array;
1474 size_t array_len = *ret_array_len;
1476 if (str == NULL)
1477 return (EINVAL);
1479 array = realloc (*ret_array,
1480 (array_len + 1) * sizeof (*array));
1481 if (array == NULL)
1482 return (ENOMEM);
1483 *ret_array = array;
1485 array[array_len] = strdup (str);
1486 if (array[array_len] == NULL)
1487 return (ENOMEM);
1489 array_len++;
1490 *ret_array_len = array_len;
1491 return (0);
1492 } /* }}} int strarray_add */
1494 void strarray_free (char **array, size_t array_len) /* {{{ */
1495 {
1496 size_t i;
1498 for (i = 0; i < array_len; i++)
1499 sfree (array[i]);
1500 sfree (array);
1501 } /* }}} void strarray_free */