1 /**
2 * collectd - src/common.c
3 * Copyright (C) 2005-2014 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 *buffer, size_t buffer_size)
422 {
423 int i;
424 size_t buffer_len;
426 buffer_len = strlen (buffer);
428 if (buffer_len <= 1)
429 {
430 if (strcmp ("/", buffer) == 0)
431 {
432 if (buffer_size < 5)
433 return (-1);
434 sstrncpy (buffer, "root", buffer_size);
435 }
436 return (0);
437 }
439 /* Move one to the left */
440 if (buffer[0] == '/')
441 {
442 memmove (buffer, buffer + 1, buffer_len);
443 buffer_len--;
444 }
446 for (i = 0; i < buffer_len - 1; i++)
447 {
448 if (buffer[i] == '/')
449 buffer[i] = '_';
450 }
452 return (0);
453 } /* int escape_slashes */
455 void replace_special (char *buffer, size_t buffer_size)
456 {
457 size_t i;
459 for (i = 0; i < buffer_size; i++)
460 {
461 if (buffer[i] == 0)
462 return;
463 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
464 buffer[i] = '_';
465 }
466 } /* void replace_special */
468 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
469 {
470 struct timeval *larger;
471 struct timeval *smaller;
473 int status;
475 NORMALIZE_TIMEVAL (tv0);
476 NORMALIZE_TIMEVAL (tv1);
478 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
479 {
480 if (delta != NULL) {
481 delta->tv_sec = 0;
482 delta->tv_usec = 0;
483 }
484 return (0);
485 }
487 if ((tv0.tv_sec < tv1.tv_sec)
488 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
489 {
490 larger = &tv1;
491 smaller = &tv0;
492 status = -1;
493 }
494 else
495 {
496 larger = &tv0;
497 smaller = &tv1;
498 status = 1;
499 }
501 if (delta != NULL) {
502 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
504 if (smaller->tv_usec <= larger->tv_usec)
505 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
506 else
507 {
508 --delta->tv_sec;
509 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
510 }
511 }
513 assert ((delta == NULL)
514 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
516 return (status);
517 } /* int timeval_cmp */
519 int check_create_dir (const char *file_orig)
520 {
521 struct stat statbuf;
523 char file_copy[512];
524 char dir[512];
525 int dir_len = 512;
526 char *fields[16];
527 int fields_num;
528 char *ptr;
529 char *saveptr;
530 int last_is_file = 1;
531 int path_is_absolute = 0;
532 size_t len;
533 int i;
535 /*
536 * Sanity checks first
537 */
538 if (file_orig == NULL)
539 return (-1);
541 if ((len = strlen (file_orig)) < 1)
542 return (-1);
543 else if (len >= sizeof (file_copy))
544 return (-1);
546 /*
547 * If `file_orig' ends in a slash the last component is a directory,
548 * otherwise it's a file. Act accordingly..
549 */
550 if (file_orig[len - 1] == '/')
551 last_is_file = 0;
552 if (file_orig[0] == '/')
553 path_is_absolute = 1;
555 /*
556 * Create a copy for `strtok_r' to destroy
557 */
558 sstrncpy (file_copy, file_orig, sizeof (file_copy));
560 /*
561 * Break into components. This will eat up several slashes in a row and
562 * remove leading and trailing slashes..
563 */
564 ptr = file_copy;
565 saveptr = NULL;
566 fields_num = 0;
567 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
568 {
569 ptr = NULL;
570 fields_num++;
572 if (fields_num >= 16)
573 break;
574 }
576 /*
577 * For each component, do..
578 */
579 for (i = 0; i < (fields_num - last_is_file); i++)
580 {
581 /*
582 * Do not create directories that start with a dot. This
583 * prevents `../../' attacks and other likely malicious
584 * behavior.
585 */
586 if (fields[i][0] == '.')
587 {
588 ERROR ("Cowardly refusing to create a directory that "
589 "begins with a `.' (dot): `%s'", file_orig);
590 return (-2);
591 }
593 /*
594 * Join the components together again
595 */
596 dir[0] = '/';
597 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
598 fields, i + 1, "/") < 0)
599 {
600 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
601 return (-1);
602 }
604 while (42) {
605 if ((stat (dir, &statbuf) == -1)
606 && (lstat (dir, &statbuf) == -1))
607 {
608 if (errno == ENOENT)
609 {
610 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
611 break;
613 /* this might happen, if a different thread created
614 * the directory in the meantime
615 * => call stat() again to check for S_ISDIR() */
616 if (EEXIST == errno)
617 continue;
619 char errbuf[1024];
620 ERROR ("check_create_dir: mkdir (%s): %s", dir,
621 sstrerror (errno,
622 errbuf, sizeof (errbuf)));
623 return (-1);
624 }
625 else
626 {
627 char errbuf[1024];
628 ERROR ("check_create_dir: stat (%s): %s", dir,
629 sstrerror (errno, errbuf,
630 sizeof (errbuf)));
631 return (-1);
632 }
633 }
634 else if (!S_ISDIR (statbuf.st_mode))
635 {
636 ERROR ("check_create_dir: `%s' exists but is not "
637 "a directory!", dir);
638 return (-1);
639 }
640 break;
641 }
642 }
644 return (0);
645 } /* check_create_dir */
647 #ifdef HAVE_LIBKSTAT
648 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
649 {
650 char ident[128];
652 *ksp_ptr = NULL;
654 if (kc == NULL)
655 return (-1);
657 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
659 *ksp_ptr = kstat_lookup (kc, module, instance, name);
660 if (*ksp_ptr == NULL)
661 {
662 ERROR ("get_kstat: Cound not find kstat %s", ident);
663 return (-1);
664 }
666 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
667 {
668 ERROR ("get_kstat: kstat %s has wrong type", ident);
669 *ksp_ptr = NULL;
670 return (-1);
671 }
673 #ifdef assert
674 assert (*ksp_ptr != NULL);
675 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
676 #endif
678 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
679 {
680 ERROR ("get_kstat: kstat %s could not be read", ident);
681 return (-1);
682 }
684 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
685 {
686 ERROR ("get_kstat: kstat %s has wrong type", ident);
687 return (-1);
688 }
690 return (0);
691 }
693 long long get_kstat_value (kstat_t *ksp, char *name)
694 {
695 kstat_named_t *kn;
696 long long retval = -1LL;
698 if (ksp == NULL)
699 {
700 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
701 return (-1LL);
702 }
703 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
704 {
705 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
706 "is not KSTAT_TYPE_NAMED (%#x).",
707 name,
708 (unsigned int) ksp->ks_type,
709 (unsigned int) KSTAT_TYPE_NAMED);
710 return (-1LL);
711 }
713 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
714 return (-1LL);
716 if (kn->data_type == KSTAT_DATA_INT32)
717 retval = (long long) kn->value.i32;
718 else if (kn->data_type == KSTAT_DATA_UINT32)
719 retval = (long long) kn->value.ui32;
720 else if (kn->data_type == KSTAT_DATA_INT64)
721 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
722 else if (kn->data_type == KSTAT_DATA_UINT64)
723 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
724 else
725 WARNING ("get_kstat_value: Not a numeric value: %s", name);
727 return (retval);
728 }
729 #endif /* HAVE_LIBKSTAT */
731 #ifndef HAVE_HTONLL
732 unsigned long long ntohll (unsigned long long n)
733 {
734 #if BYTE_ORDER == BIG_ENDIAN
735 return (n);
736 #else
737 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
738 #endif
739 } /* unsigned long long ntohll */
741 unsigned long long htonll (unsigned long long n)
742 {
743 #if BYTE_ORDER == BIG_ENDIAN
744 return (n);
745 #else
746 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
747 #endif
748 } /* unsigned long long htonll */
749 #endif /* HAVE_HTONLL */
751 #if FP_LAYOUT_NEED_NOTHING
752 /* Well, we need nothing.. */
753 /* #endif FP_LAYOUT_NEED_NOTHING */
755 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
756 # if FP_LAYOUT_NEED_ENDIANFLIP
757 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
758 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
759 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
760 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
761 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
762 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
763 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
764 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
765 # else
766 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
767 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
768 # endif
770 double ntohd (double d)
771 {
772 union
773 {
774 uint8_t byte[8];
775 uint64_t integer;
776 double floating;
777 } ret;
779 ret.floating = d;
781 /* NAN in x86 byte order */
782 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
783 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
784 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
785 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
786 {
787 return (NAN);
788 }
789 else
790 {
791 uint64_t tmp;
793 tmp = ret.integer;
794 ret.integer = FP_CONVERT (tmp);
795 return (ret.floating);
796 }
797 } /* double ntohd */
799 double htond (double d)
800 {
801 union
802 {
803 uint8_t byte[8];
804 uint64_t integer;
805 double floating;
806 } ret;
808 if (isnan (d))
809 {
810 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
811 ret.byte[4] = ret.byte[5] = 0x00;
812 ret.byte[6] = 0xf8;
813 ret.byte[7] = 0x7f;
814 return (ret.floating);
815 }
816 else
817 {
818 uint64_t tmp;
820 ret.floating = d;
821 tmp = FP_CONVERT (ret.integer);
822 ret.integer = tmp;
823 return (ret.floating);
824 }
825 } /* double htond */
826 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
828 int format_name (char *ret, int ret_len,
829 const char *hostname,
830 const char *plugin, const char *plugin_instance,
831 const char *type, const char *type_instance)
832 {
833 char *buffer;
834 size_t buffer_size;
836 buffer = ret;
837 buffer_size = (size_t) ret_len;
839 #define APPEND(str) do { \
840 size_t l = strlen (str); \
841 if (l >= buffer_size) \
842 return (ENOBUFS); \
843 memcpy (buffer, (str), l); \
844 buffer += l; buffer_size -= l; \
845 } while (0)
847 assert (plugin != NULL);
848 assert (type != NULL);
850 APPEND (hostname);
851 APPEND ("/");
852 APPEND (plugin);
853 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
854 {
855 APPEND ("-");
856 APPEND (plugin_instance);
857 }
858 APPEND ("/");
859 APPEND (type);
860 if ((type_instance != NULL) && (type_instance[0] != 0))
861 {
862 APPEND ("-");
863 APPEND (type_instance);
864 }
865 assert (buffer_size > 0);
866 buffer[0] = 0;
868 #undef APPEND
869 return (0);
870 } /* int format_name */
872 int format_values (char *ret, size_t ret_len, /* {{{ */
873 const data_set_t *ds, const value_list_t *vl,
874 _Bool store_rates)
875 {
876 size_t offset = 0;
877 int status;
878 int i;
879 gauge_t *rates = NULL;
881 assert (0 == strcmp (ds->type, vl->type));
883 memset (ret, 0, ret_len);
885 #define BUFFER_ADD(...) do { \
886 status = ssnprintf (ret + offset, ret_len - offset, \
887 __VA_ARGS__); \
888 if (status < 1) \
889 { \
890 sfree (rates); \
891 return (-1); \
892 } \
893 else if (((size_t) status) >= (ret_len - offset)) \
894 { \
895 sfree (rates); \
896 return (-1); \
897 } \
898 else \
899 offset += ((size_t) status); \
900 } while (0)
902 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
904 for (i = 0; i < ds->ds_num; i++)
905 {
906 if (ds->ds[i].type == DS_TYPE_GAUGE)
907 BUFFER_ADD (":%f", vl->values[i].gauge);
908 else if (store_rates)
909 {
910 if (rates == NULL)
911 rates = uc_get_rate (ds, vl);
912 if (rates == NULL)
913 {
914 WARNING ("format_values: "
915 "uc_get_rate failed.");
916 return (-1);
917 }
918 BUFFER_ADD (":%g", rates[i]);
919 }
920 else if (ds->ds[i].type == DS_TYPE_COUNTER)
921 BUFFER_ADD (":%llu", vl->values[i].counter);
922 else if (ds->ds[i].type == DS_TYPE_DERIVE)
923 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
924 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
925 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
926 else
927 {
928 ERROR ("format_values plugin: Unknown data source type: %i",
929 ds->ds[i].type);
930 sfree (rates);
931 return (-1);
932 }
933 } /* for ds->ds_num */
935 #undef BUFFER_ADD
937 sfree (rates);
938 return (0);
939 } /* }}} int format_values */
941 int parse_identifier (char *str, char **ret_host,
942 char **ret_plugin, char **ret_plugin_instance,
943 char **ret_type, char **ret_type_instance)
944 {
945 char *hostname = NULL;
946 char *plugin = NULL;
947 char *plugin_instance = NULL;
948 char *type = NULL;
949 char *type_instance = NULL;
951 hostname = str;
952 if (hostname == NULL)
953 return (-1);
955 plugin = strchr (hostname, '/');
956 if (plugin == NULL)
957 return (-1);
958 *plugin = '\0'; plugin++;
960 type = strchr (plugin, '/');
961 if (type == NULL)
962 return (-1);
963 *type = '\0'; type++;
965 plugin_instance = strchr (plugin, '-');
966 if (plugin_instance != NULL)
967 {
968 *plugin_instance = '\0';
969 plugin_instance++;
970 }
972 type_instance = strchr (type, '-');
973 if (type_instance != NULL)
974 {
975 *type_instance = '\0';
976 type_instance++;
977 }
979 *ret_host = hostname;
980 *ret_plugin = plugin;
981 *ret_plugin_instance = plugin_instance;
982 *ret_type = type;
983 *ret_type_instance = type_instance;
984 return (0);
985 } /* int parse_identifier */
987 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
988 {
989 char str_copy[6 * DATA_MAX_NAME_LEN];
990 char *host = NULL;
991 char *plugin = NULL;
992 char *plugin_instance = NULL;
993 char *type = NULL;
994 char *type_instance = NULL;
995 int status;
997 if ((str == NULL) || (vl == NULL))
998 return (EINVAL);
1000 sstrncpy (str_copy, str, sizeof (str_copy));
1002 status = parse_identifier (str_copy, &host,
1003 &plugin, &plugin_instance,
1004 &type, &type_instance);
1005 if (status != 0)
1006 return (status);
1008 sstrncpy (vl->host, host, sizeof (vl->host));
1009 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1010 sstrncpy (vl->plugin_instance,
1011 (plugin_instance != NULL) ? plugin_instance : "",
1012 sizeof (vl->plugin_instance));
1013 sstrncpy (vl->type, type, sizeof (vl->type));
1014 sstrncpy (vl->type_instance,
1015 (type_instance != NULL) ? type_instance : "",
1016 sizeof (vl->type_instance));
1018 return (0);
1019 } /* }}} int parse_identifier_vl */
1021 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1022 {
1023 char *value;
1024 char *endptr = NULL;
1025 size_t value_len;
1027 if (value_orig == NULL)
1028 return (EINVAL);
1030 value = strdup (value_orig);
1031 if (value == NULL)
1032 return (ENOMEM);
1033 value_len = strlen (value);
1035 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1036 {
1037 value[value_len - 1] = 0;
1038 value_len--;
1039 }
1041 switch (ds_type)
1042 {
1043 case DS_TYPE_COUNTER:
1044 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1045 break;
1047 case DS_TYPE_GAUGE:
1048 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1049 break;
1051 case DS_TYPE_DERIVE:
1052 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1053 break;
1055 case DS_TYPE_ABSOLUTE:
1056 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1057 break;
1059 default:
1060 sfree (value);
1061 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1062 return -1;
1063 }
1065 if (value == endptr) {
1066 sfree (value);
1067 ERROR ("parse_value: Failed to parse string as %s: %s.",
1068 DS_TYPE_TO_STRING (ds_type), value);
1069 return -1;
1070 }
1071 else if ((NULL != endptr) && ('\0' != *endptr))
1072 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1073 "Input string was \"%s\".",
1074 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1076 sfree (value);
1077 return 0;
1078 } /* int parse_value */
1080 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1081 {
1082 int i;
1083 char *dummy;
1084 char *ptr;
1085 char *saveptr;
1087 i = -1;
1088 dummy = buffer;
1089 saveptr = NULL;
1090 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1091 {
1092 dummy = NULL;
1094 if (i >= vl->values_len)
1095 {
1096 /* Make sure i is invalid. */
1097 i = vl->values_len + 1;
1098 break;
1099 }
1101 if (i == -1)
1102 {
1103 if (strcmp ("N", ptr) == 0)
1104 vl->time = cdtime ();
1105 else
1106 {
1107 char *endptr = NULL;
1108 double tmp;
1110 errno = 0;
1111 tmp = strtod (ptr, &endptr);
1112 if ((errno != 0) /* Overflow */
1113 || (endptr == ptr) /* Invalid string */
1114 || (endptr == NULL) /* This should not happen */
1115 || (*endptr != 0)) /* Trailing chars */
1116 return (-1);
1118 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1119 }
1120 }
1121 else
1122 {
1123 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1124 vl->values[i].gauge = NAN;
1125 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1126 return -1;
1127 }
1129 i++;
1130 } /* while (strtok_r) */
1132 if ((ptr != NULL) || (i != vl->values_len))
1133 return (-1);
1134 return (0);
1135 } /* int parse_values */
1137 #if !HAVE_GETPWNAM_R
1138 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1139 size_t buflen, struct passwd **pwbufp)
1140 {
1141 int status = 0;
1142 struct passwd *pw;
1144 memset (pwbuf, '\0', sizeof (struct passwd));
1146 pthread_mutex_lock (&getpwnam_r_lock);
1148 do
1149 {
1150 pw = getpwnam (name);
1151 if (pw == NULL)
1152 {
1153 status = (errno != 0) ? errno : ENOENT;
1154 break;
1155 }
1157 #define GETPWNAM_COPY_MEMBER(member) \
1158 if (pw->member != NULL) \
1159 { \
1160 int len = strlen (pw->member); \
1161 if (len >= buflen) \
1162 { \
1163 status = ENOMEM; \
1164 break; \
1165 } \
1166 sstrncpy (buf, pw->member, buflen); \
1167 pwbuf->member = buf; \
1168 buf += (len + 1); \
1169 buflen -= (len + 1); \
1170 }
1171 GETPWNAM_COPY_MEMBER(pw_name);
1172 GETPWNAM_COPY_MEMBER(pw_passwd);
1173 GETPWNAM_COPY_MEMBER(pw_gecos);
1174 GETPWNAM_COPY_MEMBER(pw_dir);
1175 GETPWNAM_COPY_MEMBER(pw_shell);
1177 pwbuf->pw_uid = pw->pw_uid;
1178 pwbuf->pw_gid = pw->pw_gid;
1180 if (pwbufp != NULL)
1181 *pwbufp = pwbuf;
1182 } while (0);
1184 pthread_mutex_unlock (&getpwnam_r_lock);
1186 return (status);
1187 } /* int getpwnam_r */
1188 #endif /* !HAVE_GETPWNAM_R */
1190 int notification_init (notification_t *n, int severity, const char *message,
1191 const char *host,
1192 const char *plugin, const char *plugin_instance,
1193 const char *type, const char *type_instance)
1194 {
1195 memset (n, '\0', sizeof (notification_t));
1197 n->severity = severity;
1199 if (message != NULL)
1200 sstrncpy (n->message, message, sizeof (n->message));
1201 if (host != NULL)
1202 sstrncpy (n->host, host, sizeof (n->host));
1203 if (plugin != NULL)
1204 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1205 if (plugin_instance != NULL)
1206 sstrncpy (n->plugin_instance, plugin_instance,
1207 sizeof (n->plugin_instance));
1208 if (type != NULL)
1209 sstrncpy (n->type, type, sizeof (n->type));
1210 if (type_instance != NULL)
1211 sstrncpy (n->type_instance, type_instance,
1212 sizeof (n->type_instance));
1214 return (0);
1215 } /* int notification_init */
1217 int walk_directory (const char *dir, dirwalk_callback_f callback,
1218 void *user_data, int include_hidden)
1219 {
1220 struct dirent *ent;
1221 DIR *dh;
1222 int success;
1223 int failure;
1225 success = 0;
1226 failure = 0;
1228 if ((dh = opendir (dir)) == NULL)
1229 {
1230 char errbuf[1024];
1231 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1232 sstrerror (errno, errbuf, sizeof (errbuf)));
1233 return -1;
1234 }
1236 while ((ent = readdir (dh)) != NULL)
1237 {
1238 int status;
1240 if (include_hidden)
1241 {
1242 if ((strcmp (".", ent->d_name) == 0)
1243 || (strcmp ("..", ent->d_name) == 0))
1244 continue;
1245 }
1246 else /* if (!include_hidden) */
1247 {
1248 if (ent->d_name[0]=='.')
1249 continue;
1250 }
1252 status = (*callback) (dir, ent->d_name, user_data);
1253 if (status != 0)
1254 failure++;
1255 else
1256 success++;
1257 }
1259 closedir (dh);
1261 if ((success == 0) && (failure > 0))
1262 return (-1);
1263 return (0);
1264 }
1266 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1267 {
1268 FILE *fh;
1269 ssize_t ret;
1271 fh = fopen (filename, "r");
1272 if (fh == NULL)
1273 return (-1);
1275 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1276 if ((ret == 0) && (ferror (fh) != 0))
1277 {
1278 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1279 filename);
1280 ret = -1;
1281 }
1283 fclose(fh);
1284 return (ret);
1285 }
1287 counter_t counter_diff (counter_t old_value, counter_t new_value)
1288 {
1289 counter_t diff;
1291 if (old_value > new_value)
1292 {
1293 if (old_value <= 4294967295U)
1294 diff = (4294967295U - old_value) + new_value;
1295 else
1296 diff = (18446744073709551615ULL - old_value)
1297 + new_value;
1298 }
1299 else
1300 {
1301 diff = new_value - old_value;
1302 }
1304 return (diff);
1305 } /* counter_t counter_diff */
1307 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1308 rate_to_value_state_t *state,
1309 int ds_type, cdtime_t t)
1310 {
1311 gauge_t delta_gauge;
1312 cdtime_t delta_t;
1314 if (ds_type == DS_TYPE_GAUGE)
1315 {
1316 state->last_value.gauge = rate;
1317 state->last_time = t;
1319 *ret_value = state->last_value;
1320 return (0);
1321 }
1323 /* Counter and absolute can't handle negative rates. Reset "last time"
1324 * to zero, so that the next valid rate will re-initialize the
1325 * structure. */
1326 if ((rate < 0.0)
1327 && ((ds_type == DS_TYPE_COUNTER)
1328 || (ds_type == DS_TYPE_ABSOLUTE)))
1329 {
1330 memset (state, 0, sizeof (*state));
1331 return (EINVAL);
1332 }
1334 /* Another invalid state: The time is not increasing. */
1335 if (t <= state->last_time)
1336 {
1337 memset (state, 0, sizeof (*state));
1338 return (EINVAL);
1339 }
1341 delta_t = t - state->last_time;
1342 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1344 /* Previous value is invalid. */
1345 if (state->last_time == 0) /* {{{ */
1346 {
1347 if (ds_type == DS_TYPE_DERIVE)
1348 {
1349 state->last_value.derive = (derive_t) rate;
1350 state->residual = rate - ((gauge_t) state->last_value.derive);
1351 }
1352 else if (ds_type == DS_TYPE_COUNTER)
1353 {
1354 state->last_value.counter = (counter_t) rate;
1355 state->residual = rate - ((gauge_t) state->last_value.counter);
1356 }
1357 else if (ds_type == DS_TYPE_ABSOLUTE)
1358 {
1359 state->last_value.absolute = (absolute_t) rate;
1360 state->residual = rate - ((gauge_t) state->last_value.absolute);
1361 }
1362 else
1363 {
1364 assert (23 == 42);
1365 }
1367 state->last_time = t;
1368 return (EAGAIN);
1369 } /* }}} */
1371 if (ds_type == DS_TYPE_DERIVE)
1372 {
1373 derive_t delta_derive = (derive_t) delta_gauge;
1375 state->last_value.derive += delta_derive;
1376 state->residual = delta_gauge - ((gauge_t) delta_derive);
1377 }
1378 else if (ds_type == DS_TYPE_COUNTER)
1379 {
1380 counter_t delta_counter = (counter_t) delta_gauge;
1382 state->last_value.counter += delta_counter;
1383 state->residual = delta_gauge - ((gauge_t) delta_counter);
1384 }
1385 else if (ds_type == DS_TYPE_ABSOLUTE)
1386 {
1387 absolute_t delta_absolute = (absolute_t) delta_gauge;
1389 state->last_value.absolute = delta_absolute;
1390 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1391 }
1392 else
1393 {
1394 assert (23 == 42);
1395 }
1397 state->last_time = t;
1398 *ret_value = state->last_value;
1399 return (0);
1400 } /* }}} value_t rate_to_value */
1402 int value_to_rate (value_t *ret_rate, derive_t value, /* {{{ */
1403 value_to_rate_state_t *state,
1404 int ds_type, cdtime_t t)
1405 {
1406 double interval;
1408 /* Another invalid state: The time is not increasing. */
1409 if (t <= state->last_time)
1410 {
1411 memset (state, 0, sizeof (*state));
1412 return (EINVAL);
1413 }
1415 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1417 /* Previous value is invalid. */
1418 if (state->last_time == 0) /* {{{ */
1419 {
1420 if (ds_type == DS_TYPE_DERIVE)
1421 {
1422 state->last_value.derive = value;
1423 }
1424 else if (ds_type == DS_TYPE_COUNTER)
1425 {
1426 state->last_value.counter = (counter_t) value;
1427 }
1428 else if (ds_type == DS_TYPE_ABSOLUTE)
1429 {
1430 state->last_value.absolute = (absolute_t) value;
1431 }
1432 else
1433 {
1434 assert (23 == 42);
1435 }
1437 state->last_time = t;
1438 return (EAGAIN);
1439 } /* }}} */
1441 if (ds_type == DS_TYPE_DERIVE)
1442 {
1443 ret_rate->gauge = (value - state->last_value.derive) / interval;
1444 state->last_value.derive = value;
1445 }
1446 else if (ds_type == DS_TYPE_COUNTER)
1447 {
1448 ret_rate->gauge = (((counter_t)value) - state->last_value.counter) / interval;
1449 state->last_value.counter = (counter_t) value;
1450 }
1451 else if (ds_type == DS_TYPE_ABSOLUTE)
1452 {
1453 ret_rate->gauge = (((absolute_t)value) - state->last_value.absolute) / interval;
1454 state->last_value.absolute = (absolute_t) value;
1455 }
1456 else
1457 {
1458 assert (23 == 42);
1459 }
1461 state->last_time = t;
1462 return (0);
1463 } /* }}} value_t rate_to_value */
1465 int service_name_to_port_number (const char *service_name)
1466 {
1467 struct addrinfo *ai_list;
1468 struct addrinfo *ai_ptr;
1469 struct addrinfo ai_hints;
1470 int status;
1471 int service_number;
1473 if (service_name == NULL)
1474 return (-1);
1476 ai_list = NULL;
1477 memset (&ai_hints, 0, sizeof (ai_hints));
1478 ai_hints.ai_family = AF_UNSPEC;
1480 status = getaddrinfo (/* node = */ NULL, service_name,
1481 &ai_hints, &ai_list);
1482 if (status != 0)
1483 {
1484 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1485 gai_strerror (status));
1486 return (-1);
1487 }
1489 service_number = -1;
1490 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1491 {
1492 if (ai_ptr->ai_family == AF_INET)
1493 {
1494 struct sockaddr_in *sa;
1496 sa = (void *) ai_ptr->ai_addr;
1497 service_number = (int) ntohs (sa->sin_port);
1498 }
1499 else if (ai_ptr->ai_family == AF_INET6)
1500 {
1501 struct sockaddr_in6 *sa;
1503 sa = (void *) ai_ptr->ai_addr;
1504 service_number = (int) ntohs (sa->sin6_port);
1505 }
1507 if ((service_number > 0) && (service_number <= 65535))
1508 break;
1509 }
1511 freeaddrinfo (ai_list);
1513 if ((service_number > 0) && (service_number <= 65535))
1514 return (service_number);
1515 return (-1);
1516 } /* int service_name_to_port_number */
1518 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1519 {
1520 derive_t tmp;
1521 char *endptr;
1523 if ((string == NULL) || (ret_value == NULL))
1524 return (EINVAL);
1526 errno = 0;
1527 endptr = NULL;
1528 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1529 if ((endptr == string) || (errno != 0))
1530 return (-1);
1532 *ret_value = tmp;
1533 return (0);
1534 } /* }}} int strtoderive */
1536 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1537 {
1538 char **array;
1539 size_t array_len = *ret_array_len;
1541 if (str == NULL)
1542 return (EINVAL);
1544 array = realloc (*ret_array,
1545 (array_len + 1) * sizeof (*array));
1546 if (array == NULL)
1547 return (ENOMEM);
1548 *ret_array = array;
1550 array[array_len] = strdup (str);
1551 if (array[array_len] == NULL)
1552 return (ENOMEM);
1554 array_len++;
1555 *ret_array_len = array_len;
1556 return (0);
1557 } /* }}} int strarray_add */
1559 void strarray_free (char **array, size_t array_len) /* {{{ */
1560 {
1561 size_t i;
1563 for (i = 0; i < array_len; i++)
1564 sfree (array[i]);
1565 sfree (array);
1566 } /* }}} void strarray_free */