Merge branch 'ff/kstat' into collectd-4.10
[collectd.git] / src / common.c
1 /**
2  * collectd - src/common.c
3  * Copyright (C) 2005-2009  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 verplant.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 **/
24
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include "collectd.h"
30 #include "common.h"
31 #include "plugin.h"
32
33 #if HAVE_PTHREAD_H
34 # include <pthread.h>
35 #endif
36
37 #ifdef HAVE_MATH_H
38 # include <math.h>
39 #endif
40
41 /* for ntohl and htonl */
42 #if HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
45
46 /* for getaddrinfo */
47 #include <sys/types.h>
48 #include <sys/socket.h>
49 #include <netdb.h>
50
51 #if HAVE_NETINET_IN_H
52 # include <netinet/in.h>
53 #endif
54
55 #ifdef HAVE_LIBKSTAT
56 extern kstat_ctl_t *kc;
57 #endif
58
59 #if !HAVE_GETPWNAM_R
60 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
61 #endif
62
63 #if !HAVE_STRERROR_R
64 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
65 #endif
66
67 char *sstrncpy (char *dest, const char *src, size_t n)
68 {
69         strncpy (dest, src, n);
70         dest[n - 1] = '\0';
71
72         return (dest);
73 } /* char *sstrncpy */
74
75 int ssnprintf (char *dest, size_t n, const char *format, ...)
76 {
77         int ret = 0;
78         va_list ap;
79
80         va_start (ap, format);
81         ret = vsnprintf (dest, n, format, ap);
82         dest[n - 1] = '\0';
83         va_end (ap);
84
85         return (ret);
86 } /* int ssnprintf */
87
88 char *sstrdup (const char *s)
89 {
90         char *r;
91         size_t sz;
92
93         if (s == NULL)
94                 return (NULL);
95
96         /* Do not use `strdup' here, because it's not specified in POSIX. It's
97          * ``only'' an XSI extension. */
98         sz = strlen (s) + 1;
99         r = (char *) malloc (sizeof (char) * sz);
100         if (r == NULL)
101         {
102                 ERROR ("sstrdup: Out of memory.");
103                 exit (3);
104         }
105         memcpy (r, s, sizeof (char) * sz);
106
107         return (r);
108 } /* char *sstrdup */
109
110 /* Even though Posix requires "strerror_r" to return an "int",
111  * some systems (e.g. the GNU libc) return a "char *" _and_
112  * ignore the second argument ... -tokkee */
113 char *sstrerror (int errnum, char *buf, size_t buflen)
114 {
115         buf[0] = '\0';
116
117 #if !HAVE_STRERROR_R
118         {
119                 char *temp;
120
121                 pthread_mutex_lock (&strerror_r_lock);
122
123                 temp = strerror (errnum);
124                 sstrncpy (buf, temp, buflen);
125
126                 pthread_mutex_unlock (&strerror_r_lock);
127         }
128 /* #endif !HAVE_STRERROR_R */
129
130 #elif STRERROR_R_CHAR_P
131         {
132                 char *temp;
133                 temp = strerror_r (errnum, buf, buflen);
134                 if (buf[0] == '\0')
135                 {
136                         if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
137                                 sstrncpy (buf, temp, buflen);
138                         else
139                                 sstrncpy (buf, "strerror_r did not return "
140                                                 "an error message", buflen);
141                 }
142         }
143 /* #endif STRERROR_R_CHAR_P */
144
145 #else
146         if (strerror_r (errnum, buf, buflen) != 0)
147         {
148                 ssnprintf (buf, buflen, "Error #%i; "
149                                 "Additionally, strerror_r failed.",
150                                 errnum);
151         }
152 #endif /* STRERROR_R_CHAR_P */
153
154         return (buf);
155 } /* char *sstrerror */
156
157 void *smalloc (size_t size)
158 {
159         void *r;
160
161         if ((r = malloc (size)) == NULL)
162         {
163                 ERROR ("Not enough memory.");
164                 exit (3);
165         }
166
167         return (r);
168 } /* void *smalloc */
169
170 #if 0
171 void sfree (void **ptr)
172 {
173         if (ptr == NULL)
174                 return;
175
176         if (*ptr != NULL)
177                 free (*ptr);
178
179         *ptr = NULL;
180 }
181 #endif
182
183 ssize_t sread (int fd, void *buf, size_t count)
184 {
185         char    *ptr;
186         size_t   nleft;
187         ssize_t  status;
188
189         ptr   = (char *) buf;
190         nleft = count;
191
192         while (nleft > 0)
193         {
194                 status = read (fd, (void *) ptr, nleft);
195
196                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
197                         continue;
198
199                 if (status < 0)
200                         return (status);
201
202                 if (status == 0)
203                 {
204                         DEBUG ("Received EOF from fd %i. "
205                                         "Closing fd and returning error.",
206                                         fd);
207                         close (fd);
208                         return (-1);
209                 }
210
211                 assert ((0 > status) || (nleft >= (size_t)status));
212
213                 nleft = nleft - status;
214                 ptr   = ptr   + status;
215         }
216
217         return (0);
218 }
219
220
221 ssize_t swrite (int fd, const void *buf, size_t count)
222 {
223         const char *ptr;
224         size_t      nleft;
225         ssize_t     status;
226
227         ptr   = (const char *) buf;
228         nleft = count;
229
230         while (nleft > 0)
231         {
232                 status = write (fd, (const void *) ptr, nleft);
233
234                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
235                         continue;
236
237                 if (status < 0)
238                         return (status);
239
240                 nleft = nleft - status;
241                 ptr   = ptr   + status;
242         }
243
244         return (0);
245 }
246
247 int strsplit (char *string, char **fields, size_t size)
248 {
249         size_t i;
250         char *ptr;
251         char *saveptr;
252
253         i = 0;
254         ptr = string;
255         saveptr = NULL;
256         while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
257         {
258                 ptr = NULL;
259                 i++;
260
261                 if (i >= size)
262                         break;
263         }
264
265         return ((int) i);
266 }
267
268 int strjoin (char *dst, size_t dst_len,
269                 char **fields, size_t fields_num,
270                 const char *sep)
271 {
272         size_t field_len;
273         size_t sep_len;
274         int i;
275
276         memset (dst, '\0', dst_len);
277
278         if (fields_num <= 0)
279                 return (-1);
280
281         sep_len = 0;
282         if (sep != NULL)
283                 sep_len = strlen (sep);
284
285         for (i = 0; i < (int)fields_num; i++)
286         {
287                 if ((i > 0) && (sep_len > 0))
288                 {
289                         if (dst_len <= sep_len)
290                                 return (-1);
291
292                         strncat (dst, sep, dst_len);
293                         dst_len -= sep_len;
294                 }
295
296                 field_len = strlen (fields[i]);
297
298                 if (dst_len <= field_len)
299                         return (-1);
300
301                 strncat (dst, fields[i], dst_len);
302                 dst_len -= field_len;
303         }
304
305         return (strlen (dst));
306 }
307
308 int strsubstitute (char *str, char c_from, char c_to)
309 {
310         int ret;
311
312         if (str == NULL)
313                 return (-1);
314
315         ret = 0;
316         while (*str != '\0')
317         {
318                 if (*str == c_from)
319                 {
320                         *str = c_to;
321                         ret++;
322                 }
323                 str++;
324         }
325
326         return (ret);
327 } /* int strsubstitute */
328
329 int strunescape (char *buf, size_t buf_len)
330 {
331         size_t i;
332
333         for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
334         {
335                 if (buf[i] != '\\')
336                         continue;
337
338                 if ((i >= buf_len) || (buf[i + 1] == '\0')) {
339                         ERROR ("string unescape: backslash found at end of string.");
340                         return (-1);
341                 }
342
343                 switch (buf[i + 1]) {
344                         case 't':
345                                 buf[i] = '\t';
346                                 break;
347                         case 'n':
348                                 buf[i] = '\n';
349                                 break;
350                         case 'r':
351                                 buf[i] = '\r';
352                                 break;
353                         default:
354                                 buf[i] = buf[i + 1];
355                                 break;
356                 }
357
358                 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
359         }
360         return (0);
361 } /* int strunescape */
362
363 int escape_slashes (char *buf, int buf_len)
364 {
365         int i;
366
367         if (strcmp (buf, "/") == 0)
368         {
369                 if (buf_len < 5)
370                         return (-1);
371
372                 strncpy (buf, "root", buf_len);
373                 return (0);
374         }
375
376         if (buf_len <= 1)
377                 return (0);
378
379         /* Move one to the left */
380         if (buf[0] == '/')
381                 memmove (buf, buf + 1, buf_len - 1);
382
383         for (i = 0; i < buf_len - 1; i++)
384         {
385                 if (buf[i] == '\0')
386                         break;
387                 else if (buf[i] == '/')
388                         buf[i] = '_';
389         }
390         buf[i] = '\0';
391
392         return (0);
393 } /* int escape_slashes */
394
395 void replace_special (char *buffer, size_t buffer_size)
396 {
397         size_t i;
398
399         for (i = 0; i < buffer_size; i++)
400         {
401                 if (buffer[i] == 0)
402                         return;
403                 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
404                         buffer[i] = '_';
405         }
406 } /* void replace_special */
407
408 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
409 {
410         struct timeval *larger;
411         struct timeval *smaller;
412
413         int status;
414
415         NORMALIZE_TIMEVAL (tv0);
416         NORMALIZE_TIMEVAL (tv1);
417
418         if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
419         {
420                 if (delta != NULL) {
421                         delta->tv_sec  = 0;
422                         delta->tv_usec = 0;
423                 }
424                 return (0);
425         }
426
427         if ((tv0.tv_sec < tv1.tv_sec)
428                         || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
429         {
430                 larger  = &tv1;
431                 smaller = &tv0;
432                 status  = -1;
433         }
434         else
435         {
436                 larger  = &tv0;
437                 smaller = &tv1;
438                 status  = 1;
439         }
440
441         if (delta != NULL) {
442                 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
443
444                 if (smaller->tv_usec <= larger->tv_usec)
445                         delta->tv_usec = larger->tv_usec - smaller->tv_usec;
446                 else
447                 {
448                         --delta->tv_sec;
449                         delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
450                 }
451         }
452
453         assert ((delta == NULL)
454                         || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
455
456         return (status);
457 } /* int timeval_cmp */
458
459 int check_create_dir (const char *file_orig)
460 {
461         struct stat statbuf;
462
463         char  file_copy[512];
464         char  dir[512];
465         int   dir_len = 512;
466         char *fields[16];
467         int   fields_num;
468         char *ptr;
469         char *saveptr;
470         int   last_is_file = 1;
471         int   path_is_absolute = 0;
472         size_t len;
473         int   i;
474
475         /*
476          * Sanity checks first
477          */
478         if (file_orig == NULL)
479                 return (-1);
480
481         if ((len = strlen (file_orig)) < 1)
482                 return (-1);
483         else if (len >= sizeof (file_copy))
484                 return (-1);
485
486         /*
487          * If `file_orig' ends in a slash the last component is a directory,
488          * otherwise it's a file. Act accordingly..
489          */
490         if (file_orig[len - 1] == '/')
491                 last_is_file = 0;
492         if (file_orig[0] == '/')
493                 path_is_absolute = 1;
494
495         /*
496          * Create a copy for `strtok_r' to destroy
497          */
498         sstrncpy (file_copy, file_orig, sizeof (file_copy));
499
500         /*
501          * Break into components. This will eat up several slashes in a row and
502          * remove leading and trailing slashes..
503          */
504         ptr = file_copy;
505         saveptr = NULL;
506         fields_num = 0;
507         while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
508         {
509                 ptr = NULL;
510                 fields_num++;
511
512                 if (fields_num >= 16)
513                         break;
514         }
515
516         /*
517          * For each component, do..
518          */
519         for (i = 0; i < (fields_num - last_is_file); i++)
520         {
521                 /*
522                  * Do not create directories that start with a dot. This
523                  * prevents `../../' attacks and other likely malicious
524                  * behavior.
525                  */
526                 if (fields[i][0] == '.')
527                 {
528                         ERROR ("Cowardly refusing to create a directory that "
529                                         "begins with a `.' (dot): `%s'", file_orig);
530                         return (-2);
531                 }
532
533                 /*
534                  * Join the components together again
535                  */
536                 dir[0] = '/';
537                 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
538                                         fields, i + 1, "/") < 0)
539                 {
540                         ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
541                         return (-1);
542                 }
543
544                 while (42) {
545                         if ((stat (dir, &statbuf) == -1)
546                                         && (lstat (dir, &statbuf) == -1))
547                         {
548                                 if (errno == ENOENT)
549                                 {
550                                         if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
551                                                 break;
552
553                                         /* this might happen, if a different thread created
554                                          * the directory in the meantime
555                                          * => call stat() again to check for S_ISDIR() */
556                                         if (EEXIST == errno)
557                                                 continue;
558
559                                         char errbuf[1024];
560                                         ERROR ("check_create_dir: mkdir (%s): %s", dir,
561                                                         sstrerror (errno,
562                                                                 errbuf, sizeof (errbuf)));
563                                         return (-1);
564                                 }
565                                 else
566                                 {
567                                         char errbuf[1024];
568                                         ERROR ("check_create_dir: stat (%s): %s", dir,
569                                                         sstrerror (errno, errbuf,
570                                                                 sizeof (errbuf)));
571                                         return (-1);
572                                 }
573                         }
574                         else if (!S_ISDIR (statbuf.st_mode))
575                         {
576                                 ERROR ("check_create_dir: `%s' exists but is not "
577                                                 "a directory!", dir);
578                                 return (-1);
579                         }
580                         break;
581                 }
582         }
583
584         return (0);
585 } /* check_create_dir */
586
587 #ifdef HAVE_LIBKSTAT
588 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
589 {
590         char ident[128];
591
592         *ksp_ptr = NULL;
593         
594         if (kc == NULL)
595                 return (-1);
596
597         ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
598
599         *ksp_ptr = kstat_lookup (kc, module, instance, name);
600         if (*ksp_ptr == NULL)
601         {
602                 ERROR ("get_kstat: Cound not find kstat %s", ident);
603                 return (-1);
604         }
605
606         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
607         {
608                 ERROR ("get_kstat: kstat %s has wrong type", ident);
609                 *ksp_ptr = NULL;
610                 return (-1);
611         }
612
613 #ifdef assert
614         assert (*ksp_ptr != NULL);
615         assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
616 #endif
617
618         if (kstat_read (kc, *ksp_ptr, NULL) == -1)
619         {
620                 ERROR ("get_kstat: kstat %s could not be read", ident);
621                 return (-1);
622         }
623
624         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
625         {
626                 ERROR ("get_kstat: kstat %s has wrong type", ident);
627                 return (-1);
628         }
629
630         return (0);
631 }
632
633 long long get_kstat_value (kstat_t *ksp, char *name)
634 {
635         kstat_named_t *kn;
636         long long retval = -1LL;
637
638         if (ksp == NULL)
639         {
640                 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
641                 return (-1LL);
642         }
643         else if (ksp->ks_type != KSTAT_TYPE_NAMED)
644         {
645                 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
646                                 "is not KSTAT_TYPE_NAMED (%#x).",
647                                 name,
648                                 (unsigned int) ksp->ks_type,
649                                 (unsigned int) KSTAT_TYPE_NAMED);
650                 return (-1LL);
651         }
652
653         if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
654                 return (-1LL);
655
656         if (kn->data_type == KSTAT_DATA_INT32)
657                 retval = (long long) kn->value.i32;
658         else if (kn->data_type == KSTAT_DATA_UINT32)
659                 retval = (long long) kn->value.ui32;
660         else if (kn->data_type == KSTAT_DATA_INT64)
661                 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
662         else if (kn->data_type == KSTAT_DATA_UINT64)
663                 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
664         else
665                 WARNING ("get_kstat_value: Not a numeric value: %s", name);
666                  
667         return (retval);
668 }
669 #endif /* HAVE_LIBKSTAT */
670
671 #ifndef HAVE_HTONLL
672 unsigned long long ntohll (unsigned long long n)
673 {
674 #if BYTE_ORDER == BIG_ENDIAN
675         return (n);
676 #else
677         return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
678 #endif
679 } /* unsigned long long ntohll */
680
681 unsigned long long htonll (unsigned long long n)
682 {
683 #if BYTE_ORDER == BIG_ENDIAN
684         return (n);
685 #else
686         return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
687 #endif
688 } /* unsigned long long htonll */
689 #endif /* HAVE_HTONLL */
690
691 #if FP_LAYOUT_NEED_NOTHING
692 /* Well, we need nothing.. */
693 /* #endif FP_LAYOUT_NEED_NOTHING */
694
695 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
696 # if FP_LAYOUT_NEED_ENDIANFLIP
697 #  define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
698                          (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
699                          (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
700                          (((uint64_t)(A) & 0x000000ff00000000LL) >> 8)  | \
701                          (((uint64_t)(A) & 0x00000000ff000000LL) << 8)  | \
702                          (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
703                          (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
704                          (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
705 # else
706 #  define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
707                          (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
708 # endif
709
710 double ntohd (double d)
711 {
712         union
713         {
714                 uint8_t  byte[8];
715                 uint64_t integer;
716                 double   floating;
717         } ret;
718
719         ret.floating = d;
720
721         /* NAN in x86 byte order */
722         if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
723                         && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
724                         && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
725                         && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
726         {
727                 return (NAN);
728         }
729         else
730         {
731                 uint64_t tmp;
732
733                 tmp = ret.integer;
734                 ret.integer = FP_CONVERT (tmp);
735                 return (ret.floating);
736         }
737 } /* double ntohd */
738
739 double htond (double d)
740 {
741         union
742         {
743                 uint8_t  byte[8];
744                 uint64_t integer;
745                 double   floating;
746         } ret;
747
748         if (isnan (d))
749         {
750                 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
751                 ret.byte[4] = ret.byte[5] = 0x00;
752                 ret.byte[6] = 0xf8;
753                 ret.byte[7] = 0x7f;
754                 return (ret.floating);
755         }
756         else
757         {
758                 uint64_t tmp;
759
760                 ret.floating = d;
761                 tmp = FP_CONVERT (ret.integer);
762                 ret.integer = tmp;
763                 return (ret.floating);
764         }
765 } /* double htond */
766 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
767
768 int format_name (char *ret, int ret_len,
769                 const char *hostname,
770                 const char *plugin, const char *plugin_instance,
771                 const char *type, const char *type_instance)
772 {
773         int  status;
774
775         assert (plugin != NULL);
776         assert (type != NULL);
777
778         if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
779         {
780                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
781                         status = ssnprintf (ret, ret_len, "%s/%s/%s",
782                                         hostname, plugin, type);
783                 else
784                         status = ssnprintf (ret, ret_len, "%s/%s/%s-%s",
785                                         hostname, plugin, type,
786                                         type_instance);
787         }
788         else
789         {
790                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
791                         status = ssnprintf (ret, ret_len, "%s/%s-%s/%s",
792                                         hostname, plugin, plugin_instance,
793                                         type);
794                 else
795                         status = ssnprintf (ret, ret_len, "%s/%s-%s/%s-%s",
796                                         hostname, plugin, plugin_instance,
797                                         type, type_instance);
798         }
799
800         if ((status < 1) || (status >= ret_len))
801                 return (-1);
802         return (0);
803 } /* int format_name */
804
805 int parse_identifier (char *str, char **ret_host,
806                 char **ret_plugin, char **ret_plugin_instance,
807                 char **ret_type, char **ret_type_instance)
808 {
809         char *hostname = NULL;
810         char *plugin = NULL;
811         char *plugin_instance = NULL;
812         char *type = NULL;
813         char *type_instance = NULL;
814
815         hostname = str;
816         if (hostname == NULL)
817                 return (-1);
818
819         plugin = strchr (hostname, '/');
820         if (plugin == NULL)
821                 return (-1);
822         *plugin = '\0'; plugin++;
823
824         type = strchr (plugin, '/');
825         if (type == NULL)
826                 return (-1);
827         *type = '\0'; type++;
828
829         plugin_instance = strchr (plugin, '-');
830         if (plugin_instance != NULL)
831         {
832                 *plugin_instance = '\0';
833                 plugin_instance++;
834         }
835
836         type_instance = strchr (type, '-');
837         if (type_instance != NULL)
838         {
839                 *type_instance = '\0';
840                 type_instance++;
841         }
842
843         *ret_host = hostname;
844         *ret_plugin = plugin;
845         *ret_plugin_instance = plugin_instance;
846         *ret_type = type;
847         *ret_type_instance = type_instance;
848         return (0);
849 } /* int parse_identifier */
850
851 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
852 {
853   char *value;
854   char *endptr = NULL;
855   size_t value_len;
856
857   if (value_orig == NULL)
858     return (EINVAL);
859
860   value = strdup (value_orig);
861   if (value == NULL)
862     return (ENOMEM);
863   value_len = strlen (value);
864
865   while ((value_len > 0) && isspace ((int) value[value_len - 1]))
866   {
867     value[value_len - 1] = 0;
868     value_len--;
869   }
870
871   switch (ds_type)
872   {
873     case DS_TYPE_COUNTER:
874       ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
875       break;
876
877     case DS_TYPE_GAUGE:
878       ret_value->gauge = (gauge_t) strtod (value, &endptr);
879       break;
880
881     case DS_TYPE_DERIVE:
882       ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
883       break;
884
885     case DS_TYPE_ABSOLUTE:
886       ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
887       break;
888
889     default:
890       sfree (value);
891       ERROR ("parse_value: Invalid data source type: %i.", ds_type);
892       return -1;
893   }
894
895   if (value == endptr) {
896     sfree (value);
897     ERROR ("parse_value: Failed to parse string as %s: %s.",
898         DS_TYPE_TO_STRING (ds_type), value);
899     return -1;
900   }
901   else if ((NULL != endptr) && ('\0' != *endptr))
902     INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
903         "Input string was \"%s\".",
904         endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
905
906   sfree (value);
907   return 0;
908 } /* int parse_value */
909
910 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
911 {
912         int i;
913         char *dummy;
914         char *ptr;
915         char *saveptr;
916
917         i = -1;
918         dummy = buffer;
919         saveptr = NULL;
920         while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
921         {
922                 dummy = NULL;
923
924                 if (i >= vl->values_len)
925                 {
926                         /* Make sure i is invalid. */
927                         i = vl->values_len + 1;
928                         break;
929                 }
930
931                 if (i == -1)
932                 {
933                         if (strcmp ("N", ptr) == 0)
934                                 vl->time = time (NULL);
935                         else
936                                 vl->time = (time_t) atoi (ptr);
937                 }
938                 else
939                 {
940                         if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
941                                 vl->values[i].gauge = NAN;
942                         else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
943                                 return -1;
944                 }
945
946                 i++;
947         } /* while (strtok_r) */
948
949         if ((ptr != NULL) || (i != vl->values_len))
950                 return (-1);
951         return (0);
952 } /* int parse_values */
953
954 #if !HAVE_GETPWNAM_R
955 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
956                 size_t buflen, struct passwd **pwbufp)
957 {
958         int status = 0;
959         struct passwd *pw;
960
961         memset (pwbuf, '\0', sizeof (struct passwd));
962
963         pthread_mutex_lock (&getpwnam_r_lock);
964
965         do
966         {
967                 pw = getpwnam (name);
968                 if (pw == NULL)
969                 {
970                         status = (errno != 0) ? errno : ENOENT;
971                         break;
972                 }
973
974 #define GETPWNAM_COPY_MEMBER(member) \
975                 if (pw->member != NULL) \
976                 { \
977                         int len = strlen (pw->member); \
978                         if (len >= buflen) \
979                         { \
980                                 status = ENOMEM; \
981                                 break; \
982                         } \
983                         sstrncpy (buf, pw->member, buflen); \
984                         pwbuf->member = buf; \
985                         buf    += (len + 1); \
986                         buflen -= (len + 1); \
987                 }
988                 GETPWNAM_COPY_MEMBER(pw_name);
989                 GETPWNAM_COPY_MEMBER(pw_passwd);
990                 GETPWNAM_COPY_MEMBER(pw_gecos);
991                 GETPWNAM_COPY_MEMBER(pw_dir);
992                 GETPWNAM_COPY_MEMBER(pw_shell);
993
994                 pwbuf->pw_uid = pw->pw_uid;
995                 pwbuf->pw_gid = pw->pw_gid;
996
997                 if (pwbufp != NULL)
998                         *pwbufp = pwbuf;
999         } while (0);
1000
1001         pthread_mutex_unlock (&getpwnam_r_lock);
1002
1003         return (status);
1004 } /* int getpwnam_r */
1005 #endif /* !HAVE_GETPWNAM_R */
1006
1007 int notification_init (notification_t *n, int severity, const char *message,
1008                 const char *host,
1009                 const char *plugin, const char *plugin_instance,
1010                 const char *type, const char *type_instance)
1011 {
1012         memset (n, '\0', sizeof (notification_t));
1013
1014         n->severity = severity;
1015
1016         if (message != NULL)
1017                 sstrncpy (n->message, message, sizeof (n->message));
1018         if (host != NULL)
1019                 sstrncpy (n->host, host, sizeof (n->host));
1020         if (plugin != NULL)
1021                 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1022         if (plugin_instance != NULL)
1023                 sstrncpy (n->plugin_instance, plugin_instance,
1024                                 sizeof (n->plugin_instance));
1025         if (type != NULL)
1026                 sstrncpy (n->type, type, sizeof (n->type));
1027         if (type_instance != NULL)
1028                 sstrncpy (n->type_instance, type_instance,
1029                                 sizeof (n->type_instance));
1030
1031         return (0);
1032 } /* int notification_init */
1033
1034 int walk_directory (const char *dir, dirwalk_callback_f callback,
1035                 void *user_data, int include_hidden)
1036 {
1037         struct dirent *ent;
1038         DIR *dh;
1039         int success;
1040         int failure;
1041
1042         success = 0;
1043         failure = 0;
1044
1045         if ((dh = opendir (dir)) == NULL)
1046         {
1047                 char errbuf[1024];
1048                 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1049                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1050                 return -1;
1051         }
1052
1053         while ((ent = readdir (dh)) != NULL)
1054         {
1055                 int status;
1056                 
1057                 if (include_hidden)
1058                 {
1059                         if ((strcmp (".", ent->d_name) == 0)
1060                                         || (strcmp ("..", ent->d_name) == 0))
1061                                 continue;
1062                 }
1063                 else /* if (!include_hidden) */
1064                 {
1065                         if (ent->d_name[0]=='.')
1066                                 continue;
1067                 }
1068
1069                 status = (*callback) (dir, ent->d_name, user_data);
1070                 if (status != 0)
1071                         failure++;
1072                 else
1073                         success++;
1074         }
1075
1076         closedir (dh);
1077
1078         if ((success == 0) && (failure > 0))
1079                 return (-1);
1080         return (0);
1081 }
1082
1083 int read_file_contents (const char *filename, char *buf, int bufsize)
1084 {
1085         FILE *fh;
1086         int n;
1087
1088         if ((fh = fopen (filename, "r")) == NULL)
1089                 return -1;
1090
1091         n = fread(buf, 1, bufsize, fh);
1092         fclose(fh);
1093
1094         return n;
1095 }
1096
1097 counter_t counter_diff (counter_t old_value, counter_t new_value)
1098 {
1099         counter_t diff;
1100
1101         if (old_value > new_value)
1102         {
1103                 if (old_value <= 4294967295U)
1104                         diff = (4294967295U - old_value) + new_value;
1105                 else
1106                         diff = (18446744073709551615ULL - old_value)
1107                                 + new_value;
1108         }
1109         else
1110         {
1111                 diff = new_value - old_value;
1112         }
1113
1114         return (diff);
1115 } /* counter_t counter_to_gauge */
1116
1117 int service_name_to_port_number (const char *service_name)
1118 {
1119         struct addrinfo *ai_list;
1120         struct addrinfo *ai_ptr;
1121         struct addrinfo ai_hints;
1122         int status;
1123         int service_number;
1124
1125         if (service_name == NULL)
1126                 return (-1);
1127
1128         ai_list = NULL;
1129         memset (&ai_hints, 0, sizeof (ai_hints));
1130         ai_hints.ai_family = AF_UNSPEC;
1131
1132         status = getaddrinfo (/* node = */ NULL, service_name,
1133                         &ai_hints, &ai_list);
1134         if (status != 0)
1135         {
1136                 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1137                                 gai_strerror (status));
1138                 return (-1);
1139         }
1140
1141         service_number = -1;
1142         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1143         {
1144                 if (ai_ptr->ai_family == AF_INET)
1145                 {
1146                         struct sockaddr_in *sa;
1147
1148                         sa = (void *) ai_ptr->ai_addr;
1149                         service_number = (int) ntohs (sa->sin_port);
1150                 }
1151                 else if (ai_ptr->ai_family == AF_INET6)
1152                 {
1153                         struct sockaddr_in6 *sa;
1154
1155                         sa = (void *) ai_ptr->ai_addr;
1156                         service_number = (int) ntohs (sa->sin6_port);
1157                 }
1158
1159                 if ((service_number > 0) && (service_number <= 65535))
1160                         break;
1161         }
1162
1163         freeaddrinfo (ai_list);
1164
1165         if ((service_number > 0) && (service_number <= 65535))
1166                 return (service_number);
1167         return (-1);
1168 } /* int service_name_to_port_number */
1169
1170 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1171 {
1172         derive_t tmp;
1173         char *endptr;
1174
1175         if ((string == NULL) || (ret_value == NULL))
1176                 return (EINVAL);
1177
1178         errno = 0;
1179         endptr = NULL;
1180         tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1181         if ((endptr == string) || (errno != 0))
1182                 return (-1);
1183
1184         *ret_value = tmp;
1185         return (0);
1186 } /* }}} int strtoderive */