1 /**
2 * collectd - src/common.c
3 * Copyright (C) 2005-2014 Florian octo Forster
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 *
23 * Authors:
24 * Florian octo Forster <octo at collectd.org>
25 * Niki W. Waibel <niki.waibel@gmx.net>
26 * Sebastian Harl <sh at tokkee.org>
27 * Michał Mirosław <mirq-linux at rere.qmqm.pl>
28 **/
30 #if HAVE_CONFIG_H
31 # include "config.h"
32 #endif
34 #include "collectd.h"
35 #include "common.h"
36 #include "plugin.h"
37 #include "utils_cache.h"
39 #if HAVE_PTHREAD_H
40 # include <pthread.h>
41 #endif
43 #ifdef HAVE_MATH_H
44 # include <math.h>
45 #endif
47 /* for getaddrinfo */
48 #include <sys/types.h>
49 #include <sys/socket.h>
50 #include <netdb.h>
52 #if HAVE_NETINET_IN_H
53 # include <netinet/in.h>
54 #endif
56 /* for ntohl and htonl */
57 #if HAVE_ARPA_INET_H
58 # include <arpa/inet.h>
59 #endif
61 #ifdef HAVE_LIBKSTAT
62 extern kstat_ctl_t *kc;
63 #endif
65 #if !HAVE_GETPWNAM_R
66 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
67 #endif
69 #if !HAVE_STRERROR_R
70 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
71 #endif
73 char *sstrncpy (char *dest, const char *src, size_t n)
74 {
75 strncpy (dest, src, n);
76 dest[n - 1] = '\0';
78 return (dest);
79 } /* char *sstrncpy */
81 int ssnprintf (char *dest, size_t n, const char *format, ...)
82 {
83 int ret = 0;
84 va_list ap;
86 va_start (ap, format);
87 ret = vsnprintf (dest, n, format, ap);
88 dest[n - 1] = '\0';
89 va_end (ap);
91 return (ret);
92 } /* int ssnprintf */
94 char *ssnprintf_alloc (char const *format, ...) /* {{{ */
95 {
96 char static_buffer[1024] = "";
97 char *alloc_buffer;
98 size_t alloc_buffer_size;
99 int status;
100 va_list ap;
102 /* Try printing into the static buffer. In many cases it will be
103 * sufficiently large and we can simply return a strdup() of this
104 * buffer. */
105 va_start (ap, format);
106 status = vsnprintf (static_buffer, sizeof (static_buffer), format, ap);
107 va_end (ap);
108 if (status < 0)
109 return (NULL);
111 /* "status" does not include the null byte. */
112 alloc_buffer_size = (size_t) (status + 1);
113 if (alloc_buffer_size <= sizeof (static_buffer))
114 return (strdup (static_buffer));
116 /* Allocate a buffer large enough to hold the string. */
117 alloc_buffer = malloc (alloc_buffer_size);
118 if (alloc_buffer == NULL)
119 return (NULL);
120 memset (alloc_buffer, 0, alloc_buffer_size);
122 /* Print again into this new buffer. */
123 va_start (ap, format);
124 status = vsnprintf (alloc_buffer, alloc_buffer_size, format, ap);
125 va_end (ap);
126 if (status < 0)
127 {
128 sfree (alloc_buffer);
129 return (NULL);
130 }
132 return (alloc_buffer);
133 } /* }}} char *ssnprintf_alloc */
135 char *sstrdup (const char *s)
136 {
137 char *r;
138 size_t sz;
140 if (s == NULL)
141 return (NULL);
143 /* Do not use `strdup' here, because it's not specified in POSIX. It's
144 * ``only'' an XSI extension. */
145 sz = strlen (s) + 1;
146 r = (char *) malloc (sizeof (char) * sz);
147 if (r == NULL)
148 {
149 ERROR ("sstrdup: Out of memory.");
150 exit (3);
151 }
152 memcpy (r, s, sizeof (char) * sz);
154 return (r);
155 } /* char *sstrdup */
157 /* Even though Posix requires "strerror_r" to return an "int",
158 * some systems (e.g. the GNU libc) return a "char *" _and_
159 * ignore the second argument ... -tokkee */
160 char *sstrerror (int errnum, char *buf, size_t buflen)
161 {
162 buf[0] = '\0';
164 #if !HAVE_STRERROR_R
165 {
166 char *temp;
168 pthread_mutex_lock (&strerror_r_lock);
170 temp = strerror (errnum);
171 sstrncpy (buf, temp, buflen);
173 pthread_mutex_unlock (&strerror_r_lock);
174 }
175 /* #endif !HAVE_STRERROR_R */
177 #elif STRERROR_R_CHAR_P
178 {
179 char *temp;
180 temp = strerror_r (errnum, buf, buflen);
181 if (buf[0] == '\0')
182 {
183 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
184 sstrncpy (buf, temp, buflen);
185 else
186 sstrncpy (buf, "strerror_r did not return "
187 "an error message", buflen);
188 }
189 }
190 /* #endif STRERROR_R_CHAR_P */
192 #else
193 if (strerror_r (errnum, buf, buflen) != 0)
194 {
195 ssnprintf (buf, buflen, "Error #%i; "
196 "Additionally, strerror_r failed.",
197 errnum);
198 }
199 #endif /* STRERROR_R_CHAR_P */
201 return (buf);
202 } /* char *sstrerror */
204 void *smalloc (size_t size)
205 {
206 void *r;
208 if ((r = malloc (size)) == NULL)
209 {
210 ERROR ("Not enough memory.");
211 exit (3);
212 }
214 return (r);
215 } /* void *smalloc */
217 #if 0
218 void sfree (void **ptr)
219 {
220 if (ptr == NULL)
221 return;
223 if (*ptr != NULL)
224 free (*ptr);
226 *ptr = NULL;
227 }
228 #endif
230 ssize_t sread (int fd, void *buf, size_t count)
231 {
232 char *ptr;
233 size_t nleft;
234 ssize_t status;
236 ptr = (char *) buf;
237 nleft = count;
239 while (nleft > 0)
240 {
241 status = read (fd, (void *) ptr, nleft);
243 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
244 continue;
246 if (status < 0)
247 return (status);
249 if (status == 0)
250 {
251 DEBUG ("Received EOF from fd %i. "
252 "Closing fd and returning error.",
253 fd);
254 close (fd);
255 return (-1);
256 }
258 assert ((0 > status) || (nleft >= (size_t)status));
260 nleft = nleft - status;
261 ptr = ptr + status;
262 }
264 return (0);
265 }
268 ssize_t swrite (int fd, const void *buf, size_t count)
269 {
270 const char *ptr;
271 size_t nleft;
272 ssize_t status;
274 ptr = (const char *) buf;
275 nleft = count;
277 while (nleft > 0)
278 {
279 status = write (fd, (const void *) ptr, nleft);
281 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
282 continue;
284 if (status < 0)
285 return (status);
287 nleft = nleft - status;
288 ptr = ptr + status;
289 }
291 return (0);
292 }
294 int strsplit (char *string, char **fields, size_t size)
295 {
296 size_t i;
297 char *ptr;
298 char *saveptr;
300 i = 0;
301 ptr = string;
302 saveptr = NULL;
303 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
304 {
305 ptr = NULL;
306 i++;
308 if (i >= size)
309 break;
310 }
312 return ((int) i);
313 }
315 int strjoin (char *dst, size_t dst_len,
316 char **fields, size_t fields_num,
317 const char *sep)
318 {
319 size_t field_len;
320 size_t sep_len;
321 int i;
323 memset (dst, '\0', dst_len);
325 if (fields_num <= 0)
326 return (-1);
328 sep_len = 0;
329 if (sep != NULL)
330 sep_len = strlen (sep);
332 for (i = 0; i < (int)fields_num; i++)
333 {
334 if ((i > 0) && (sep_len > 0))
335 {
336 if (dst_len <= sep_len)
337 return (-1);
339 strncat (dst, sep, dst_len);
340 dst_len -= sep_len;
341 }
343 field_len = strlen (fields[i]);
345 if (dst_len <= field_len)
346 return (-1);
348 strncat (dst, fields[i], dst_len);
349 dst_len -= field_len;
350 }
352 return (strlen (dst));
353 }
355 int strsubstitute (char *str, char c_from, char c_to)
356 {
357 int ret;
359 if (str == NULL)
360 return (-1);
362 ret = 0;
363 while (*str != '\0')
364 {
365 if (*str == c_from)
366 {
367 *str = c_to;
368 ret++;
369 }
370 str++;
371 }
373 return (ret);
374 } /* int strsubstitute */
376 int strunescape (char *buf, size_t buf_len)
377 {
378 size_t i;
380 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
381 {
382 if (buf[i] != '\\')
383 continue;
385 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
386 ERROR ("string unescape: backslash found at end of string.");
387 /* Ensure null-byte at the end of the buffer. */
388 buf[i] = 0;
389 return (-1);
390 }
392 switch (buf[i + 1]) {
393 case 't':
394 buf[i] = '\t';
395 break;
396 case 'n':
397 buf[i] = '\n';
398 break;
399 case 'r':
400 buf[i] = '\r';
401 break;
402 default:
403 buf[i] = buf[i + 1];
404 break;
405 }
407 /* Move everything after the position one position to the left.
408 * Add a null-byte as last character in the buffer. */
409 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
410 buf[buf_len - 1] = 0;
411 }
412 return (0);
413 } /* int strunescape */
415 size_t strstripnewline (char *buffer)
416 {
417 size_t buffer_len = strlen (buffer);
419 while (buffer_len > 0)
420 {
421 if ((buffer[buffer_len - 1] != '\n')
422 && (buffer[buffer_len - 1] != '\r'))
423 break;
424 buffer[buffer_len] = 0;
425 buffer_len--;
426 }
428 return (buffer_len);
429 } /* size_t strstripnewline */
431 int escape_slashes (char *buffer, size_t buffer_size)
432 {
433 int i;
434 size_t buffer_len;
436 buffer_len = strlen (buffer);
438 if (buffer_len <= 1)
439 {
440 if (strcmp ("/", buffer) == 0)
441 {
442 if (buffer_size < 5)
443 return (-1);
444 sstrncpy (buffer, "root", buffer_size);
445 }
446 return (0);
447 }
449 /* Move one to the left */
450 if (buffer[0] == '/')
451 {
452 memmove (buffer, buffer + 1, buffer_len);
453 buffer_len--;
454 }
456 for (i = 0; i < buffer_len - 1; i++)
457 {
458 if (buffer[i] == '/')
459 buffer[i] = '_';
460 }
462 return (0);
463 } /* int escape_slashes */
465 void replace_special (char *buffer, size_t buffer_size)
466 {
467 size_t i;
469 for (i = 0; i < buffer_size; i++)
470 {
471 if (buffer[i] == 0)
472 return;
473 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
474 buffer[i] = '_';
475 }
476 } /* void replace_special */
478 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
479 {
480 struct timeval *larger;
481 struct timeval *smaller;
483 int status;
485 NORMALIZE_TIMEVAL (tv0);
486 NORMALIZE_TIMEVAL (tv1);
488 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
489 {
490 if (delta != NULL) {
491 delta->tv_sec = 0;
492 delta->tv_usec = 0;
493 }
494 return (0);
495 }
497 if ((tv0.tv_sec < tv1.tv_sec)
498 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
499 {
500 larger = &tv1;
501 smaller = &tv0;
502 status = -1;
503 }
504 else
505 {
506 larger = &tv0;
507 smaller = &tv1;
508 status = 1;
509 }
511 if (delta != NULL) {
512 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
514 if (smaller->tv_usec <= larger->tv_usec)
515 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
516 else
517 {
518 --delta->tv_sec;
519 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
520 }
521 }
523 assert ((delta == NULL)
524 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
526 return (status);
527 } /* int timeval_cmp */
529 int check_create_dir (const char *file_orig)
530 {
531 struct stat statbuf;
533 char file_copy[512];
534 char dir[512];
535 int dir_len = 512;
536 char *fields[16];
537 int fields_num;
538 char *ptr;
539 char *saveptr;
540 int last_is_file = 1;
541 int path_is_absolute = 0;
542 size_t len;
543 int i;
545 /*
546 * Sanity checks first
547 */
548 if (file_orig == NULL)
549 return (-1);
551 if ((len = strlen (file_orig)) < 1)
552 return (-1);
553 else if (len >= sizeof (file_copy))
554 return (-1);
556 /*
557 * If `file_orig' ends in a slash the last component is a directory,
558 * otherwise it's a file. Act accordingly..
559 */
560 if (file_orig[len - 1] == '/')
561 last_is_file = 0;
562 if (file_orig[0] == '/')
563 path_is_absolute = 1;
565 /*
566 * Create a copy for `strtok_r' to destroy
567 */
568 sstrncpy (file_copy, file_orig, sizeof (file_copy));
570 /*
571 * Break into components. This will eat up several slashes in a row and
572 * remove leading and trailing slashes..
573 */
574 ptr = file_copy;
575 saveptr = NULL;
576 fields_num = 0;
577 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
578 {
579 ptr = NULL;
580 fields_num++;
582 if (fields_num >= 16)
583 break;
584 }
586 /*
587 * For each component, do..
588 */
589 for (i = 0; i < (fields_num - last_is_file); i++)
590 {
591 /*
592 * Do not create directories that start with a dot. This
593 * prevents `../../' attacks and other likely malicious
594 * behavior.
595 */
596 if (fields[i][0] == '.')
597 {
598 ERROR ("Cowardly refusing to create a directory that "
599 "begins with a `.' (dot): `%s'", file_orig);
600 return (-2);
601 }
603 /*
604 * Join the components together again
605 */
606 dir[0] = '/';
607 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
608 fields, i + 1, "/") < 0)
609 {
610 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
611 return (-1);
612 }
614 while (42) {
615 if ((stat (dir, &statbuf) == -1)
616 && (lstat (dir, &statbuf) == -1))
617 {
618 if (errno == ENOENT)
619 {
620 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
621 break;
623 /* this might happen, if a different thread created
624 * the directory in the meantime
625 * => call stat() again to check for S_ISDIR() */
626 if (EEXIST == errno)
627 continue;
629 char errbuf[1024];
630 ERROR ("check_create_dir: mkdir (%s): %s", dir,
631 sstrerror (errno,
632 errbuf, sizeof (errbuf)));
633 return (-1);
634 }
635 else
636 {
637 char errbuf[1024];
638 ERROR ("check_create_dir: stat (%s): %s", dir,
639 sstrerror (errno, errbuf,
640 sizeof (errbuf)));
641 return (-1);
642 }
643 }
644 else if (!S_ISDIR (statbuf.st_mode))
645 {
646 ERROR ("check_create_dir: `%s' exists but is not "
647 "a directory!", dir);
648 return (-1);
649 }
650 break;
651 }
652 }
654 return (0);
655 } /* check_create_dir */
657 #ifdef HAVE_LIBKSTAT
658 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
659 {
660 char ident[128];
662 *ksp_ptr = NULL;
664 if (kc == NULL)
665 return (-1);
667 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
669 *ksp_ptr = kstat_lookup (kc, module, instance, name);
670 if (*ksp_ptr == NULL)
671 {
672 ERROR ("get_kstat: Cound not find kstat %s", ident);
673 return (-1);
674 }
676 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
677 {
678 ERROR ("get_kstat: kstat %s has wrong type", ident);
679 *ksp_ptr = NULL;
680 return (-1);
681 }
683 #ifdef assert
684 assert (*ksp_ptr != NULL);
685 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
686 #endif
688 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
689 {
690 ERROR ("get_kstat: kstat %s could not be read", ident);
691 return (-1);
692 }
694 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
695 {
696 ERROR ("get_kstat: kstat %s has wrong type", ident);
697 return (-1);
698 }
700 return (0);
701 }
703 long long get_kstat_value (kstat_t *ksp, char *name)
704 {
705 kstat_named_t *kn;
706 long long retval = -1LL;
708 if (ksp == NULL)
709 {
710 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
711 return (-1LL);
712 }
713 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
714 {
715 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
716 "is not KSTAT_TYPE_NAMED (%#x).",
717 name,
718 (unsigned int) ksp->ks_type,
719 (unsigned int) KSTAT_TYPE_NAMED);
720 return (-1LL);
721 }
723 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
724 return (-1LL);
726 if (kn->data_type == KSTAT_DATA_INT32)
727 retval = (long long) kn->value.i32;
728 else if (kn->data_type == KSTAT_DATA_UINT32)
729 retval = (long long) kn->value.ui32;
730 else if (kn->data_type == KSTAT_DATA_INT64)
731 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
732 else if (kn->data_type == KSTAT_DATA_UINT64)
733 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
734 else
735 WARNING ("get_kstat_value: Not a numeric value: %s", name);
737 return (retval);
738 }
739 #endif /* HAVE_LIBKSTAT */
741 #ifndef HAVE_HTONLL
742 unsigned long long ntohll (unsigned long long n)
743 {
744 #if BYTE_ORDER == BIG_ENDIAN
745 return (n);
746 #else
747 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
748 #endif
749 } /* unsigned long long ntohll */
751 unsigned long long htonll (unsigned long long n)
752 {
753 #if BYTE_ORDER == BIG_ENDIAN
754 return (n);
755 #else
756 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
757 #endif
758 } /* unsigned long long htonll */
759 #endif /* HAVE_HTONLL */
761 #if FP_LAYOUT_NEED_NOTHING
762 /* Well, we need nothing.. */
763 /* #endif FP_LAYOUT_NEED_NOTHING */
765 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
766 # if FP_LAYOUT_NEED_ENDIANFLIP
767 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
768 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
769 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
770 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
771 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
772 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
773 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
774 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
775 # else
776 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
777 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
778 # endif
780 double ntohd (double d)
781 {
782 union
783 {
784 uint8_t byte[8];
785 uint64_t integer;
786 double floating;
787 } ret;
789 ret.floating = d;
791 /* NAN in x86 byte order */
792 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
793 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
794 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
795 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
796 {
797 return (NAN);
798 }
799 else
800 {
801 uint64_t tmp;
803 tmp = ret.integer;
804 ret.integer = FP_CONVERT (tmp);
805 return (ret.floating);
806 }
807 } /* double ntohd */
809 double htond (double d)
810 {
811 union
812 {
813 uint8_t byte[8];
814 uint64_t integer;
815 double floating;
816 } ret;
818 if (isnan (d))
819 {
820 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
821 ret.byte[4] = ret.byte[5] = 0x00;
822 ret.byte[6] = 0xf8;
823 ret.byte[7] = 0x7f;
824 return (ret.floating);
825 }
826 else
827 {
828 uint64_t tmp;
830 ret.floating = d;
831 tmp = FP_CONVERT (ret.integer);
832 ret.integer = tmp;
833 return (ret.floating);
834 }
835 } /* double htond */
836 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
838 int format_name (char *ret, int ret_len,
839 const char *hostname,
840 const char *plugin, const char *plugin_instance,
841 const char *type, const char *type_instance)
842 {
843 char *buffer;
844 size_t buffer_size;
846 buffer = ret;
847 buffer_size = (size_t) ret_len;
849 #define APPEND(str) do { \
850 size_t l = strlen (str); \
851 if (l >= buffer_size) \
852 return (ENOBUFS); \
853 memcpy (buffer, (str), l); \
854 buffer += l; buffer_size -= l; \
855 } while (0)
857 assert (plugin != NULL);
858 assert (type != NULL);
860 APPEND (hostname);
861 APPEND ("/");
862 APPEND (plugin);
863 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
864 {
865 APPEND ("-");
866 APPEND (plugin_instance);
867 }
868 APPEND ("/");
869 APPEND (type);
870 if ((type_instance != NULL) && (type_instance[0] != 0))
871 {
872 APPEND ("-");
873 APPEND (type_instance);
874 }
875 assert (buffer_size > 0);
876 buffer[0] = 0;
878 #undef APPEND
879 return (0);
880 } /* int format_name */
882 int format_values (char *ret, size_t ret_len, /* {{{ */
883 const data_set_t *ds, const value_list_t *vl,
884 _Bool store_rates)
885 {
886 size_t offset = 0;
887 int status;
888 int i;
889 gauge_t *rates = NULL;
891 assert (0 == strcmp (ds->type, vl->type));
893 memset (ret, 0, ret_len);
895 #define BUFFER_ADD(...) do { \
896 status = ssnprintf (ret + offset, ret_len - offset, \
897 __VA_ARGS__); \
898 if (status < 1) \
899 { \
900 sfree (rates); \
901 return (-1); \
902 } \
903 else if (((size_t) status) >= (ret_len - offset)) \
904 { \
905 sfree (rates); \
906 return (-1); \
907 } \
908 else \
909 offset += ((size_t) status); \
910 } while (0)
912 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
914 for (i = 0; i < ds->ds_num; i++)
915 {
916 if (ds->ds[i].type == DS_TYPE_GAUGE)
917 BUFFER_ADD (":%f", vl->values[i].gauge);
918 else if (store_rates)
919 {
920 if (rates == NULL)
921 rates = uc_get_rate (ds, vl);
922 if (rates == NULL)
923 {
924 WARNING ("format_values: "
925 "uc_get_rate failed.");
926 return (-1);
927 }
928 BUFFER_ADD (":%g", rates[i]);
929 }
930 else if (ds->ds[i].type == DS_TYPE_COUNTER)
931 BUFFER_ADD (":%llu", vl->values[i].counter);
932 else if (ds->ds[i].type == DS_TYPE_DERIVE)
933 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
934 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
935 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
936 else
937 {
938 ERROR ("format_values plugin: Unknown data source type: %i",
939 ds->ds[i].type);
940 sfree (rates);
941 return (-1);
942 }
943 } /* for ds->ds_num */
945 #undef BUFFER_ADD
947 sfree (rates);
948 return (0);
949 } /* }}} int format_values */
951 int parse_identifier (char *str, char **ret_host,
952 char **ret_plugin, char **ret_plugin_instance,
953 char **ret_type, char **ret_type_instance)
954 {
955 char *hostname = NULL;
956 char *plugin = NULL;
957 char *plugin_instance = NULL;
958 char *type = NULL;
959 char *type_instance = NULL;
961 hostname = str;
962 if (hostname == NULL)
963 return (-1);
965 plugin = strchr (hostname, '/');
966 if (plugin == NULL)
967 return (-1);
968 *plugin = '\0'; plugin++;
970 type = strchr (plugin, '/');
971 if (type == NULL)
972 return (-1);
973 *type = '\0'; type++;
975 plugin_instance = strchr (plugin, '-');
976 if (plugin_instance != NULL)
977 {
978 *plugin_instance = '\0';
979 plugin_instance++;
980 }
982 type_instance = strchr (type, '-');
983 if (type_instance != NULL)
984 {
985 *type_instance = '\0';
986 type_instance++;
987 }
989 *ret_host = hostname;
990 *ret_plugin = plugin;
991 *ret_plugin_instance = plugin_instance;
992 *ret_type = type;
993 *ret_type_instance = type_instance;
994 return (0);
995 } /* int parse_identifier */
997 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
998 {
999 char str_copy[6 * DATA_MAX_NAME_LEN];
1000 char *host = NULL;
1001 char *plugin = NULL;
1002 char *plugin_instance = NULL;
1003 char *type = NULL;
1004 char *type_instance = NULL;
1005 int status;
1007 if ((str == NULL) || (vl == NULL))
1008 return (EINVAL);
1010 sstrncpy (str_copy, str, sizeof (str_copy));
1012 status = parse_identifier (str_copy, &host,
1013 &plugin, &plugin_instance,
1014 &type, &type_instance);
1015 if (status != 0)
1016 return (status);
1018 sstrncpy (vl->host, host, sizeof (vl->host));
1019 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1020 sstrncpy (vl->plugin_instance,
1021 (plugin_instance != NULL) ? plugin_instance : "",
1022 sizeof (vl->plugin_instance));
1023 sstrncpy (vl->type, type, sizeof (vl->type));
1024 sstrncpy (vl->type_instance,
1025 (type_instance != NULL) ? type_instance : "",
1026 sizeof (vl->type_instance));
1028 return (0);
1029 } /* }}} int parse_identifier_vl */
1031 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1032 {
1033 char *value;
1034 char *endptr = NULL;
1035 size_t value_len;
1037 if (value_orig == NULL)
1038 return (EINVAL);
1040 value = strdup (value_orig);
1041 if (value == NULL)
1042 return (ENOMEM);
1043 value_len = strlen (value);
1045 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1046 {
1047 value[value_len - 1] = 0;
1048 value_len--;
1049 }
1051 switch (ds_type)
1052 {
1053 case DS_TYPE_COUNTER:
1054 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1055 break;
1057 case DS_TYPE_GAUGE:
1058 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1059 break;
1061 case DS_TYPE_DERIVE:
1062 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1063 break;
1065 case DS_TYPE_ABSOLUTE:
1066 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1067 break;
1069 default:
1070 sfree (value);
1071 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1072 return -1;
1073 }
1075 if (value == endptr) {
1076 sfree (value);
1077 ERROR ("parse_value: Failed to parse string as %s: %s.",
1078 DS_TYPE_TO_STRING (ds_type), value);
1079 return -1;
1080 }
1081 else if ((NULL != endptr) && ('\0' != *endptr))
1082 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1083 "Input string was \"%s\".",
1084 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1086 sfree (value);
1087 return 0;
1088 } /* int parse_value */
1090 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1091 {
1092 int i;
1093 char *dummy;
1094 char *ptr;
1095 char *saveptr;
1097 i = -1;
1098 dummy = buffer;
1099 saveptr = NULL;
1100 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1101 {
1102 dummy = NULL;
1104 if (i >= vl->values_len)
1105 {
1106 /* Make sure i is invalid. */
1107 i = vl->values_len + 1;
1108 break;
1109 }
1111 if (i == -1)
1112 {
1113 if (strcmp ("N", ptr) == 0)
1114 vl->time = cdtime ();
1115 else
1116 {
1117 char *endptr = NULL;
1118 double tmp;
1120 errno = 0;
1121 tmp = strtod (ptr, &endptr);
1122 if ((errno != 0) /* Overflow */
1123 || (endptr == ptr) /* Invalid string */
1124 || (endptr == NULL) /* This should not happen */
1125 || (*endptr != 0)) /* Trailing chars */
1126 return (-1);
1128 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1129 }
1130 }
1131 else
1132 {
1133 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1134 vl->values[i].gauge = NAN;
1135 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1136 return -1;
1137 }
1139 i++;
1140 } /* while (strtok_r) */
1142 if ((ptr != NULL) || (i != vl->values_len))
1143 return (-1);
1144 return (0);
1145 } /* int parse_values */
1147 #if !HAVE_GETPWNAM_R
1148 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1149 size_t buflen, struct passwd **pwbufp)
1150 {
1151 int status = 0;
1152 struct passwd *pw;
1154 memset (pwbuf, '\0', sizeof (struct passwd));
1156 pthread_mutex_lock (&getpwnam_r_lock);
1158 do
1159 {
1160 pw = getpwnam (name);
1161 if (pw == NULL)
1162 {
1163 status = (errno != 0) ? errno : ENOENT;
1164 break;
1165 }
1167 #define GETPWNAM_COPY_MEMBER(member) \
1168 if (pw->member != NULL) \
1169 { \
1170 int len = strlen (pw->member); \
1171 if (len >= buflen) \
1172 { \
1173 status = ENOMEM; \
1174 break; \
1175 } \
1176 sstrncpy (buf, pw->member, buflen); \
1177 pwbuf->member = buf; \
1178 buf += (len + 1); \
1179 buflen -= (len + 1); \
1180 }
1181 GETPWNAM_COPY_MEMBER(pw_name);
1182 GETPWNAM_COPY_MEMBER(pw_passwd);
1183 GETPWNAM_COPY_MEMBER(pw_gecos);
1184 GETPWNAM_COPY_MEMBER(pw_dir);
1185 GETPWNAM_COPY_MEMBER(pw_shell);
1187 pwbuf->pw_uid = pw->pw_uid;
1188 pwbuf->pw_gid = pw->pw_gid;
1190 if (pwbufp != NULL)
1191 *pwbufp = pwbuf;
1192 } while (0);
1194 pthread_mutex_unlock (&getpwnam_r_lock);
1196 return (status);
1197 } /* int getpwnam_r */
1198 #endif /* !HAVE_GETPWNAM_R */
1200 int notification_init (notification_t *n, int severity, const char *message,
1201 const char *host,
1202 const char *plugin, const char *plugin_instance,
1203 const char *type, const char *type_instance)
1204 {
1205 memset (n, '\0', sizeof (notification_t));
1207 n->severity = severity;
1209 if (message != NULL)
1210 sstrncpy (n->message, message, sizeof (n->message));
1211 if (host != NULL)
1212 sstrncpy (n->host, host, sizeof (n->host));
1213 if (plugin != NULL)
1214 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1215 if (plugin_instance != NULL)
1216 sstrncpy (n->plugin_instance, plugin_instance,
1217 sizeof (n->plugin_instance));
1218 if (type != NULL)
1219 sstrncpy (n->type, type, sizeof (n->type));
1220 if (type_instance != NULL)
1221 sstrncpy (n->type_instance, type_instance,
1222 sizeof (n->type_instance));
1224 return (0);
1225 } /* int notification_init */
1227 int walk_directory (const char *dir, dirwalk_callback_f callback,
1228 void *user_data, int include_hidden)
1229 {
1230 struct dirent *ent;
1231 DIR *dh;
1232 int success;
1233 int failure;
1235 success = 0;
1236 failure = 0;
1238 if ((dh = opendir (dir)) == NULL)
1239 {
1240 char errbuf[1024];
1241 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1242 sstrerror (errno, errbuf, sizeof (errbuf)));
1243 return -1;
1244 }
1246 while ((ent = readdir (dh)) != NULL)
1247 {
1248 int status;
1250 if (include_hidden)
1251 {
1252 if ((strcmp (".", ent->d_name) == 0)
1253 || (strcmp ("..", ent->d_name) == 0))
1254 continue;
1255 }
1256 else /* if (!include_hidden) */
1257 {
1258 if (ent->d_name[0]=='.')
1259 continue;
1260 }
1262 status = (*callback) (dir, ent->d_name, user_data);
1263 if (status != 0)
1264 failure++;
1265 else
1266 success++;
1267 }
1269 closedir (dh);
1271 if ((success == 0) && (failure > 0))
1272 return (-1);
1273 return (0);
1274 }
1276 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1277 {
1278 FILE *fh;
1279 ssize_t ret;
1281 fh = fopen (filename, "r");
1282 if (fh == NULL)
1283 return (-1);
1285 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1286 if ((ret == 0) && (ferror (fh) != 0))
1287 {
1288 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1289 filename);
1290 ret = -1;
1291 }
1293 fclose(fh);
1294 return (ret);
1295 }
1297 counter_t counter_diff (counter_t old_value, counter_t new_value)
1298 {
1299 counter_t diff;
1301 if (old_value > new_value)
1302 {
1303 if (old_value <= 4294967295U)
1304 diff = (4294967295U - old_value) + new_value;
1305 else
1306 diff = (18446744073709551615ULL - old_value)
1307 + new_value;
1308 }
1309 else
1310 {
1311 diff = new_value - old_value;
1312 }
1314 return (diff);
1315 } /* counter_t counter_diff */
1317 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1318 rate_to_value_state_t *state,
1319 int ds_type, cdtime_t t)
1320 {
1321 gauge_t delta_gauge;
1322 cdtime_t delta_t;
1324 if (ds_type == DS_TYPE_GAUGE)
1325 {
1326 state->last_value.gauge = rate;
1327 state->last_time = t;
1329 *ret_value = state->last_value;
1330 return (0);
1331 }
1333 /* Counter and absolute can't handle negative rates. Reset "last time"
1334 * to zero, so that the next valid rate will re-initialize the
1335 * structure. */
1336 if ((rate < 0.0)
1337 && ((ds_type == DS_TYPE_COUNTER)
1338 || (ds_type == DS_TYPE_ABSOLUTE)))
1339 {
1340 memset (state, 0, sizeof (*state));
1341 return (EINVAL);
1342 }
1344 /* Another invalid state: The time is not increasing. */
1345 if (t <= state->last_time)
1346 {
1347 memset (state, 0, sizeof (*state));
1348 return (EINVAL);
1349 }
1351 delta_t = t - state->last_time;
1352 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1354 /* Previous value is invalid. */
1355 if (state->last_time == 0) /* {{{ */
1356 {
1357 if (ds_type == DS_TYPE_DERIVE)
1358 {
1359 state->last_value.derive = (derive_t) rate;
1360 state->residual = rate - ((gauge_t) state->last_value.derive);
1361 }
1362 else if (ds_type == DS_TYPE_COUNTER)
1363 {
1364 state->last_value.counter = (counter_t) rate;
1365 state->residual = rate - ((gauge_t) state->last_value.counter);
1366 }
1367 else if (ds_type == DS_TYPE_ABSOLUTE)
1368 {
1369 state->last_value.absolute = (absolute_t) rate;
1370 state->residual = rate - ((gauge_t) state->last_value.absolute);
1371 }
1372 else
1373 {
1374 assert (23 == 42);
1375 }
1377 state->last_time = t;
1378 return (EAGAIN);
1379 } /* }}} */
1381 if (ds_type == DS_TYPE_DERIVE)
1382 {
1383 derive_t delta_derive = (derive_t) delta_gauge;
1385 state->last_value.derive += delta_derive;
1386 state->residual = delta_gauge - ((gauge_t) delta_derive);
1387 }
1388 else if (ds_type == DS_TYPE_COUNTER)
1389 {
1390 counter_t delta_counter = (counter_t) delta_gauge;
1392 state->last_value.counter += delta_counter;
1393 state->residual = delta_gauge - ((gauge_t) delta_counter);
1394 }
1395 else if (ds_type == DS_TYPE_ABSOLUTE)
1396 {
1397 absolute_t delta_absolute = (absolute_t) delta_gauge;
1399 state->last_value.absolute = delta_absolute;
1400 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1401 }
1402 else
1403 {
1404 assert (23 == 42);
1405 }
1407 state->last_time = t;
1408 *ret_value = state->last_value;
1409 return (0);
1410 } /* }}} value_t rate_to_value */
1412 int value_to_rate (value_t *ret_rate, derive_t value, /* {{{ */
1413 value_to_rate_state_t *state,
1414 int ds_type, cdtime_t t)
1415 {
1416 double interval;
1418 /* Another invalid state: The time is not increasing. */
1419 if (t <= state->last_time)
1420 {
1421 memset (state, 0, sizeof (*state));
1422 return (EINVAL);
1423 }
1425 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1427 /* Previous value is invalid. */
1428 if (state->last_time == 0) /* {{{ */
1429 {
1430 if (ds_type == DS_TYPE_DERIVE)
1431 {
1432 state->last_value.derive = value;
1433 }
1434 else if (ds_type == DS_TYPE_COUNTER)
1435 {
1436 state->last_value.counter = (counter_t) value;
1437 }
1438 else if (ds_type == DS_TYPE_ABSOLUTE)
1439 {
1440 state->last_value.absolute = (absolute_t) value;
1441 }
1442 else
1443 {
1444 assert (23 == 42);
1445 }
1447 state->last_time = t;
1448 return (EAGAIN);
1449 } /* }}} */
1451 if (ds_type == DS_TYPE_DERIVE)
1452 {
1453 ret_rate->gauge = (value - state->last_value.derive) / interval;
1454 state->last_value.derive = value;
1455 }
1456 else if (ds_type == DS_TYPE_COUNTER)
1457 {
1458 ret_rate->gauge = (((counter_t)value) - state->last_value.counter) / interval;
1459 state->last_value.counter = (counter_t) value;
1460 }
1461 else if (ds_type == DS_TYPE_ABSOLUTE)
1462 {
1463 ret_rate->gauge = (((absolute_t)value) - state->last_value.absolute) / interval;
1464 state->last_value.absolute = (absolute_t) value;
1465 }
1466 else
1467 {
1468 assert (23 == 42);
1469 }
1471 state->last_time = t;
1472 return (0);
1473 } /* }}} value_t rate_to_value */
1475 int service_name_to_port_number (const char *service_name)
1476 {
1477 struct addrinfo *ai_list;
1478 struct addrinfo *ai_ptr;
1479 struct addrinfo ai_hints;
1480 int status;
1481 int service_number;
1483 if (service_name == NULL)
1484 return (-1);
1486 ai_list = NULL;
1487 memset (&ai_hints, 0, sizeof (ai_hints));
1488 ai_hints.ai_family = AF_UNSPEC;
1490 status = getaddrinfo (/* node = */ NULL, service_name,
1491 &ai_hints, &ai_list);
1492 if (status != 0)
1493 {
1494 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1495 gai_strerror (status));
1496 return (-1);
1497 }
1499 service_number = -1;
1500 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1501 {
1502 if (ai_ptr->ai_family == AF_INET)
1503 {
1504 struct sockaddr_in *sa;
1506 sa = (void *) ai_ptr->ai_addr;
1507 service_number = (int) ntohs (sa->sin_port);
1508 }
1509 else if (ai_ptr->ai_family == AF_INET6)
1510 {
1511 struct sockaddr_in6 *sa;
1513 sa = (void *) ai_ptr->ai_addr;
1514 service_number = (int) ntohs (sa->sin6_port);
1515 }
1517 if ((service_number > 0) && (service_number <= 65535))
1518 break;
1519 }
1521 freeaddrinfo (ai_list);
1523 if ((service_number > 0) && (service_number <= 65535))
1524 return (service_number);
1525 return (-1);
1526 } /* int service_name_to_port_number */
1528 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1529 {
1530 derive_t tmp;
1531 char *endptr;
1533 if ((string == NULL) || (ret_value == NULL))
1534 return (EINVAL);
1536 errno = 0;
1537 endptr = NULL;
1538 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1539 if ((endptr == string) || (errno != 0))
1540 return (-1);
1542 *ret_value = tmp;
1543 return (0);
1544 } /* }}} int strtoderive */
1546 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1547 {
1548 char **array;
1549 size_t array_len = *ret_array_len;
1551 if (str == NULL)
1552 return (EINVAL);
1554 array = realloc (*ret_array,
1555 (array_len + 1) * sizeof (*array));
1556 if (array == NULL)
1557 return (ENOMEM);
1558 *ret_array = array;
1560 array[array_len] = strdup (str);
1561 if (array[array_len] == NULL)
1562 return (ENOMEM);
1564 array_len++;
1565 *ret_array_len = array_len;
1566 return (0);
1567 } /* }}} int strarray_add */
1569 void strarray_free (char **array, size_t array_len) /* {{{ */
1570 {
1571 size_t i;
1573 for (i = 0; i < array_len; i++)
1574 sfree (array[i]);
1575 sfree (array);
1576 } /* }}} void strarray_free */