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