Merge branch 'collectd-4.2' into collectd-4.3
[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 "common.h"
28 #include "plugin.h"
29
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
33
34 #ifdef HAVE_MATH_H
35 # include <math.h>
36 #endif
37
38 /* for ntohl and htonl */
39 #if HAVE_ARPA_INET_H
40 # include <arpa/inet.h>
41 #endif
42
43 #ifdef HAVE_LIBKSTAT
44 extern kstat_ctl_t *kc;
45 #endif
46
47 #if !HAVE_GETPWNAM_R
48 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
49 #endif
50
51 #if !HAVE_STRERROR_R
52 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
53 #endif
54
55 void sstrncpy (char *d, const char *s, int len)
56 {
57         strncpy (d, s, len);
58         d[len - 1] = '\0';
59 }
60
61 char *sstrdup (const char *s)
62 {
63         char *r;
64
65         if (s == NULL)
66                 return (NULL);
67
68         if((r = strdup (s)) == NULL)
69         {
70                 DEBUG ("Not enough memory.");
71                 exit(3);
72         }
73
74         return (r);
75 }
76
77 /* Even though Posix requires "strerror_r" to return an "int",
78  * some systems (e.g. the GNU libc) return a "char *" _and_
79  * ignore the second argument ... -tokkee */
80 char *sstrerror (int errnum, char *buf, size_t buflen)
81 {
82         buf[0] = '\0';
83
84 #if !HAVE_STRERROR_R
85         {
86                 char *temp;
87
88                 pthread_mutex_lock (&strerror_r_lock);
89
90                 temp = strerror (errnum);
91                 strncpy (buf, temp, buflen);
92
93                 pthread_mutex_unlock (&strerror_r_lock);
94         }
95 /* #endif !HAVE_STRERROR_R */
96
97 #elif STRERROR_R_CHAR_P
98         {
99                 char *temp;
100                 temp = strerror_r (errnum, buf, buflen);
101                 if (buf[0] == '\0')
102                 {
103                         if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
104                                 strncpy (buf, temp, buflen);
105                         else
106                                 strncpy (buf, "strerror_r did not return "
107                                                 "an error message", buflen);
108                 }
109         }
110 /* #endif STRERROR_R_CHAR_P */
111
112 #else
113         if (strerror_r (errnum, buf, buflen) != 0)
114         {
115                 snprintf (buf, buflen, "Error #%i; "
116                                 "Additionally, strerror_r failed.",
117                                 errnum);
118         }
119 #endif /* STRERROR_R_CHAR_P */
120
121         buf[buflen - 1] = '\0';
122         return (buf);
123 } /* char *sstrerror */
124
125 void *smalloc (size_t size)
126 {
127         void *r;
128
129         if ((r = malloc (size)) == NULL)
130         {
131                 DEBUG("Not enough memory.");
132                 exit(3);
133         }
134
135         return r;
136 }
137
138 #if 0
139 void sfree (void **ptr)
140 {
141         if (ptr == NULL)
142                 return;
143
144         if (*ptr != NULL)
145                 free (*ptr);
146
147         *ptr = NULL;
148 }
149 #endif
150
151 ssize_t sread (int fd, void *buf, size_t count)
152 {
153         char    *ptr;
154         size_t   nleft;
155         ssize_t  status;
156
157         ptr   = (char *) buf;
158         nleft = count;
159
160         while (nleft > 0)
161         {
162                 status = read (fd, (void *) ptr, nleft);
163
164                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
165                         continue;
166
167                 if (status < 0)
168                         return (status);
169
170                 if (status == 0)
171                 {
172                         DEBUG ("Received EOF from fd %i. "
173                                         "Closing fd and returning error.",
174                                         fd);
175                         close (fd);
176                         return (-1);
177                 }
178
179                 assert ((0 > status) || (nleft >= (size_t)status));
180
181                 nleft = nleft - status;
182                 ptr   = ptr   + status;
183         }
184
185         return (0);
186 }
187
188
189 ssize_t swrite (int fd, const void *buf, size_t count)
190 {
191         const char *ptr;
192         size_t      nleft;
193         ssize_t     status;
194
195         ptr   = (const char *) buf;
196         nleft = count;
197
198         while (nleft > 0)
199         {
200                 status = write (fd, (const void *) ptr, nleft);
201
202                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
203                         continue;
204
205                 if (status < 0)
206                         return (status);
207
208                 nleft = nleft - status;
209                 ptr   = ptr   + status;
210         }
211
212         return (0);
213 }
214
215 int strsplit (char *string, char **fields, size_t size)
216 {
217         size_t i;
218         char *ptr;
219         char *saveptr;
220
221         i = 0;
222         ptr = string;
223         saveptr = NULL;
224         while ((fields[i] = strtok_r (ptr, " \t", &saveptr)) != NULL)
225         {
226                 ptr = NULL;
227                 i++;
228
229                 if (i >= size)
230                         break;
231         }
232
233         return (i);
234 }
235
236 int strjoin (char *dst, size_t dst_len,
237                 char **fields, size_t fields_num,
238                 const char *sep)
239 {
240         size_t field_len;
241         size_t sep_len;
242         int i;
243
244         memset (dst, '\0', dst_len);
245
246         if (fields_num <= 0)
247                 return (-1);
248
249         sep_len = 0;
250         if (sep != NULL)
251                 sep_len = strlen (sep);
252
253         for (i = 0; i < (int)fields_num; i++)
254         {
255                 if ((i > 0) && (sep_len > 0))
256                 {
257                         if (dst_len <= sep_len)
258                                 return (-1);
259
260                         strncat (dst, sep, dst_len);
261                         dst_len -= sep_len;
262                 }
263
264                 field_len = strlen (fields[i]);
265
266                 if (dst_len <= field_len)
267                         return (-1);
268
269                 strncat (dst, fields[i], dst_len);
270                 dst_len -= field_len;
271         }
272
273         return (strlen (dst));
274 }
275
276 int strsubstitute (char *str, char c_from, char c_to)
277 {
278         int ret;
279
280         if (str == NULL)
281                 return (-1);
282
283         ret = 0;
284         while (*str != '\0')
285         {
286                 if (*str == c_from)
287                 {
288                         *str = c_to;
289                         ret++;
290                 }
291                 str++;
292         }
293
294         return (ret);
295 } /* int strsubstitute */
296
297 int escape_slashes (char *buf, int buf_len)
298 {
299         int i;
300
301         if (strcmp (buf, "/") == 0)
302         {
303                 if (buf_len < 5)
304                         return (-1);
305
306                 strncpy (buf, "root", buf_len);
307                 return (0);
308         }
309
310         if (buf_len <= 1)
311                 return (0);
312
313         /* Move one to the left */
314         if (buf[0] == '/')
315                 memmove (buf, buf + 1, buf_len - 1);
316
317         for (i = 0; i < buf_len - 1; i++)
318         {
319                 if (buf[i] == '\0')
320                         break;
321                 else if (buf[i] == '/')
322                         buf[i] = '_';
323         }
324         buf[i] = '\0';
325
326         return (0);
327 } /* int escape_slashes */
328
329 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
330 {
331         if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
332                 return (-2);
333
334         if ((tv0->tv_sec < tv1->tv_sec)
335                         || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
336                 return (-1);
337
338         ret->tv_sec  = tv0->tv_sec - tv1->tv_sec;
339         ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
340
341         if (ret->tv_nsec < 0)
342         {
343                 assert (ret->tv_sec > 0);
344
345                 ret->tv_nsec += 1000000000;
346                 ret->tv_sec  -= 1;
347         }
348
349         return (0);
350 }
351
352 int check_create_dir (const char *file_orig)
353 {
354         struct stat statbuf;
355
356         char  file_copy[512];
357         char  dir[512];
358         int   dir_len = 512;
359         char *fields[16];
360         int   fields_num;
361         char *ptr;
362         char *saveptr;
363         int   last_is_file = 1;
364         int   path_is_absolute = 0;
365         int   len;
366         int   i;
367
368         /*
369          * Sanity checks first
370          */
371         if (file_orig == NULL)
372                 return (-1);
373
374         if ((len = strlen (file_orig)) < 1)
375                 return (-1);
376         else if (len >= 512)
377                 return (-1);
378
379         /*
380          * If `file_orig' ends in a slash the last component is a directory,
381          * otherwise it's a file. Act accordingly..
382          */
383         if (file_orig[len - 1] == '/')
384                 last_is_file = 0;
385         if (file_orig[0] == '/')
386                 path_is_absolute = 1;
387
388         /*
389          * Create a copy for `strtok_r' to destroy
390          */
391         strncpy (file_copy, file_orig, 512);
392         file_copy[511] = '\0';
393
394         /*
395          * Break into components. This will eat up several slashes in a row and
396          * remove leading and trailing slashes..
397          */
398         ptr = file_copy;
399         saveptr = NULL;
400         fields_num = 0;
401         while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
402         {
403                 ptr = NULL;
404                 fields_num++;
405
406                 if (fields_num >= 16)
407                         break;
408         }
409
410         /*
411          * For each component, do..
412          */
413         for (i = 0; i < (fields_num - last_is_file); i++)
414         {
415                 /*
416                  * Do not create directories that start with a dot. This
417                  * prevents `../../' attacks and other likely malicious
418                  * behavior.
419                  */
420                 if (fields[i][0] == '.')
421                 {
422                         ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
423                         return (-2);
424                 }
425
426                 /*
427                  * Join the components together again
428                  */
429                 dir[0] = '/';
430                 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
431                                         fields, i + 1, "/") < 0)
432                 {
433                         ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
434                         return (-1);
435                 }
436
437                 if (stat (dir, &statbuf) == -1)
438                 {
439                         if (errno == ENOENT)
440                         {
441                                 if (mkdir (dir, 0755) == -1)
442                                 {
443                                         char errbuf[1024];
444                                         ERROR ("check_create_dir: mkdir (%s): %s", dir,
445                                                         sstrerror (errno,
446                                                                 errbuf, sizeof (errbuf)));
447                                         return (-1);
448                                 }
449                         }
450                         else
451                         {
452                                 char errbuf[1024];
453                                 ERROR ("stat (%s): %s", dir,
454                                                 sstrerror (errno, errbuf,
455                                                         sizeof (errbuf)));
456                                 return (-1);
457                         }
458                 }
459                 else if (!S_ISDIR (statbuf.st_mode))
460                 {
461                         ERROR ("stat (%s): Not a directory!", dir);
462                         return (-1);
463                 }
464         }
465
466         return (0);
467 } /* check_create_dir */
468
469 #ifdef HAVE_LIBKSTAT
470 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
471 {
472         char ident[128];
473         
474         if (kc == NULL)
475                 return (-1);
476
477         snprintf (ident, 128, "%s,%i,%s", module, instance, name);
478         ident[127] = '\0';
479
480         if (*ksp_ptr == NULL)
481         {
482                 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
483                 {
484                         ERROR ("Cound not find kstat %s", ident);
485                         return (-1);
486                 }
487
488                 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
489                 {
490                         WARNING ("kstat %s has wrong type", ident);
491                         *ksp_ptr = NULL;
492                         return (-1);
493                 }
494         }
495
496 #ifdef assert
497         assert (*ksp_ptr != NULL);
498         assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
499 #endif
500
501         if (kstat_read (kc, *ksp_ptr, NULL) == -1)
502         {
503                 WARNING ("kstat %s could not be read", ident);
504                 return (-1);
505         }
506
507         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
508         {
509                 WARNING ("kstat %s has wrong type", ident);
510                 return (-1);
511         }
512
513         return (0);
514 }
515
516 long long get_kstat_value (kstat_t *ksp, char *name)
517 {
518         kstat_named_t *kn;
519         long long retval = -1LL;
520
521 #ifdef assert
522         assert (ksp != NULL);
523         assert (ksp->ks_type == KSTAT_TYPE_NAMED);
524 #else
525         if (ksp == NULL)
526         {
527                 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
528                 return (-1LL);
529         }
530         else if (ksp->ks_type != KSTAT_TYPE_NAMED)
531         {
532                 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
533                 return (-1LL);
534         }
535 #endif
536
537         if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
538                 return (retval);
539
540         if (kn->data_type == KSTAT_DATA_INT32)
541                 retval = (long long) kn->value.i32;
542         else if (kn->data_type == KSTAT_DATA_UINT32)
543                 retval = (long long) kn->value.ui32;
544         else if (kn->data_type == KSTAT_DATA_INT64)
545                 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
546         else if (kn->data_type == KSTAT_DATA_UINT64)
547                 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
548         else
549                 WARNING ("get_kstat_value: Not a numeric value: %s", name);
550                  
551         return (retval);
552 }
553 #endif /* HAVE_LIBKSTAT */
554
555 unsigned long long ntohll (unsigned long long n)
556 {
557 #if __BYTE_ORDER == __BIG_ENDIAN
558         return (n);
559 #else
560         return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
561 #endif
562 } /* unsigned long long ntohll */
563
564 unsigned long long htonll (unsigned long long n)
565 {
566 #if __BYTE_ORDER == __BIG_ENDIAN
567         return (n);
568 #else
569         return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
570 #endif
571 } /* unsigned long long htonll */
572
573 int format_name (char *ret, int ret_len,
574                 const char *hostname,
575                 const char *plugin, const char *plugin_instance,
576                 const char *type, const char *type_instance)
577 {
578         int  status;
579
580         assert (plugin != NULL);
581         assert (type != NULL);
582
583         if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
584         {
585                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
586                         status = snprintf (ret, ret_len, "%s/%s/%s",
587                                         hostname, plugin, type);
588                 else
589                         status = snprintf (ret, ret_len, "%s/%s/%s-%s",
590                                         hostname, plugin, type,
591                                         type_instance);
592         }
593         else
594         {
595                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
596                         status = snprintf (ret, ret_len, "%s/%s-%s/%s",
597                                         hostname, plugin, plugin_instance,
598                                         type);
599                 else
600                         status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
601                                         hostname, plugin, plugin_instance,
602                                         type, type_instance);
603         }
604
605         if ((status < 1) || (status >= ret_len))
606                 return (-1);
607         return (0);
608 } /* int format_name */
609
610 int parse_identifier (char *str, char **ret_host,
611                 char **ret_plugin, char **ret_plugin_instance,
612                 char **ret_type, char **ret_type_instance)
613 {
614         char *hostname = NULL;
615         char *plugin = NULL;
616         char *plugin_instance = NULL;
617         char *type = NULL;
618         char *type_instance = NULL;
619
620         hostname = str;
621         if (hostname == NULL)
622                 return (-1);
623
624         plugin = strchr (hostname, '/');
625         if (plugin == NULL)
626                 return (-1);
627         *plugin = '\0'; plugin++;
628
629         type = strchr (plugin, '/');
630         if (type == NULL)
631                 return (-1);
632         *type = '\0'; type++;
633
634         plugin_instance = strchr (plugin, '-');
635         if (plugin_instance != NULL)
636         {
637                 *plugin_instance = '\0';
638                 plugin_instance++;
639         }
640
641         type_instance = strchr (type, '-');
642         if (type_instance != NULL)
643         {
644                 *type_instance = '\0';
645                 type_instance++;
646         }
647
648         *ret_host = hostname;
649         *ret_plugin = plugin;
650         *ret_plugin_instance = plugin_instance;
651         *ret_type = type;
652         *ret_type_instance = type_instance;
653         return (0);
654 } /* int parse_identifier */
655
656 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
657 {
658         int i;
659         char *dummy;
660         char *ptr;
661         char *saveptr;
662
663         i = -1;
664         dummy = buffer;
665         saveptr = NULL;
666         while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
667         {
668                 dummy = NULL;
669
670                 if (i >= vl->values_len)
671                         break;
672
673                 if (i == -1)
674                 {
675                         if (strcmp ("N", ptr) == 0)
676                                 vl->time = time (NULL);
677                         else
678                                 vl->time = (time_t) atoi (ptr);
679                 }
680                 else
681                 {
682                         if (strcmp ("U", ptr) == 0)
683                                 vl->values[i].gauge = NAN;
684                         else if (ds->ds[i].type == DS_TYPE_COUNTER)
685                                 vl->values[i].counter = atoll (ptr);
686                         else if (ds->ds[i].type == DS_TYPE_GAUGE)
687                                 vl->values[i].gauge = atof (ptr);
688                 }
689
690                 i++;
691         } /* while (strtok_r) */
692
693         if ((ptr != NULL) || (i != vl->values_len))
694                 return (-1);
695         return (0);
696 } /* int parse_values */
697
698 #if !HAVE_GETPWNAM_R
699 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
700                 size_t buflen, struct passwd **pwbufp)
701 {
702         int status = 0;
703         struct passwd *pw;
704
705         memset (pwbuf, '\0', sizeof (struct passwd));
706
707         pthread_mutex_lock (&getpwnam_r_lock);
708
709         do
710         {
711                 pw = getpwnam (name);
712                 if (pw == NULL)
713                 {
714                         status = (errno != 0) ? errno : ENOENT;
715                         break;
716                 }
717
718 #define GETPWNAM_COPY_MEMBER(member) \
719                 if (pw->member != NULL) \
720                 { \
721                         int len = strlen (pw->member); \
722                         if (len >= buflen) \
723                         { \
724                                 status = ENOMEM; \
725                                 break; \
726                         } \
727                         sstrncpy (buf, pw->member, buflen); \
728                         pwbuf->member = buf; \
729                         buf    += (len + 1); \
730                         buflen -= (len + 1); \
731                 }
732                 GETPWNAM_COPY_MEMBER(pw_name);
733                 GETPWNAM_COPY_MEMBER(pw_passwd);
734                 GETPWNAM_COPY_MEMBER(pw_gecos);
735                 GETPWNAM_COPY_MEMBER(pw_dir);
736                 GETPWNAM_COPY_MEMBER(pw_shell);
737
738                 pwbuf->pw_uid = pw->pw_uid;
739                 pwbuf->pw_gid = pw->pw_gid;
740
741                 if (pwbufp != NULL)
742                         *pwbufp = pwbuf;
743         } while (0);
744
745         pthread_mutex_unlock (&getpwnam_r_lock);
746
747         return (status);
748 } /* int getpwnam_r */
749 #endif /* !HAVE_GETPWNAM_R */
750
751 int notification_init (notification_t *n, int severity, const char *message,
752                 const char *host,
753                 const char *plugin, const char *plugin_instance,
754                 const char *type, const char *type_instance)
755 {
756         memset (n, '\0', sizeof (notification_t));
757
758         n->severity = severity;
759
760         if (message != NULL)
761                 strncpy (n->message, message, sizeof (n->message));
762         if (host != NULL)
763                 strncpy (n->host, host, sizeof (n->host));
764         if (plugin != NULL)
765                 strncpy (n->plugin, plugin, sizeof (n->plugin));
766         if (plugin_instance != NULL)
767                 strncpy (n->plugin_instance, plugin_instance,
768                                 sizeof (n->plugin_instance));
769         if (type != NULL)
770                 strncpy (n->type, type, sizeof (n->type));
771         if (type_instance != NULL)
772                 strncpy (n->type_instance, type_instance,
773                                 sizeof (n->type_instance));
774
775         n->message[sizeof (n->message) - 1] = '\0';
776         n->host[sizeof (n->host) - 1] = '\0';
777         n->plugin[sizeof (n->plugin) - 1] = '\0';
778         n->plugin_instance[sizeof (n->plugin_instance) - 1] = '\0';
779         n->type[sizeof (n->type) - 1] = '\0';
780         n->type_instance[sizeof (n->type_instance) - 1] = '\0';
781
782         return (0);
783 } /* int notification_init */