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