Code

src/common.c: Reimplement format_name for performance.
[collectd.git] / src / common.c
1 /**
2  * collectd - src/common.c
3  * Copyright (C) 2005-2010  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at collectd.org>
20  *   Niki W. Waibel <niki.waibel@gmx.net>
21  *   Sebastian Harl <sh at tokkee.org>
22  *   Michał Mirosław <mirq-linux at rere.qmqm.pl>
23 **/
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32 #include "utils_cache.h"
34 #if HAVE_PTHREAD_H
35 # include <pthread.h>
36 #endif
38 #ifdef HAVE_MATH_H
39 # include <math.h>
40 #endif
42 /* for getaddrinfo */
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netdb.h>
47 #if HAVE_NETINET_IN_H
48 # include <netinet/in.h>
49 #endif
51 /* for ntohl and htonl */
52 #if HAVE_ARPA_INET_H
53 # include <arpa/inet.h>
54 #endif
56 #ifdef HAVE_LIBKSTAT
57 extern kstat_ctl_t *kc;
58 #endif
60 #if !HAVE_GETPWNAM_R
61 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
62 #endif
64 #if !HAVE_STRERROR_R
65 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
66 #endif
68 char *sstrncpy (char *dest, const char *src, size_t n)
69 {
70         strncpy (dest, src, n);
71         dest[n - 1] = '\0';
73         return (dest);
74 } /* char *sstrncpy */
76 int ssnprintf (char *dest, size_t n, const char *format, ...)
77 {
78         int ret = 0;
79         va_list ap;
81         va_start (ap, format);
82         ret = vsnprintf (dest, n, format, ap);
83         dest[n - 1] = '\0';
84         va_end (ap);
86         return (ret);
87 } /* int ssnprintf */
89 char *sstrdup (const char *s)
90 {
91         char *r;
92         size_t sz;
94         if (s == NULL)
95                 return (NULL);
97         /* Do not use `strdup' here, because it's not specified in POSIX. It's
98          * ``only'' an XSI extension. */
99         sz = strlen (s) + 1;
100         r = (char *) malloc (sizeof (char) * sz);
101         if (r == NULL)
102         {
103                 ERROR ("sstrdup: Out of memory.");
104                 exit (3);
105         }
106         memcpy (r, s, sizeof (char) * sz);
108         return (r);
109 } /* char *sstrdup */
111 /* Even though Posix requires "strerror_r" to return an "int",
112  * some systems (e.g. the GNU libc) return a "char *" _and_
113  * ignore the second argument ... -tokkee */
114 char *sstrerror (int errnum, char *buf, size_t buflen)
116         buf[0] = '\0';
118 #if !HAVE_STRERROR_R
119         {
120                 char *temp;
122                 pthread_mutex_lock (&strerror_r_lock);
124                 temp = strerror (errnum);
125                 sstrncpy (buf, temp, buflen);
127                 pthread_mutex_unlock (&strerror_r_lock);
128         }
129 /* #endif !HAVE_STRERROR_R */
131 #elif STRERROR_R_CHAR_P
132         {
133                 char *temp;
134                 temp = strerror_r (errnum, buf, buflen);
135                 if (buf[0] == '\0')
136                 {
137                         if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
138                                 sstrncpy (buf, temp, buflen);
139                         else
140                                 sstrncpy (buf, "strerror_r did not return "
141                                                 "an error message", buflen);
142                 }
143         }
144 /* #endif STRERROR_R_CHAR_P */
146 #else
147         if (strerror_r (errnum, buf, buflen) != 0)
148         {
149                 ssnprintf (buf, buflen, "Error #%i; "
150                                 "Additionally, strerror_r failed.",
151                                 errnum);
152         }
153 #endif /* STRERROR_R_CHAR_P */
155         return (buf);
156 } /* char *sstrerror */
158 void *smalloc (size_t size)
160         void *r;
162         if ((r = malloc (size)) == NULL)
163         {
164                 ERROR ("Not enough memory.");
165                 exit (3);
166         }
168         return (r);
169 } /* void *smalloc */
171 #if 0
172 void sfree (void **ptr)
174         if (ptr == NULL)
175                 return;
177         if (*ptr != NULL)
178                 free (*ptr);
180         *ptr = NULL;
182 #endif
184 ssize_t sread (int fd, void *buf, size_t count)
186         char    *ptr;
187         size_t   nleft;
188         ssize_t  status;
190         ptr   = (char *) buf;
191         nleft = count;
193         while (nleft > 0)
194         {
195                 status = read (fd, (void *) ptr, nleft);
197                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
198                         continue;
200                 if (status < 0)
201                         return (status);
203                 if (status == 0)
204                 {
205                         DEBUG ("Received EOF from fd %i. "
206                                         "Closing fd and returning error.",
207                                         fd);
208                         close (fd);
209                         return (-1);
210                 }
212                 assert ((0 > status) || (nleft >= (size_t)status));
214                 nleft = nleft - status;
215                 ptr   = ptr   + status;
216         }
218         return (0);
222 ssize_t swrite (int fd, const void *buf, size_t count)
224         const char *ptr;
225         size_t      nleft;
226         ssize_t     status;
228         ptr   = (const char *) buf;
229         nleft = count;
231         while (nleft > 0)
232         {
233                 status = write (fd, (const void *) ptr, nleft);
235                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
236                         continue;
238                 if (status < 0)
239                         return (status);
241                 nleft = nleft - status;
242                 ptr   = ptr   + status;
243         }
245         return (0);
248 int strsplit (char *string, char **fields, size_t size)
250         size_t i;
251         char *ptr;
252         char *saveptr;
254         i = 0;
255         ptr = string;
256         saveptr = NULL;
257         while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
258         {
259                 ptr = NULL;
260                 i++;
262                 if (i >= size)
263                         break;
264         }
266         return ((int) i);
269 int strjoin (char *dst, size_t dst_len,
270                 char **fields, size_t fields_num,
271                 const char *sep)
273         size_t field_len;
274         size_t sep_len;
275         int i;
277         memset (dst, '\0', dst_len);
279         if (fields_num <= 0)
280                 return (-1);
282         sep_len = 0;
283         if (sep != NULL)
284                 sep_len = strlen (sep);
286         for (i = 0; i < (int)fields_num; i++)
287         {
288                 if ((i > 0) && (sep_len > 0))
289                 {
290                         if (dst_len <= sep_len)
291                                 return (-1);
293                         strncat (dst, sep, dst_len);
294                         dst_len -= sep_len;
295                 }
297                 field_len = strlen (fields[i]);
299                 if (dst_len <= field_len)
300                         return (-1);
302                 strncat (dst, fields[i], dst_len);
303                 dst_len -= field_len;
304         }
306         return (strlen (dst));
309 int strsubstitute (char *str, char c_from, char c_to)
311         int ret;
313         if (str == NULL)
314                 return (-1);
316         ret = 0;
317         while (*str != '\0')
318         {
319                 if (*str == c_from)
320                 {
321                         *str = c_to;
322                         ret++;
323                 }
324                 str++;
325         }
327         return (ret);
328 } /* int strsubstitute */
330 int strunescape (char *buf, size_t buf_len)
332         size_t i;
334         for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
335         {
336                 if (buf[i] != '\\')
337                         continue;
339                 if ((i >= buf_len) || (buf[i + 1] == '\0')) {
340                         ERROR ("string unescape: backslash found at end of string.");
341                         return (-1);
342                 }
344                 switch (buf[i + 1]) {
345                         case 't':
346                                 buf[i] = '\t';
347                                 break;
348                         case 'n':
349                                 buf[i] = '\n';
350                                 break;
351                         case 'r':
352                                 buf[i] = '\r';
353                                 break;
354                         default:
355                                 buf[i] = buf[i + 1];
356                                 break;
357                 }
359                 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
360         }
361         return (0);
362 } /* int strunescape */
364 int escape_slashes (char *buf, int buf_len)
366         int i;
368         if (strcmp (buf, "/") == 0)
369         {
370                 if (buf_len < 5)
371                         return (-1);
373                 strncpy (buf, "root", buf_len);
374                 return (0);
375         }
377         if (buf_len <= 1)
378                 return (0);
380         /* Move one to the left */
381         if (buf[0] == '/')
382                 memmove (buf, buf + 1, buf_len - 1);
384         for (i = 0; i < buf_len - 1; i++)
385         {
386                 if (buf[i] == '\0')
387                         break;
388                 else if (buf[i] == '/')
389                         buf[i] = '_';
390         }
391         buf[i] = '\0';
393         return (0);
394 } /* int escape_slashes */
396 void replace_special (char *buffer, size_t buffer_size)
398         size_t i;
400         for (i = 0; i < buffer_size; i++)
401         {
402                 if (buffer[i] == 0)
403                         return;
404                 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
405                         buffer[i] = '_';
406         }
407 } /* void replace_special */
409 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
411         struct timeval *larger;
412         struct timeval *smaller;
414         int status;
416         NORMALIZE_TIMEVAL (tv0);
417         NORMALIZE_TIMEVAL (tv1);
419         if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
420         {
421                 if (delta != NULL) {
422                         delta->tv_sec  = 0;
423                         delta->tv_usec = 0;
424                 }
425                 return (0);
426         }
428         if ((tv0.tv_sec < tv1.tv_sec)
429                         || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
430         {
431                 larger  = &tv1;
432                 smaller = &tv0;
433                 status  = -1;
434         }
435         else
436         {
437                 larger  = &tv0;
438                 smaller = &tv1;
439                 status  = 1;
440         }
442         if (delta != NULL) {
443                 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
445                 if (smaller->tv_usec <= larger->tv_usec)
446                         delta->tv_usec = larger->tv_usec - smaller->tv_usec;
447                 else
448                 {
449                         --delta->tv_sec;
450                         delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
451                 }
452         }
454         assert ((delta == NULL)
455                         || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
457         return (status);
458 } /* int timeval_cmp */
460 int check_create_dir (const char *file_orig)
462         struct stat statbuf;
464         char  file_copy[512];
465         char  dir[512];
466         int   dir_len = 512;
467         char *fields[16];
468         int   fields_num;
469         char *ptr;
470         char *saveptr;
471         int   last_is_file = 1;
472         int   path_is_absolute = 0;
473         size_t len;
474         int   i;
476         /*
477          * Sanity checks first
478          */
479         if (file_orig == NULL)
480                 return (-1);
482         if ((len = strlen (file_orig)) < 1)
483                 return (-1);
484         else if (len >= sizeof (file_copy))
485                 return (-1);
487         /*
488          * If `file_orig' ends in a slash the last component is a directory,
489          * otherwise it's a file. Act accordingly..
490          */
491         if (file_orig[len - 1] == '/')
492                 last_is_file = 0;
493         if (file_orig[0] == '/')
494                 path_is_absolute = 1;
496         /*
497          * Create a copy for `strtok_r' to destroy
498          */
499         sstrncpy (file_copy, file_orig, sizeof (file_copy));
501         /*
502          * Break into components. This will eat up several slashes in a row and
503          * remove leading and trailing slashes..
504          */
505         ptr = file_copy;
506         saveptr = NULL;
507         fields_num = 0;
508         while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
509         {
510                 ptr = NULL;
511                 fields_num++;
513                 if (fields_num >= 16)
514                         break;
515         }
517         /*
518          * For each component, do..
519          */
520         for (i = 0; i < (fields_num - last_is_file); i++)
521         {
522                 /*
523                  * Do not create directories that start with a dot. This
524                  * prevents `../../' attacks and other likely malicious
525                  * behavior.
526                  */
527                 if (fields[i][0] == '.')
528                 {
529                         ERROR ("Cowardly refusing to create a directory that "
530                                         "begins with a `.' (dot): `%s'", file_orig);
531                         return (-2);
532                 }
534                 /*
535                  * Join the components together again
536                  */
537                 dir[0] = '/';
538                 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
539                                         fields, i + 1, "/") < 0)
540                 {
541                         ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
542                         return (-1);
543                 }
545                 while (42) {
546                         if ((stat (dir, &statbuf) == -1)
547                                         && (lstat (dir, &statbuf) == -1))
548                         {
549                                 if (errno == ENOENT)
550                                 {
551                                         if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
552                                                 break;
554                                         /* this might happen, if a different thread created
555                                          * the directory in the meantime
556                                          * => call stat() again to check for S_ISDIR() */
557                                         if (EEXIST == errno)
558                                                 continue;
560                                         char errbuf[1024];
561                                         ERROR ("check_create_dir: mkdir (%s): %s", dir,
562                                                         sstrerror (errno,
563                                                                 errbuf, sizeof (errbuf)));
564                                         return (-1);
565                                 }
566                                 else
567                                 {
568                                         char errbuf[1024];
569                                         ERROR ("check_create_dir: stat (%s): %s", dir,
570                                                         sstrerror (errno, errbuf,
571                                                                 sizeof (errbuf)));
572                                         return (-1);
573                                 }
574                         }
575                         else if (!S_ISDIR (statbuf.st_mode))
576                         {
577                                 ERROR ("check_create_dir: `%s' exists but is not "
578                                                 "a directory!", dir);
579                                 return (-1);
580                         }
581                         break;
582                 }
583         }
585         return (0);
586 } /* check_create_dir */
588 #ifdef HAVE_LIBKSTAT
589 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
591         char ident[128];
593         *ksp_ptr = NULL;
594         
595         if (kc == NULL)
596                 return (-1);
598         ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
600         *ksp_ptr = kstat_lookup (kc, module, instance, name);
601         if (*ksp_ptr == NULL)
602         {
603                 ERROR ("get_kstat: Cound not find kstat %s", ident);
604                 return (-1);
605         }
607         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
608         {
609                 ERROR ("get_kstat: kstat %s has wrong type", ident);
610                 *ksp_ptr = NULL;
611                 return (-1);
612         }
614 #ifdef assert
615         assert (*ksp_ptr != NULL);
616         assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
617 #endif
619         if (kstat_read (kc, *ksp_ptr, NULL) == -1)
620         {
621                 ERROR ("get_kstat: kstat %s could not be read", ident);
622                 return (-1);
623         }
625         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
626         {
627                 ERROR ("get_kstat: kstat %s has wrong type", ident);
628                 return (-1);
629         }
631         return (0);
634 long long get_kstat_value (kstat_t *ksp, char *name)
636         kstat_named_t *kn;
637         long long retval = -1LL;
639         if (ksp == NULL)
640         {
641                 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
642                 return (-1LL);
643         }
644         else if (ksp->ks_type != KSTAT_TYPE_NAMED)
645         {
646                 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
647                                 "is not KSTAT_TYPE_NAMED (%#x).",
648                                 name,
649                                 (unsigned int) ksp->ks_type,
650                                 (unsigned int) KSTAT_TYPE_NAMED);
651                 return (-1LL);
652         }
654         if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
655                 return (-1LL);
657         if (kn->data_type == KSTAT_DATA_INT32)
658                 retval = (long long) kn->value.i32;
659         else if (kn->data_type == KSTAT_DATA_UINT32)
660                 retval = (long long) kn->value.ui32;
661         else if (kn->data_type == KSTAT_DATA_INT64)
662                 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
663         else if (kn->data_type == KSTAT_DATA_UINT64)
664                 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
665         else
666                 WARNING ("get_kstat_value: Not a numeric value: %s", name);
668         return (retval);
670 #endif /* HAVE_LIBKSTAT */
672 #ifndef HAVE_HTONLL
673 unsigned long long ntohll (unsigned long long n)
675 #if BYTE_ORDER == BIG_ENDIAN
676         return (n);
677 #else
678         return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
679 #endif
680 } /* unsigned long long ntohll */
682 unsigned long long htonll (unsigned long long n)
684 #if BYTE_ORDER == BIG_ENDIAN
685         return (n);
686 #else
687         return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
688 #endif
689 } /* unsigned long long htonll */
690 #endif /* HAVE_HTONLL */
692 #if FP_LAYOUT_NEED_NOTHING
693 /* Well, we need nothing.. */
694 /* #endif FP_LAYOUT_NEED_NOTHING */
696 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
697 # if FP_LAYOUT_NEED_ENDIANFLIP
698 #  define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
699                          (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
700                          (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
701                          (((uint64_t)(A) & 0x000000ff00000000LL) >> 8)  | \
702                          (((uint64_t)(A) & 0x00000000ff000000LL) << 8)  | \
703                          (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
704                          (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
705                          (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
706 # else
707 #  define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
708                          (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
709 # endif
711 double ntohd (double d)
713         union
714         {
715                 uint8_t  byte[8];
716                 uint64_t integer;
717                 double   floating;
718         } ret;
720         ret.floating = d;
722         /* NAN in x86 byte order */
723         if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
724                         && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
725                         && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
726                         && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
727         {
728                 return (NAN);
729         }
730         else
731         {
732                 uint64_t tmp;
734                 tmp = ret.integer;
735                 ret.integer = FP_CONVERT (tmp);
736                 return (ret.floating);
737         }
738 } /* double ntohd */
740 double htond (double d)
742         union
743         {
744                 uint8_t  byte[8];
745                 uint64_t integer;
746                 double   floating;
747         } ret;
749         if (isnan (d))
750         {
751                 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
752                 ret.byte[4] = ret.byte[5] = 0x00;
753                 ret.byte[6] = 0xf8;
754                 ret.byte[7] = 0x7f;
755                 return (ret.floating);
756         }
757         else
758         {
759                 uint64_t tmp;
761                 ret.floating = d;
762                 tmp = FP_CONVERT (ret.integer);
763                 ret.integer = tmp;
764                 return (ret.floating);
765         }
766 } /* double htond */
767 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
769 int format_name (char *ret, int ret_len,
770                 const char *hostname,
771                 const char *plugin, const char *plugin_instance,
772                 const char *type, const char *type_instance)
774   char *buffer;
775   size_t buffer_size;
777   buffer = ret;
778   buffer_size = (size_t) ret_len;
780 #define APPEND(str) do {                                               \
781   size_t l = strlen (str);                                             \
782   if (l >= buffer_size)                                                \
783     return (ENOBUFS);                                                  \
784   memcpy (buffer, (str), l);                                           \
785   buffer += l; buffer_size -= l;                                       \
786 } while (0)
788   assert (plugin != NULL);
789   assert (type != NULL);
791   APPEND (hostname);
792   APPEND ("/");
793   APPEND (plugin);
794   if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
795   {
796     APPEND ("-");
797     APPEND (plugin_instance);
798   }
799   APPEND ("/");
800   APPEND (type);
801   if ((type_instance != NULL) && (type_instance[0] != 0))
802   {
803     APPEND ("-");
804     APPEND (type_instance);
805   }
806   assert (buffer_size > 0);
807   buffer[0] = 0;
809 #undef APPEND
810   return (0);
811 } /* int format_name */
813 int format_values (char *ret, size_t ret_len, /* {{{ */
814                 const data_set_t *ds, const value_list_t *vl,
815                 _Bool store_rates)
817         size_t offset = 0;
818         int status;
819         int i;
820         gauge_t *rates = NULL;
822         assert (0 == strcmp (ds->type, vl->type));
824         memset (ret, 0, ret_len);
826 #define BUFFER_ADD(...) do { \
827         status = ssnprintf (ret + offset, ret_len - offset, \
828                         __VA_ARGS__); \
829         if (status < 1) \
830         { \
831                 sfree (rates); \
832                 return (-1); \
833         } \
834         else if (((size_t) status) >= (ret_len - offset)) \
835         { \
836                 sfree (rates); \
837                 return (-1); \
838         } \
839         else \
840                 offset += ((size_t) status); \
841 } while (0)
843         BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
845         for (i = 0; i < ds->ds_num; i++)
846         {
847                 if (ds->ds[i].type == DS_TYPE_GAUGE)
848                         BUFFER_ADD (":%f", vl->values[i].gauge);
849                 else if (store_rates)
850                 {
851                         if (rates == NULL)
852                                 rates = uc_get_rate (ds, vl);
853                         if (rates == NULL)
854                         {
855                                 WARNING ("format_values: "
856                                                 "uc_get_rate failed.");
857                                 return (-1);
858                         }
859                         BUFFER_ADD (":%g", rates[i]);
860                 }
861                 else if (ds->ds[i].type == DS_TYPE_COUNTER)
862                         BUFFER_ADD (":%llu", vl->values[i].counter);
863                 else if (ds->ds[i].type == DS_TYPE_DERIVE)
864                         BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
865                 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
866                         BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
867                 else
868                 {
869                         ERROR ("format_values plugin: Unknown data source type: %i",
870                                         ds->ds[i].type);
871                         sfree (rates);
872                         return (-1);
873                 }
874         } /* for ds->ds_num */
876 #undef BUFFER_ADD
878         sfree (rates);
879         return (0);
880 } /* }}} int format_values */
882 int parse_identifier (char *str, char **ret_host,
883                 char **ret_plugin, char **ret_plugin_instance,
884                 char **ret_type, char **ret_type_instance)
886         char *hostname = NULL;
887         char *plugin = NULL;
888         char *plugin_instance = NULL;
889         char *type = NULL;
890         char *type_instance = NULL;
892         hostname = str;
893         if (hostname == NULL)
894                 return (-1);
896         plugin = strchr (hostname, '/');
897         if (plugin == NULL)
898                 return (-1);
899         *plugin = '\0'; plugin++;
901         type = strchr (plugin, '/');
902         if (type == NULL)
903                 return (-1);
904         *type = '\0'; type++;
906         plugin_instance = strchr (plugin, '-');
907         if (plugin_instance != NULL)
908         {
909                 *plugin_instance = '\0';
910                 plugin_instance++;
911         }
913         type_instance = strchr (type, '-');
914         if (type_instance != NULL)
915         {
916                 *type_instance = '\0';
917                 type_instance++;
918         }
920         *ret_host = hostname;
921         *ret_plugin = plugin;
922         *ret_plugin_instance = plugin_instance;
923         *ret_type = type;
924         *ret_type_instance = type_instance;
925         return (0);
926 } /* int parse_identifier */
928 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
930         char str_copy[6 * DATA_MAX_NAME_LEN];
931         char *host = NULL;
932         char *plugin = NULL;
933         char *plugin_instance = NULL;
934         char *type = NULL;
935         char *type_instance = NULL;
936         int status;
938         if ((str == NULL) || (vl == NULL))
939                 return (EINVAL);
941         sstrncpy (str_copy, str, sizeof (str_copy));
943         status = parse_identifier (str_copy, &host,
944                         &plugin, &plugin_instance,
945                         &type, &type_instance);
946         if (status != 0)
947                 return (status);
949         sstrncpy (vl->host, host, sizeof (vl->host));
950         sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
951         sstrncpy (vl->plugin_instance,
952                         (plugin_instance != NULL) ? plugin_instance : "",
953                         sizeof (vl->plugin_instance));
954         sstrncpy (vl->type, type, sizeof (vl->type));
955         sstrncpy (vl->type_instance,
956                         (type_instance != NULL) ? type_instance : "",
957                         sizeof (vl->type_instance));
959         return (0);
960 } /* }}} int parse_identifier_vl */
962 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
964   char *value;
965   char *endptr = NULL;
966   size_t value_len;
968   if (value_orig == NULL)
969     return (EINVAL);
971   value = strdup (value_orig);
972   if (value == NULL)
973     return (ENOMEM);
974   value_len = strlen (value);
976   while ((value_len > 0) && isspace ((int) value[value_len - 1]))
977   {
978     value[value_len - 1] = 0;
979     value_len--;
980   }
982   switch (ds_type)
983   {
984     case DS_TYPE_COUNTER:
985       ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
986       break;
988     case DS_TYPE_GAUGE:
989       ret_value->gauge = (gauge_t) strtod (value, &endptr);
990       break;
992     case DS_TYPE_DERIVE:
993       ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
994       break;
996     case DS_TYPE_ABSOLUTE:
997       ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
998       break;
1000     default:
1001       sfree (value);
1002       ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1003       return -1;
1004   }
1006   if (value == endptr) {
1007     sfree (value);
1008     ERROR ("parse_value: Failed to parse string as %s: %s.",
1009         DS_TYPE_TO_STRING (ds_type), value);
1010     return -1;
1011   }
1012   else if ((NULL != endptr) && ('\0' != *endptr))
1013     INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1014         "Input string was \"%s\".",
1015         endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1017   sfree (value);
1018   return 0;
1019 } /* int parse_value */
1021 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1023         int i;
1024         char *dummy;
1025         char *ptr;
1026         char *saveptr;
1028         i = -1;
1029         dummy = buffer;
1030         saveptr = NULL;
1031         while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1032         {
1033                 dummy = NULL;
1035                 if (i >= vl->values_len)
1036                 {
1037                         /* Make sure i is invalid. */
1038                         i = vl->values_len + 1;
1039                         break;
1040                 }
1042                 if (i == -1)
1043                 {
1044                         if (strcmp ("N", ptr) == 0)
1045                                 vl->time = cdtime ();
1046                         else
1047                         {
1048                                 char *endptr = NULL;
1049                                 double tmp;
1051                                 errno = 0;
1052                                 tmp = strtod (ptr, &endptr);
1053                                 if ((errno != 0)                    /* Overflow */
1054                                                 || (endptr == ptr)  /* Invalid string */
1055                                                 || (endptr == NULL) /* This should not happen */
1056                                                 || (*endptr != 0))  /* Trailing chars */
1057                                         return (-1);
1059                                 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1060                         }
1061                 }
1062                 else
1063                 {
1064                         if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1065                                 vl->values[i].gauge = NAN;
1066                         else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1067                                 return -1;
1068                 }
1070                 i++;
1071         } /* while (strtok_r) */
1073         if ((ptr != NULL) || (i != vl->values_len))
1074                 return (-1);
1075         return (0);
1076 } /* int parse_values */
1078 #if !HAVE_GETPWNAM_R
1079 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1080                 size_t buflen, struct passwd **pwbufp)
1082         int status = 0;
1083         struct passwd *pw;
1085         memset (pwbuf, '\0', sizeof (struct passwd));
1087         pthread_mutex_lock (&getpwnam_r_lock);
1089         do
1090         {
1091                 pw = getpwnam (name);
1092                 if (pw == NULL)
1093                 {
1094                         status = (errno != 0) ? errno : ENOENT;
1095                         break;
1096                 }
1098 #define GETPWNAM_COPY_MEMBER(member) \
1099                 if (pw->member != NULL) \
1100                 { \
1101                         int len = strlen (pw->member); \
1102                         if (len >= buflen) \
1103                         { \
1104                                 status = ENOMEM; \
1105                                 break; \
1106                         } \
1107                         sstrncpy (buf, pw->member, buflen); \
1108                         pwbuf->member = buf; \
1109                         buf    += (len + 1); \
1110                         buflen -= (len + 1); \
1111                 }
1112                 GETPWNAM_COPY_MEMBER(pw_name);
1113                 GETPWNAM_COPY_MEMBER(pw_passwd);
1114                 GETPWNAM_COPY_MEMBER(pw_gecos);
1115                 GETPWNAM_COPY_MEMBER(pw_dir);
1116                 GETPWNAM_COPY_MEMBER(pw_shell);
1118                 pwbuf->pw_uid = pw->pw_uid;
1119                 pwbuf->pw_gid = pw->pw_gid;
1121                 if (pwbufp != NULL)
1122                         *pwbufp = pwbuf;
1123         } while (0);
1125         pthread_mutex_unlock (&getpwnam_r_lock);
1127         return (status);
1128 } /* int getpwnam_r */
1129 #endif /* !HAVE_GETPWNAM_R */
1131 int notification_init (notification_t *n, int severity, const char *message,
1132                 const char *host,
1133                 const char *plugin, const char *plugin_instance,
1134                 const char *type, const char *type_instance)
1136         memset (n, '\0', sizeof (notification_t));
1138         n->severity = severity;
1140         if (message != NULL)
1141                 sstrncpy (n->message, message, sizeof (n->message));
1142         if (host != NULL)
1143                 sstrncpy (n->host, host, sizeof (n->host));
1144         if (plugin != NULL)
1145                 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1146         if (plugin_instance != NULL)
1147                 sstrncpy (n->plugin_instance, plugin_instance,
1148                                 sizeof (n->plugin_instance));
1149         if (type != NULL)
1150                 sstrncpy (n->type, type, sizeof (n->type));
1151         if (type_instance != NULL)
1152                 sstrncpy (n->type_instance, type_instance,
1153                                 sizeof (n->type_instance));
1155         return (0);
1156 } /* int notification_init */
1158 int walk_directory (const char *dir, dirwalk_callback_f callback,
1159                 void *user_data, int include_hidden)
1161         struct dirent *ent;
1162         DIR *dh;
1163         int success;
1164         int failure;
1166         success = 0;
1167         failure = 0;
1169         if ((dh = opendir (dir)) == NULL)
1170         {
1171                 char errbuf[1024];
1172                 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1173                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1174                 return -1;
1175         }
1177         while ((ent = readdir (dh)) != NULL)
1178         {
1179                 int status;
1180                 
1181                 if (include_hidden)
1182                 {
1183                         if ((strcmp (".", ent->d_name) == 0)
1184                                         || (strcmp ("..", ent->d_name) == 0))
1185                                 continue;
1186                 }
1187                 else /* if (!include_hidden) */
1188                 {
1189                         if (ent->d_name[0]=='.')
1190                                 continue;
1191                 }
1193                 status = (*callback) (dir, ent->d_name, user_data);
1194                 if (status != 0)
1195                         failure++;
1196                 else
1197                         success++;
1198         }
1200         closedir (dh);
1202         if ((success == 0) && (failure > 0))
1203                 return (-1);
1204         return (0);
1207 int read_file_contents (const char *filename, char *buf, int bufsize)
1209         FILE *fh;
1210         int n;
1212         if ((fh = fopen (filename, "r")) == NULL)
1213                 return -1;
1215         n = fread(buf, 1, bufsize, fh);
1216         fclose(fh);
1218         return n;
1221 counter_t counter_diff (counter_t old_value, counter_t new_value)
1223         counter_t diff;
1225         if (old_value > new_value)
1226         {
1227                 if (old_value <= 4294967295U)
1228                         diff = (4294967295U - old_value) + new_value;
1229                 else
1230                         diff = (18446744073709551615ULL - old_value)
1231                                 + new_value;
1232         }
1233         else
1234         {
1235                 diff = new_value - old_value;
1236         }
1238         return (diff);
1239 } /* counter_t counter_diff */
1241 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1242                 rate_to_value_state_t *state,
1243                 int ds_type, cdtime_t t)
1245         gauge_t delta_gauge;
1246         cdtime_t delta_t;
1248         if (ds_type == DS_TYPE_GAUGE)
1249         {
1250                 state->last_value.gauge = rate;
1251                 state->last_time = t;
1253                 *ret_value = state->last_value;
1254                 return (0);
1255         }
1257         /* Counter and absolute can't handle negative rates. Reset "last time"
1258          * to zero, so that the next valid rate will re-initialize the
1259          * structure. */
1260         if ((rate < 0.0)
1261                         && ((ds_type == DS_TYPE_COUNTER)
1262                                 || (ds_type == DS_TYPE_ABSOLUTE)))
1263         {
1264                 memset (state, 0, sizeof (*state));
1265                 return (EINVAL);
1266         }
1268         /* Another invalid state: The time is not increasing. */
1269         if (t <= state->last_time)
1270         {
1271                 memset (state, 0, sizeof (*state));
1272                 return (EINVAL);
1273         }
1275         delta_t = t - state->last_time;
1276         delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1278         /* Previous value is invalid. */
1279         if (state->last_time == 0) /* {{{ */
1280         {
1281                 if (ds_type == DS_TYPE_DERIVE)
1282                 {
1283                         state->last_value.derive = (derive_t) rate;
1284                         state->residual = rate - ((gauge_t) state->last_value.derive);
1285                 }
1286                 else if (ds_type == DS_TYPE_COUNTER)
1287                 {
1288                         state->last_value.counter = (counter_t) rate;
1289                         state->residual = rate - ((gauge_t) state->last_value.counter);
1290                 }
1291                 else if (ds_type == DS_TYPE_ABSOLUTE)
1292                 {
1293                         state->last_value.absolute = (absolute_t) rate;
1294                         state->residual = rate - ((gauge_t) state->last_value.absolute);
1295                 }
1296                 else
1297                 {
1298                         assert (23 == 42);
1299                 }
1301                 state->last_time = t;
1302                 return (EAGAIN);
1303         } /* }}} */
1305         if (ds_type == DS_TYPE_DERIVE)
1306         {
1307                 derive_t delta_derive = (derive_t) delta_gauge;
1309                 state->last_value.derive += delta_derive;
1310                 state->residual = delta_gauge - ((gauge_t) delta_derive);
1311         }
1312         else if (ds_type == DS_TYPE_COUNTER)
1313         {
1314                 counter_t delta_counter = (counter_t) delta_gauge;
1316                 state->last_value.counter += delta_counter;
1317                 state->residual = delta_gauge - ((gauge_t) delta_counter);
1318         }
1319         else if (ds_type == DS_TYPE_ABSOLUTE)
1320         {
1321                 absolute_t delta_absolute = (absolute_t) delta_gauge;
1323                 state->last_value.absolute = delta_absolute;
1324                 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1325         }
1326         else
1327         {
1328                 assert (23 == 42);
1329         }
1331         state->last_time = t;
1332         *ret_value = state->last_value;
1333         return (0);
1334 } /* }}} value_t rate_to_value */
1336 int service_name_to_port_number (const char *service_name)
1338         struct addrinfo *ai_list;
1339         struct addrinfo *ai_ptr;
1340         struct addrinfo ai_hints;
1341         int status;
1342         int service_number;
1344         if (service_name == NULL)
1345                 return (-1);
1347         ai_list = NULL;
1348         memset (&ai_hints, 0, sizeof (ai_hints));
1349         ai_hints.ai_family = AF_UNSPEC;
1351         status = getaddrinfo (/* node = */ NULL, service_name,
1352                         &ai_hints, &ai_list);
1353         if (status != 0)
1354         {
1355                 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1356                                 gai_strerror (status));
1357                 return (-1);
1358         }
1360         service_number = -1;
1361         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1362         {
1363                 if (ai_ptr->ai_family == AF_INET)
1364                 {
1365                         struct sockaddr_in *sa;
1367                         sa = (void *) ai_ptr->ai_addr;
1368                         service_number = (int) ntohs (sa->sin_port);
1369                 }
1370                 else if (ai_ptr->ai_family == AF_INET6)
1371                 {
1372                         struct sockaddr_in6 *sa;
1374                         sa = (void *) ai_ptr->ai_addr;
1375                         service_number = (int) ntohs (sa->sin6_port);
1376                 }
1378                 if ((service_number > 0) && (service_number <= 65535))
1379                         break;
1380         }
1382         freeaddrinfo (ai_list);
1384         if ((service_number > 0) && (service_number <= 65535))
1385                 return (service_number);
1386         return (-1);
1387 } /* int service_name_to_port_number */
1389 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1391         derive_t tmp;
1392         char *endptr;
1394         if ((string == NULL) || (ret_value == NULL))
1395                 return (EINVAL);
1397         errno = 0;
1398         endptr = NULL;
1399         tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1400         if ((endptr == string) || (errno != 0))
1401                 return (-1);
1403         *ret_value = tmp;
1404         return (0);
1405 } /* }}} int strtoderive */