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