e396b79d4285ae6c6b324dec722a56d4151300fc
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 escape_string (char *buffer, size_t buffer_size)
377 {
378 char *temp;
379 size_t i;
380 size_t j;
382 /* Check if we need to escape at all first */
383 temp = strpbrk (buffer, " \t\"\\");
384 if (temp == NULL)
385 return (0);
387 if (buffer_size < 3)
388 return (EINVAL);
390 temp = (char *) malloc (buffer_size);
391 if (temp == NULL)
392 return (ENOMEM);
393 memset (temp, 0, buffer_size);
395 temp[0] = '"';
396 j = 1;
398 for (i = 0; i < buffer_size; i++)
399 {
400 if (buffer[i] == 0)
401 {
402 break;
403 }
404 else if ((buffer[i] == '"') || (buffer[i] == '\\'))
405 {
406 if (j > (buffer_size - 4))
407 break;
408 temp[j] = '\\';
409 temp[j + 1] = buffer[i];
410 j += 2;
411 }
412 else
413 {
414 if (j > (buffer_size - 3))
415 break;
416 temp[j] = buffer[i];
417 j++;
418 }
419 }
421 assert ((j + 1) < buffer_size);
422 temp[j] = '"';
423 temp[j + 1] = 0;
425 sstrncpy (buffer, temp, buffer_size);
426 sfree (temp);
427 return (0);
428 } /* int escape_string */
430 int strunescape (char *buf, size_t buf_len)
431 {
432 size_t i;
434 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
435 {
436 if (buf[i] != '\\')
437 continue;
439 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
440 ERROR ("string unescape: backslash found at end of string.");
441 /* Ensure null-byte at the end of the buffer. */
442 buf[i] = 0;
443 return (-1);
444 }
446 switch (buf[i + 1]) {
447 case 't':
448 buf[i] = '\t';
449 break;
450 case 'n':
451 buf[i] = '\n';
452 break;
453 case 'r':
454 buf[i] = '\r';
455 break;
456 default:
457 buf[i] = buf[i + 1];
458 break;
459 }
461 /* Move everything after the position one position to the left.
462 * Add a null-byte as last character in the buffer. */
463 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
464 buf[buf_len - 1] = 0;
465 }
466 return (0);
467 } /* int strunescape */
469 size_t strstripnewline (char *buffer)
470 {
471 size_t buffer_len = strlen (buffer);
473 while (buffer_len > 0)
474 {
475 if ((buffer[buffer_len - 1] != '\n')
476 && (buffer[buffer_len - 1] != '\r'))
477 break;
478 buffer_len--;
479 buffer[buffer_len] = 0;
480 }
482 return (buffer_len);
483 } /* size_t strstripnewline */
485 int escape_slashes (char *buffer, size_t buffer_size)
486 {
487 int i;
488 size_t buffer_len;
490 buffer_len = strlen (buffer);
492 if (buffer_len <= 1)
493 {
494 if (strcmp ("/", buffer) == 0)
495 {
496 if (buffer_size < 5)
497 return (-1);
498 sstrncpy (buffer, "root", buffer_size);
499 }
500 return (0);
501 }
503 /* Move one to the left */
504 if (buffer[0] == '/')
505 {
506 memmove (buffer, buffer + 1, buffer_len);
507 buffer_len--;
508 }
510 for (i = 0; i < buffer_len - 1; i++)
511 {
512 if (buffer[i] == '/')
513 buffer[i] = '_';
514 }
516 return (0);
517 } /* int escape_slashes */
519 void replace_special (char *buffer, size_t buffer_size)
520 {
521 size_t i;
523 for (i = 0; i < buffer_size; i++)
524 {
525 if (buffer[i] == 0)
526 return;
527 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
528 buffer[i] = '_';
529 }
530 } /* void replace_special */
532 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
533 {
534 struct timeval *larger;
535 struct timeval *smaller;
537 int status;
539 NORMALIZE_TIMEVAL (tv0);
540 NORMALIZE_TIMEVAL (tv1);
542 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
543 {
544 if (delta != NULL) {
545 delta->tv_sec = 0;
546 delta->tv_usec = 0;
547 }
548 return (0);
549 }
551 if ((tv0.tv_sec < tv1.tv_sec)
552 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
553 {
554 larger = &tv1;
555 smaller = &tv0;
556 status = -1;
557 }
558 else
559 {
560 larger = &tv0;
561 smaller = &tv1;
562 status = 1;
563 }
565 if (delta != NULL) {
566 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
568 if (smaller->tv_usec <= larger->tv_usec)
569 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
570 else
571 {
572 --delta->tv_sec;
573 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
574 }
575 }
577 assert ((delta == NULL)
578 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
580 return (status);
581 } /* int timeval_cmp */
583 int check_create_dir (const char *file_orig)
584 {
585 struct stat statbuf;
587 char file_copy[512];
588 char dir[512];
589 int dir_len = 512;
590 char *fields[16];
591 int fields_num;
592 char *ptr;
593 char *saveptr;
594 int last_is_file = 1;
595 int path_is_absolute = 0;
596 size_t len;
597 int i;
599 /*
600 * Sanity checks first
601 */
602 if (file_orig == NULL)
603 return (-1);
605 if ((len = strlen (file_orig)) < 1)
606 return (-1);
607 else if (len >= sizeof (file_copy))
608 return (-1);
610 /*
611 * If `file_orig' ends in a slash the last component is a directory,
612 * otherwise it's a file. Act accordingly..
613 */
614 if (file_orig[len - 1] == '/')
615 last_is_file = 0;
616 if (file_orig[0] == '/')
617 path_is_absolute = 1;
619 /*
620 * Create a copy for `strtok_r' to destroy
621 */
622 sstrncpy (file_copy, file_orig, sizeof (file_copy));
624 /*
625 * Break into components. This will eat up several slashes in a row and
626 * remove leading and trailing slashes..
627 */
628 ptr = file_copy;
629 saveptr = NULL;
630 fields_num = 0;
631 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
632 {
633 ptr = NULL;
634 fields_num++;
636 if (fields_num >= 16)
637 break;
638 }
640 /*
641 * For each component, do..
642 */
643 for (i = 0; i < (fields_num - last_is_file); i++)
644 {
645 /*
646 * Do not create directories that start with a dot. This
647 * prevents `../../' attacks and other likely malicious
648 * behavior.
649 */
650 if (fields[i][0] == '.')
651 {
652 ERROR ("Cowardly refusing to create a directory that "
653 "begins with a `.' (dot): `%s'", file_orig);
654 return (-2);
655 }
657 /*
658 * Join the components together again
659 */
660 dir[0] = '/';
661 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
662 fields, i + 1, "/") < 0)
663 {
664 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
665 return (-1);
666 }
668 while (42) {
669 if ((stat (dir, &statbuf) == -1)
670 && (lstat (dir, &statbuf) == -1))
671 {
672 if (errno == ENOENT)
673 {
674 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
675 break;
677 /* this might happen, if a different thread created
678 * the directory in the meantime
679 * => call stat() again to check for S_ISDIR() */
680 if (EEXIST == errno)
681 continue;
683 char errbuf[1024];
684 ERROR ("check_create_dir: mkdir (%s): %s", dir,
685 sstrerror (errno,
686 errbuf, sizeof (errbuf)));
687 return (-1);
688 }
689 else
690 {
691 char errbuf[1024];
692 ERROR ("check_create_dir: stat (%s): %s", dir,
693 sstrerror (errno, errbuf,
694 sizeof (errbuf)));
695 return (-1);
696 }
697 }
698 else if (!S_ISDIR (statbuf.st_mode))
699 {
700 ERROR ("check_create_dir: `%s' exists but is not "
701 "a directory!", dir);
702 return (-1);
703 }
704 break;
705 }
706 }
708 return (0);
709 } /* check_create_dir */
711 #ifdef HAVE_LIBKSTAT
712 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
713 {
714 char ident[128];
716 *ksp_ptr = NULL;
718 if (kc == NULL)
719 return (-1);
721 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
723 *ksp_ptr = kstat_lookup (kc, module, instance, name);
724 if (*ksp_ptr == NULL)
725 {
726 ERROR ("get_kstat: Cound not find kstat %s", ident);
727 return (-1);
728 }
730 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
731 {
732 ERROR ("get_kstat: kstat %s has wrong type", ident);
733 *ksp_ptr = NULL;
734 return (-1);
735 }
737 #ifdef assert
738 assert (*ksp_ptr != NULL);
739 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
740 #endif
742 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
743 {
744 ERROR ("get_kstat: kstat %s could not be read", ident);
745 return (-1);
746 }
748 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
749 {
750 ERROR ("get_kstat: kstat %s has wrong type", ident);
751 return (-1);
752 }
754 return (0);
755 }
757 long long get_kstat_value (kstat_t *ksp, char *name)
758 {
759 kstat_named_t *kn;
760 long long retval = -1LL;
762 if (ksp == NULL)
763 {
764 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
765 return (-1LL);
766 }
767 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
768 {
769 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
770 "is not KSTAT_TYPE_NAMED (%#x).",
771 name,
772 (unsigned int) ksp->ks_type,
773 (unsigned int) KSTAT_TYPE_NAMED);
774 return (-1LL);
775 }
777 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
778 return (-1LL);
780 if (kn->data_type == KSTAT_DATA_INT32)
781 retval = (long long) kn->value.i32;
782 else if (kn->data_type == KSTAT_DATA_UINT32)
783 retval = (long long) kn->value.ui32;
784 else if (kn->data_type == KSTAT_DATA_INT64)
785 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
786 else if (kn->data_type == KSTAT_DATA_UINT64)
787 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
788 else
789 WARNING ("get_kstat_value: Not a numeric value: %s", name);
791 return (retval);
792 }
793 #endif /* HAVE_LIBKSTAT */
795 #ifndef HAVE_HTONLL
796 unsigned long long ntohll (unsigned long long n)
797 {
798 #if BYTE_ORDER == BIG_ENDIAN
799 return (n);
800 #else
801 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
802 #endif
803 } /* unsigned long long ntohll */
805 unsigned long long htonll (unsigned long long n)
806 {
807 #if BYTE_ORDER == BIG_ENDIAN
808 return (n);
809 #else
810 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
811 #endif
812 } /* unsigned long long htonll */
813 #endif /* HAVE_HTONLL */
815 #if FP_LAYOUT_NEED_NOTHING
816 /* Well, we need nothing.. */
817 /* #endif FP_LAYOUT_NEED_NOTHING */
819 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
820 # if FP_LAYOUT_NEED_ENDIANFLIP
821 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
822 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
823 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
824 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
825 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
826 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
827 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
828 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
829 # else
830 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
831 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
832 # endif
834 double ntohd (double d)
835 {
836 union
837 {
838 uint8_t byte[8];
839 uint64_t integer;
840 double floating;
841 } ret;
843 ret.floating = d;
845 /* NAN in x86 byte order */
846 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
847 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
848 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
849 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
850 {
851 return (NAN);
852 }
853 else
854 {
855 uint64_t tmp;
857 tmp = ret.integer;
858 ret.integer = FP_CONVERT (tmp);
859 return (ret.floating);
860 }
861 } /* double ntohd */
863 double htond (double d)
864 {
865 union
866 {
867 uint8_t byte[8];
868 uint64_t integer;
869 double floating;
870 } ret;
872 if (isnan (d))
873 {
874 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
875 ret.byte[4] = ret.byte[5] = 0x00;
876 ret.byte[6] = 0xf8;
877 ret.byte[7] = 0x7f;
878 return (ret.floating);
879 }
880 else
881 {
882 uint64_t tmp;
884 ret.floating = d;
885 tmp = FP_CONVERT (ret.integer);
886 ret.integer = tmp;
887 return (ret.floating);
888 }
889 } /* double htond */
890 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
892 int format_name (char *ret, int ret_len,
893 const char *hostname,
894 const char *plugin, const char *plugin_instance,
895 const char *type, const char *type_instance)
896 {
897 char *buffer;
898 size_t buffer_size;
900 buffer = ret;
901 buffer_size = (size_t) ret_len;
903 #define APPEND(str) do { \
904 size_t l = strlen (str); \
905 if (l >= buffer_size) \
906 return (ENOBUFS); \
907 memcpy (buffer, (str), l); \
908 buffer += l; buffer_size -= l; \
909 } while (0)
911 assert (plugin != NULL);
912 assert (type != NULL);
914 APPEND (hostname);
915 APPEND ("/");
916 APPEND (plugin);
917 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
918 {
919 APPEND ("-");
920 APPEND (plugin_instance);
921 }
922 APPEND ("/");
923 APPEND (type);
924 if ((type_instance != NULL) && (type_instance[0] != 0))
925 {
926 APPEND ("-");
927 APPEND (type_instance);
928 }
929 assert (buffer_size > 0);
930 buffer[0] = 0;
932 #undef APPEND
933 return (0);
934 } /* int format_name */
936 int format_values (char *ret, size_t ret_len, /* {{{ */
937 const data_set_t *ds, const value_list_t *vl,
938 _Bool store_rates)
939 {
940 size_t offset = 0;
941 int status;
942 int i;
943 gauge_t *rates = NULL;
945 assert (0 == strcmp (ds->type, vl->type));
947 memset (ret, 0, ret_len);
949 #define BUFFER_ADD(...) do { \
950 status = ssnprintf (ret + offset, ret_len - offset, \
951 __VA_ARGS__); \
952 if (status < 1) \
953 { \
954 sfree (rates); \
955 return (-1); \
956 } \
957 else if (((size_t) status) >= (ret_len - offset)) \
958 { \
959 sfree (rates); \
960 return (-1); \
961 } \
962 else \
963 offset += ((size_t) status); \
964 } while (0)
966 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
968 for (i = 0; i < ds->ds_num; i++)
969 {
970 if (ds->ds[i].type == DS_TYPE_GAUGE)
971 BUFFER_ADD (":"GAUGE_FORMAT, vl->values[i].gauge);
972 else if (store_rates)
973 {
974 if (rates == NULL)
975 rates = uc_get_rate (ds, vl);
976 if (rates == NULL)
977 {
978 WARNING ("format_values: uc_get_rate failed.");
979 return (-1);
980 }
981 BUFFER_ADD (":"GAUGE_FORMAT, rates[i]);
982 }
983 else if (ds->ds[i].type == DS_TYPE_COUNTER)
984 BUFFER_ADD (":%llu", vl->values[i].counter);
985 else if (ds->ds[i].type == DS_TYPE_DERIVE)
986 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
987 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
988 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
989 else
990 {
991 ERROR ("format_values: Unknown data source type: %i",
992 ds->ds[i].type);
993 sfree (rates);
994 return (-1);
995 }
996 } /* for ds->ds_num */
998 #undef BUFFER_ADD
1000 sfree (rates);
1001 return (0);
1002 } /* }}} int format_values */
1004 int parse_identifier (char *str, char **ret_host,
1005 char **ret_plugin, char **ret_plugin_instance,
1006 char **ret_type, char **ret_type_instance)
1007 {
1008 char *hostname = NULL;
1009 char *plugin = NULL;
1010 char *plugin_instance = NULL;
1011 char *type = NULL;
1012 char *type_instance = NULL;
1014 hostname = str;
1015 if (hostname == NULL)
1016 return (-1);
1018 plugin = strchr (hostname, '/');
1019 if (plugin == NULL)
1020 return (-1);
1021 *plugin = '\0'; plugin++;
1023 type = strchr (plugin, '/');
1024 if (type == NULL)
1025 return (-1);
1026 *type = '\0'; type++;
1028 plugin_instance = strchr (plugin, '-');
1029 if (plugin_instance != NULL)
1030 {
1031 *plugin_instance = '\0';
1032 plugin_instance++;
1033 }
1035 type_instance = strchr (type, '-');
1036 if (type_instance != NULL)
1037 {
1038 *type_instance = '\0';
1039 type_instance++;
1040 }
1042 *ret_host = hostname;
1043 *ret_plugin = plugin;
1044 *ret_plugin_instance = plugin_instance;
1045 *ret_type = type;
1046 *ret_type_instance = type_instance;
1047 return (0);
1048 } /* int parse_identifier */
1050 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
1051 {
1052 char str_copy[6 * DATA_MAX_NAME_LEN];
1053 char *host = NULL;
1054 char *plugin = NULL;
1055 char *plugin_instance = NULL;
1056 char *type = NULL;
1057 char *type_instance = NULL;
1058 int status;
1060 if ((str == NULL) || (vl == NULL))
1061 return (EINVAL);
1063 sstrncpy (str_copy, str, sizeof (str_copy));
1065 status = parse_identifier (str_copy, &host,
1066 &plugin, &plugin_instance,
1067 &type, &type_instance);
1068 if (status != 0)
1069 return (status);
1071 sstrncpy (vl->host, host, sizeof (vl->host));
1072 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1073 sstrncpy (vl->plugin_instance,
1074 (plugin_instance != NULL) ? plugin_instance : "",
1075 sizeof (vl->plugin_instance));
1076 sstrncpy (vl->type, type, sizeof (vl->type));
1077 sstrncpy (vl->type_instance,
1078 (type_instance != NULL) ? type_instance : "",
1079 sizeof (vl->type_instance));
1081 return (0);
1082 } /* }}} int parse_identifier_vl */
1084 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1085 {
1086 char *value;
1087 char *endptr = NULL;
1088 size_t value_len;
1090 if (value_orig == NULL)
1091 return (EINVAL);
1093 value = strdup (value_orig);
1094 if (value == NULL)
1095 return (ENOMEM);
1096 value_len = strlen (value);
1098 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1099 {
1100 value[value_len - 1] = 0;
1101 value_len--;
1102 }
1104 switch (ds_type)
1105 {
1106 case DS_TYPE_COUNTER:
1107 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1108 break;
1110 case DS_TYPE_GAUGE:
1111 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1112 break;
1114 case DS_TYPE_DERIVE:
1115 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1116 break;
1118 case DS_TYPE_ABSOLUTE:
1119 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1120 break;
1122 default:
1123 sfree (value);
1124 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1125 return -1;
1126 }
1128 if (value == endptr) {
1129 ERROR ("parse_value: Failed to parse string as %s: %s.",
1130 DS_TYPE_TO_STRING (ds_type), value);
1131 sfree (value);
1132 return -1;
1133 }
1134 else if ((NULL != endptr) && ('\0' != *endptr))
1135 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1136 "Input string was \"%s\".",
1137 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1139 sfree (value);
1140 return 0;
1141 } /* int parse_value */
1143 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1144 {
1145 int i;
1146 char *dummy;
1147 char *ptr;
1148 char *saveptr;
1150 i = -1;
1151 dummy = buffer;
1152 saveptr = NULL;
1153 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1154 {
1155 dummy = NULL;
1157 if (i >= vl->values_len)
1158 {
1159 /* Make sure i is invalid. */
1160 i = vl->values_len + 1;
1161 break;
1162 }
1164 if (i == -1)
1165 {
1166 if (strcmp ("N", ptr) == 0)
1167 vl->time = cdtime ();
1168 else
1169 {
1170 char *endptr = NULL;
1171 double tmp;
1173 errno = 0;
1174 tmp = strtod (ptr, &endptr);
1175 if ((errno != 0) /* Overflow */
1176 || (endptr == ptr) /* Invalid string */
1177 || (endptr == NULL) /* This should not happen */
1178 || (*endptr != 0)) /* Trailing chars */
1179 return (-1);
1181 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1182 }
1183 }
1184 else
1185 {
1186 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1187 vl->values[i].gauge = NAN;
1188 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1189 return -1;
1190 }
1192 i++;
1193 } /* while (strtok_r) */
1195 if ((ptr != NULL) || (i != vl->values_len))
1196 return (-1);
1197 return (0);
1198 } /* int parse_values */
1200 #if !HAVE_GETPWNAM_R
1201 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1202 size_t buflen, struct passwd **pwbufp)
1203 {
1204 int status = 0;
1205 struct passwd *pw;
1207 memset (pwbuf, '\0', sizeof (struct passwd));
1209 pthread_mutex_lock (&getpwnam_r_lock);
1211 do
1212 {
1213 pw = getpwnam (name);
1214 if (pw == NULL)
1215 {
1216 status = (errno != 0) ? errno : ENOENT;
1217 break;
1218 }
1220 #define GETPWNAM_COPY_MEMBER(member) \
1221 if (pw->member != NULL) \
1222 { \
1223 int len = strlen (pw->member); \
1224 if (len >= buflen) \
1225 { \
1226 status = ENOMEM; \
1227 break; \
1228 } \
1229 sstrncpy (buf, pw->member, buflen); \
1230 pwbuf->member = buf; \
1231 buf += (len + 1); \
1232 buflen -= (len + 1); \
1233 }
1234 GETPWNAM_COPY_MEMBER(pw_name);
1235 GETPWNAM_COPY_MEMBER(pw_passwd);
1236 GETPWNAM_COPY_MEMBER(pw_gecos);
1237 GETPWNAM_COPY_MEMBER(pw_dir);
1238 GETPWNAM_COPY_MEMBER(pw_shell);
1240 pwbuf->pw_uid = pw->pw_uid;
1241 pwbuf->pw_gid = pw->pw_gid;
1243 if (pwbufp != NULL)
1244 *pwbufp = pwbuf;
1245 } while (0);
1247 pthread_mutex_unlock (&getpwnam_r_lock);
1249 return (status);
1250 } /* int getpwnam_r */
1251 #endif /* !HAVE_GETPWNAM_R */
1253 int notification_init (notification_t *n, int severity, const char *message,
1254 const char *host,
1255 const char *plugin, const char *plugin_instance,
1256 const char *type, const char *type_instance)
1257 {
1258 memset (n, '\0', sizeof (notification_t));
1260 n->severity = severity;
1262 if (message != NULL)
1263 sstrncpy (n->message, message, sizeof (n->message));
1264 if (host != NULL)
1265 sstrncpy (n->host, host, sizeof (n->host));
1266 if (plugin != NULL)
1267 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1268 if (plugin_instance != NULL)
1269 sstrncpy (n->plugin_instance, plugin_instance,
1270 sizeof (n->plugin_instance));
1271 if (type != NULL)
1272 sstrncpy (n->type, type, sizeof (n->type));
1273 if (type_instance != NULL)
1274 sstrncpy (n->type_instance, type_instance,
1275 sizeof (n->type_instance));
1277 return (0);
1278 } /* int notification_init */
1280 int walk_directory (const char *dir, dirwalk_callback_f callback,
1281 void *user_data, int include_hidden)
1282 {
1283 struct dirent *ent;
1284 DIR *dh;
1285 int success;
1286 int failure;
1288 success = 0;
1289 failure = 0;
1291 if ((dh = opendir (dir)) == NULL)
1292 {
1293 char errbuf[1024];
1294 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1295 sstrerror (errno, errbuf, sizeof (errbuf)));
1296 return -1;
1297 }
1299 while ((ent = readdir (dh)) != NULL)
1300 {
1301 int status;
1303 if (include_hidden)
1304 {
1305 if ((strcmp (".", ent->d_name) == 0)
1306 || (strcmp ("..", ent->d_name) == 0))
1307 continue;
1308 }
1309 else /* if (!include_hidden) */
1310 {
1311 if (ent->d_name[0]=='.')
1312 continue;
1313 }
1315 status = (*callback) (dir, ent->d_name, user_data);
1316 if (status != 0)
1317 failure++;
1318 else
1319 success++;
1320 }
1322 closedir (dh);
1324 if ((success == 0) && (failure > 0))
1325 return (-1);
1326 return (0);
1327 }
1329 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1330 {
1331 FILE *fh;
1332 ssize_t ret;
1334 fh = fopen (filename, "r");
1335 if (fh == NULL)
1336 return (-1);
1338 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1339 if ((ret == 0) && (ferror (fh) != 0))
1340 {
1341 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1342 filename);
1343 ret = -1;
1344 }
1346 fclose(fh);
1347 return (ret);
1348 }
1350 counter_t counter_diff (counter_t old_value, counter_t new_value)
1351 {
1352 counter_t diff;
1354 if (old_value > new_value)
1355 {
1356 if (old_value <= 4294967295U)
1357 diff = (4294967295U - old_value) + new_value;
1358 else
1359 diff = (18446744073709551615ULL - old_value)
1360 + new_value;
1361 }
1362 else
1363 {
1364 diff = new_value - old_value;
1365 }
1367 return (diff);
1368 } /* counter_t counter_diff */
1370 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1371 rate_to_value_state_t *state,
1372 int ds_type, cdtime_t t)
1373 {
1374 gauge_t delta_gauge;
1375 cdtime_t delta_t;
1377 if (ds_type == DS_TYPE_GAUGE)
1378 {
1379 state->last_value.gauge = rate;
1380 state->last_time = t;
1382 *ret_value = state->last_value;
1383 return (0);
1384 }
1386 /* Counter and absolute can't handle negative rates. Reset "last time"
1387 * to zero, so that the next valid rate will re-initialize the
1388 * structure. */
1389 if ((rate < 0.0)
1390 && ((ds_type == DS_TYPE_COUNTER)
1391 || (ds_type == DS_TYPE_ABSOLUTE)))
1392 {
1393 memset (state, 0, sizeof (*state));
1394 return (EINVAL);
1395 }
1397 /* Another invalid state: The time is not increasing. */
1398 if (t <= state->last_time)
1399 {
1400 memset (state, 0, sizeof (*state));
1401 return (EINVAL);
1402 }
1404 delta_t = t - state->last_time;
1405 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1407 /* Previous value is invalid. */
1408 if (state->last_time == 0) /* {{{ */
1409 {
1410 if (ds_type == DS_TYPE_DERIVE)
1411 {
1412 state->last_value.derive = (derive_t) rate;
1413 state->residual = rate - ((gauge_t) state->last_value.derive);
1414 }
1415 else if (ds_type == DS_TYPE_COUNTER)
1416 {
1417 state->last_value.counter = (counter_t) rate;
1418 state->residual = rate - ((gauge_t) state->last_value.counter);
1419 }
1420 else if (ds_type == DS_TYPE_ABSOLUTE)
1421 {
1422 state->last_value.absolute = (absolute_t) rate;
1423 state->residual = rate - ((gauge_t) state->last_value.absolute);
1424 }
1425 else
1426 {
1427 assert (23 == 42);
1428 }
1430 state->last_time = t;
1431 return (EAGAIN);
1432 } /* }}} */
1434 if (ds_type == DS_TYPE_DERIVE)
1435 {
1436 derive_t delta_derive = (derive_t) delta_gauge;
1438 state->last_value.derive += delta_derive;
1439 state->residual = delta_gauge - ((gauge_t) delta_derive);
1440 }
1441 else if (ds_type == DS_TYPE_COUNTER)
1442 {
1443 counter_t delta_counter = (counter_t) delta_gauge;
1445 state->last_value.counter += delta_counter;
1446 state->residual = delta_gauge - ((gauge_t) delta_counter);
1447 }
1448 else if (ds_type == DS_TYPE_ABSOLUTE)
1449 {
1450 absolute_t delta_absolute = (absolute_t) delta_gauge;
1452 state->last_value.absolute = delta_absolute;
1453 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1454 }
1455 else
1456 {
1457 assert (23 == 42);
1458 }
1460 state->last_time = t;
1461 *ret_value = state->last_value;
1462 return (0);
1463 } /* }}} value_t rate_to_value */
1465 int value_to_rate (value_t *ret_rate, derive_t value, /* {{{ */
1466 value_to_rate_state_t *state,
1467 int ds_type, cdtime_t t)
1468 {
1469 double interval;
1471 /* Another invalid state: The time is not increasing. */
1472 if (t <= state->last_time)
1473 {
1474 memset (state, 0, sizeof (*state));
1475 return (EINVAL);
1476 }
1478 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1480 /* Previous value is invalid. */
1481 if (state->last_time == 0) /* {{{ */
1482 {
1483 if (ds_type == DS_TYPE_DERIVE)
1484 {
1485 state->last_value.derive = value;
1486 }
1487 else if (ds_type == DS_TYPE_COUNTER)
1488 {
1489 state->last_value.counter = (counter_t) value;
1490 }
1491 else if (ds_type == DS_TYPE_ABSOLUTE)
1492 {
1493 state->last_value.absolute = (absolute_t) value;
1494 }
1495 else
1496 {
1497 assert (23 == 42);
1498 }
1500 state->last_time = t;
1501 return (EAGAIN);
1502 } /* }}} */
1504 if (ds_type == DS_TYPE_DERIVE)
1505 {
1506 ret_rate->gauge = (value - state->last_value.derive) / interval;
1507 state->last_value.derive = value;
1508 }
1509 else if (ds_type == DS_TYPE_COUNTER)
1510 {
1511 ret_rate->gauge = (((counter_t)value) - state->last_value.counter) / interval;
1512 state->last_value.counter = (counter_t) value;
1513 }
1514 else if (ds_type == DS_TYPE_ABSOLUTE)
1515 {
1516 ret_rate->gauge = (((absolute_t)value) - state->last_value.absolute) / interval;
1517 state->last_value.absolute = (absolute_t) value;
1518 }
1519 else
1520 {
1521 assert (23 == 42);
1522 }
1524 state->last_time = t;
1525 return (0);
1526 } /* }}} value_t rate_to_value */
1528 int service_name_to_port_number (const char *service_name)
1529 {
1530 struct addrinfo *ai_list;
1531 struct addrinfo *ai_ptr;
1532 struct addrinfo ai_hints;
1533 int status;
1534 int service_number;
1536 if (service_name == NULL)
1537 return (-1);
1539 ai_list = NULL;
1540 memset (&ai_hints, 0, sizeof (ai_hints));
1541 ai_hints.ai_family = AF_UNSPEC;
1543 status = getaddrinfo (/* node = */ NULL, service_name,
1544 &ai_hints, &ai_list);
1545 if (status != 0)
1546 {
1547 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1548 gai_strerror (status));
1549 return (-1);
1550 }
1552 service_number = -1;
1553 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1554 {
1555 if (ai_ptr->ai_family == AF_INET)
1556 {
1557 struct sockaddr_in *sa;
1559 sa = (void *) ai_ptr->ai_addr;
1560 service_number = (int) ntohs (sa->sin_port);
1561 }
1562 else if (ai_ptr->ai_family == AF_INET6)
1563 {
1564 struct sockaddr_in6 *sa;
1566 sa = (void *) ai_ptr->ai_addr;
1567 service_number = (int) ntohs (sa->sin6_port);
1568 }
1570 if ((service_number > 0) && (service_number <= 65535))
1571 break;
1572 }
1574 freeaddrinfo (ai_list);
1576 if ((service_number > 0) && (service_number <= 65535))
1577 return (service_number);
1578 return (-1);
1579 } /* int service_name_to_port_number */
1581 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1582 {
1583 derive_t tmp;
1584 char *endptr;
1586 if ((string == NULL) || (ret_value == NULL))
1587 return (EINVAL);
1589 errno = 0;
1590 endptr = NULL;
1591 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1592 if ((endptr == string) || (errno != 0))
1593 return (-1);
1595 *ret_value = tmp;
1596 return (0);
1597 } /* }}} int strtoderive */
1599 int strtogauge (const char *string, gauge_t *ret_value) /* {{{ */
1600 {
1601 gauge_t tmp;
1602 char *endptr = NULL;
1604 if ((string == NULL) || (ret_value == NULL))
1605 return (EINVAL);
1607 errno = 0;
1608 endptr = NULL;
1609 tmp = (gauge_t) strtod (string, &endptr);
1610 if (errno != 0)
1611 return (errno);
1612 else if ((endptr == NULL) || (*endptr != 0))
1613 return (EINVAL);
1615 *ret_value = tmp;
1616 return (0);
1617 } /* }}} int strtogauge */
1619 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1620 {
1621 char **array;
1622 size_t array_len = *ret_array_len;
1624 if (str == NULL)
1625 return (EINVAL);
1627 array = realloc (*ret_array,
1628 (array_len + 1) * sizeof (*array));
1629 if (array == NULL)
1630 return (ENOMEM);
1631 *ret_array = array;
1633 array[array_len] = strdup (str);
1634 if (array[array_len] == NULL)
1635 return (ENOMEM);
1637 array_len++;
1638 *ret_array_len = array_len;
1639 return (0);
1640 } /* }}} int strarray_add */
1642 void strarray_free (char **array, size_t array_len) /* {{{ */
1643 {
1644 size_t i;
1646 for (i = 0; i < array_len; i++)
1647 sfree (array[i]);
1648 sfree (array);
1649 } /* }}} void strarray_free */