Code

7555b7ef99d26150d81193ce7e1d4d1a8e3a4b33
[collectd.git] / src / common.c
1 /**
2  * collectd - src/common.c
3  * Copyright (C) 2005-2007  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 **/
23 #if HAVE_CONFIG_H
24 # include "config.h"
25 #endif
27 #include "common.h"
28 #include "plugin.h"
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
34 #ifdef HAVE_MATH_H
35 # include <math.h>
36 #endif
38 /* for ntohl and htonl */
39 #if HAVE_ARPA_INET_H
40 # include <arpa/inet.h>
41 #endif
43 #ifdef HAVE_LIBKSTAT
44 extern kstat_ctl_t *kc;
45 #endif
47 #if !HAVE_GETPWNAM_R
48 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
49 #endif
51 void sstrncpy (char *d, const char *s, int len)
52 {
53         strncpy (d, s, len);
54         d[len - 1] = '\0';
55 }
57 char *sstrdup (const char *s)
58 {
59         char *r;
61         if (s == NULL)
62                 return (NULL);
64         if((r = strdup (s)) == NULL)
65         {
66                 DEBUG ("Not enough memory.");
67                 exit(3);
68         }
70         return (r);
71 }
73 /* Even though Posix requires "strerror_r" to return an "int",
74  * some systems (e.g. the GNU libc) return a "char *" _and_
75  * ignore the second argument ... -tokkee */
76 char *sstrerror (int errnum, char *buf, size_t buflen)
77 {
78         buf[0] = '\0';
79 #ifdef STRERROR_R_CHAR_P
80         {
81                 char *temp;
82                 temp = strerror_r (errnum, buf, buflen);
83                 if (buf[0] == '\0')
84                 {
85                         strncpy (buf, temp, buflen);
86                         buf[buflen - 1] = '\0';
87                 }
88         }
89 #else
90         strerror_r (errnum, buf, buflen);
91 #endif /* STRERROR_R_CHAR_P */
92         return (buf);
93 } /* char *sstrerror */
95 void *smalloc (size_t size)
96 {
97         void *r;
99         if ((r = malloc (size)) == NULL)
100         {
101                 DEBUG("Not enough memory.");
102                 exit(3);
103         }
105         return r;
108 #if 0
109 void sfree (void **ptr)
111         if (ptr == NULL)
112                 return;
114         if (*ptr != NULL)
115                 free (*ptr);
117         *ptr = NULL;
119 #endif
121 ssize_t sread (int fd, void *buf, size_t count)
123         char    *ptr;
124         size_t   nleft;
125         ssize_t  status;
127         ptr   = (char *) buf;
128         nleft = count;
130         while (nleft > 0)
131         {
132                 status = read (fd, (void *) ptr, nleft);
134                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
135                         continue;
137                 if (status < 0)
138                         return (status);
140                 if (status == 0)
141                 {
142                         DEBUG ("Received EOF from fd %i. "
143                                         "Closing fd and returning error.",
144                                         fd);
145                         close (fd);
146                         return (-1);
147                 }
149                 assert (nleft >= status);
151                 nleft = nleft - status;
152                 ptr   = ptr   + status;
153         }
155         return (0);
159 ssize_t swrite (int fd, const void *buf, size_t count)
161         const char *ptr;
162         size_t      nleft;
163         ssize_t     status;
165         ptr   = (const char *) buf;
166         nleft = count;
168         while (nleft > 0)
169         {
170                 status = write (fd, (const void *) ptr, nleft);
172                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
173                         continue;
175                 if (status < 0)
176                         return (status);
178                 nleft = nleft - status;
179                 ptr   = ptr   + status;
180         }
182         return (0);
185 int strsplit (char *string, char **fields, size_t size)
187         size_t i;
188         char *ptr;
189         char *saveptr;
191         i = 0;
192         ptr = string;
193         saveptr = NULL;
194         while ((fields[i] = strtok_r (ptr, " \t", &saveptr)) != NULL)
195         {
196                 ptr = NULL;
197                 i++;
199                 if (i >= size)
200                         break;
201         }
203         return (i);
206 int strjoin (char *dst, size_t dst_len,
207                 char **fields, size_t fields_num,
208                 const char *sep)
210         int field_len;
211         int sep_len;
212         int i;
214         memset (dst, '\0', dst_len);
216         if (fields_num <= 0)
217                 return (-1);
219         sep_len = 0;
220         if (sep != NULL)
221                 sep_len = strlen (sep);
223         for (i = 0; i < fields_num; i++)
224         {
225                 if ((i > 0) && (sep_len > 0))
226                 {
227                         if (dst_len <= sep_len)
228                                 return (-1);
230                         strncat (dst, sep, dst_len);
231                         dst_len -= sep_len;
232                 }
234                 field_len = strlen (fields[i]);
236                 if (dst_len <= field_len)
237                         return (-1);
239                 strncat (dst, fields[i], dst_len);
240                 dst_len -= field_len;
241         }
243         return (strlen (dst));
246 int strsubstitute (char *str, char c_from, char c_to)
248         int ret;
250         if (str == NULL)
251                 return (-1);
253         ret = 0;
254         while (*str != '\0')
255         {
256                 if (*str == c_from)
257                 {
258                         *str = c_to;
259                         ret++;
260                 }
261                 str++;
262         }
264         return (ret);
265 } /* int strsubstitute */
267 int escape_slashes (char *buf, int buf_len)
269         int i;
271         if (strcmp (buf, "/") == 0)
272         {
273                 if (buf_len < 5)
274                         return (-1);
276                 strncpy (buf, "root", buf_len);
277                 return (0);
278         }
280         if (buf_len <= 1)
281                 return (0);
283         /* Move one to the left */
284         if (buf[0] == '/')
285                 memmove (buf, buf + 1, buf_len - 1);
287         for (i = 0; i < buf_len - 1; i++)
288         {
289                 if (buf[i] == '\0')
290                         break;
291                 else if (buf[i] == '/')
292                         buf[i] = '_';
293         }
294         buf[i] = '\0';
296         return (0);
297 } /* int escape_slashes */
299 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
301         if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
302                 return (-2);
304         if ((tv0->tv_sec < tv1->tv_sec)
305                         || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
306                 return (-1);
308         ret->tv_sec  = tv0->tv_sec - tv1->tv_sec;
309         ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
311         if (ret->tv_nsec < 0)
312         {
313                 assert (ret->tv_sec > 0);
315                 ret->tv_nsec += 1000000000;
316                 ret->tv_sec  -= 1;
317         }
319         return (0);
322 int check_create_dir (const char *file_orig)
324         struct stat statbuf;
326         char  file_copy[512];
327         char  dir[512];
328         int   dir_len = 512;
329         char *fields[16];
330         int   fields_num;
331         char *ptr;
332         char *saveptr;
333         int   last_is_file = 1;
334         int   path_is_absolute = 0;
335         int   len;
336         int   i;
338         /*
339          * Sanity checks first
340          */
341         if (file_orig == NULL)
342                 return (-1);
344         if ((len = strlen (file_orig)) < 1)
345                 return (-1);
346         else if (len >= 512)
347                 return (-1);
349         /*
350          * If `file_orig' ends in a slash the last component is a directory,
351          * otherwise it's a file. Act accordingly..
352          */
353         if (file_orig[len - 1] == '/')
354                 last_is_file = 0;
355         if (file_orig[0] == '/')
356                 path_is_absolute = 1;
358         /*
359          * Create a copy for `strtok_r' to destroy
360          */
361         strncpy (file_copy, file_orig, 512);
362         file_copy[511] = '\0';
364         /*
365          * Break into components. This will eat up several slashes in a row and
366          * remove leading and trailing slashes..
367          */
368         ptr = file_copy;
369         saveptr = NULL;
370         fields_num = 0;
371         while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
372         {
373                 ptr = NULL;
374                 fields_num++;
376                 if (fields_num >= 16)
377                         break;
378         }
380         /*
381          * For each component, do..
382          */
383         for (i = 0; i < (fields_num - last_is_file); i++)
384         {
385                 /*
386                  * Do not create directories that start with a dot. This
387                  * prevents `../../' attacks and other likely malicious
388                  * behavior.
389                  */
390                 if (fields[i][0] == '.')
391                 {
392                         ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
393                         return (-2);
394                 }
396                 /*
397                  * Join the components together again
398                  */
399                 dir[0] = '/';
400                 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
401                                         fields, i + 1, "/") < 0)
402                 {
403                         ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
404                         return (-1);
405                 }
407                 if (stat (dir, &statbuf) == -1)
408                 {
409                         if (errno == ENOENT)
410                         {
411                                 if (mkdir (dir, 0755) == -1)
412                                 {
413                                         char errbuf[1024];
414                                         ERROR ("mkdir (%s): %s", dir,
415                                                         sstrerror (errno,
416                                                                 errbuf, sizeof (errbuf)));
417                                         return (-1);
418                                 }
419                         }
420                         else
421                         {
422                                 char errbuf[1024];
423                                 ERROR ("stat (%s): %s", dir,
424                                                 sstrerror (errno, errbuf,
425                                                         sizeof (errbuf)));
426                                 return (-1);
427                         }
428                 }
429                 else if (!S_ISDIR (statbuf.st_mode))
430                 {
431                         ERROR ("stat (%s): Not a directory!", dir);
432                         return (-1);
433                 }
434         }
436         return (0);
439 #ifdef HAVE_LIBKSTAT
440 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
442         char ident[128];
443         
444         if (kc == NULL)
445                 return (-1);
447         snprintf (ident, 128, "%s,%i,%s", module, instance, name);
448         ident[127] = '\0';
450         if (*ksp_ptr == NULL)
451         {
452                 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
453                 {
454                         ERROR ("Cound not find kstat %s", ident);
455                         return (-1);
456                 }
458                 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
459                 {
460                         WARNING ("kstat %s has wrong type", ident);
461                         *ksp_ptr = NULL;
462                         return (-1);
463                 }
464         }
466 #ifdef assert
467         assert (*ksp_ptr != NULL);
468         assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
469 #endif
471         if (kstat_read (kc, *ksp_ptr, NULL) == -1)
472         {
473                 WARNING ("kstat %s could not be read", ident);
474                 return (-1);
475         }
477         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
478         {
479                 WARNING ("kstat %s has wrong type", ident);
480                 return (-1);
481         }
483         return (0);
486 long long get_kstat_value (kstat_t *ksp, char *name)
488         kstat_named_t *kn;
489         long long retval = -1LL;
491 #ifdef assert
492         assert (ksp != NULL);
493         assert (ksp->ks_type == KSTAT_TYPE_NAMED);
494 #else
495         if (ksp == NULL)
496         {
497                 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
498                 return (-1LL);
499         }
500         else if (ksp->ks_type != KSTAT_TYPE_NAMED)
501         {
502                 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
503                 return (-1LL);
504         }
505 #endif
507         if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
508                 return (retval);
510         if (kn->data_type == KSTAT_DATA_INT32)
511                 retval = (long long) kn->value.i32;
512         else if (kn->data_type == KSTAT_DATA_UINT32)
513                 retval = (long long) kn->value.ui32;
514         else if (kn->data_type == KSTAT_DATA_INT64)
515                 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
516         else if (kn->data_type == KSTAT_DATA_UINT64)
517                 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
518         else
519                 WARNING ("get_kstat_value: Not a numeric value: %s", name);
520                  
521         return (retval);
523 #endif /* HAVE_LIBKSTAT */
525 unsigned long long ntohll (unsigned long long n)
527 #if __BYTE_ORDER == __BIG_ENDIAN
528         return (n);
529 #else
530         return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
531 #endif
532 } /* unsigned long long ntohll */
534 unsigned long long htonll (unsigned long long n)
536 #if __BYTE_ORDER == __BIG_ENDIAN
537         return (n);
538 #else
539         return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
540 #endif
541 } /* unsigned long long htonll */
543 int format_name (char *ret, int ret_len,
544                 const char *hostname,
545                 const char *plugin, const char *plugin_instance,
546                 const char *type, const char *type_instance)
548         int  status;
550         assert (plugin != NULL);
551         assert (type != NULL);
553         if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
554         {
555                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
556                         status = snprintf (ret, ret_len, "%s/%s/%s",
557                                         hostname, plugin, type);
558                 else
559                         status = snprintf (ret, ret_len, "%s/%s/%s-%s",
560                                         hostname, plugin, type,
561                                         type_instance);
562         }
563         else
564         {
565                 if ((type_instance == NULL) || (strlen (type_instance) == 0))
566                         status = snprintf (ret, ret_len, "%s/%s-%s/%s",
567                                         hostname, plugin, plugin_instance,
568                                         type);
569                 else
570                         status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
571                                         hostname, plugin, plugin_instance,
572                                         type, type_instance);
573         }
575         if ((status < 1) || (status >= ret_len))
576                 return (-1);
577         return (0);
578 } /* int format_name */
580 int parse_identifier (char *str, char **ret_host,
581                 char **ret_plugin, char **ret_plugin_instance,
582                 char **ret_type, char **ret_type_instance)
584         char *hostname = NULL;
585         char *plugin = NULL;
586         char *plugin_instance = NULL;
587         char *type = NULL;
588         char *type_instance = NULL;
590         hostname = str;
591         if (hostname == NULL)
592                 return (-1);
594         plugin = strchr (hostname, '/');
595         if (plugin == NULL)
596                 return (-1);
597         *plugin = '\0'; plugin++;
599         type = strchr (plugin, '/');
600         if (type == NULL)
601                 return (-1);
602         *type = '\0'; type++;
604         plugin_instance = strchr (plugin, '-');
605         if (plugin_instance != NULL)
606         {
607                 *plugin_instance = '\0';
608                 plugin_instance++;
609         }
611         type_instance = strchr (type, '-');
612         if (type_instance != NULL)
613         {
614                 *type_instance = '\0';
615                 type_instance++;
616         }
618         *ret_host = hostname;
619         *ret_plugin = plugin;
620         *ret_plugin_instance = plugin_instance;
621         *ret_type = type;
622         *ret_type_instance = type_instance;
623         return (0);
624 } /* int parse_identifier */
626 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
628         int i;
629         char *dummy;
630         char *ptr;
631         char *saveptr;
633         i = -1;
634         dummy = buffer;
635         saveptr = NULL;
636         while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
637         {
638                 dummy = NULL;
640                 if (i >= vl->values_len)
641                         break;
643                 if (i == -1)
644                 {
645                         if (strcmp ("N", ptr) == 0)
646                                 vl->time = time (NULL);
647                         else
648                                 vl->time = (time_t) atoi (ptr);
649                 }
650                 else
651                 {
652                         if (strcmp ("U", ptr) == 0)
653                                 vl->values[i].gauge = NAN;
654                         else if (ds->ds[i].type == DS_TYPE_COUNTER)
655                                 vl->values[i].counter = atoll (ptr);
656                         else if (ds->ds[i].type == DS_TYPE_GAUGE)
657                                 vl->values[i].gauge = atof (ptr);
658                 }
660                 i++;
661         } /* while (strtok_r) */
663         if ((ptr != NULL) || (i != vl->values_len))
664                 return (-1);
665         return (0);
666 } /* int parse_values */
668 #if !HAVE_GETPWNAM_R
669 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
670                 size_t buflen, struct passwd **pwbufp)
672         int status = 0;
673         struct passwd *pw;
675         memset (pwbuf, '\0', sizeof (struct passwd));
677         pthread_mutex_lock (&getpwnam_r_lock);
679         do
680         {
681                 pw = getpwnam (name);
682                 if (pw == NULL)
683                 {
684                         status = (errno != 0) ? errno : ENOENT;
685                         break;
686                 }
688 #define GETPWNAM_COPY_MEMBER(member) \
689                 if (pw->member != NULL) \
690                 { \
691                         int len = strlen (pw->member); \
692                         if (len >= buflen) \
693                         { \
694                                 status = ENOMEM; \
695                                 break; \
696                         } \
697                         sstrncpy (buf, pw->member, buflen); \
698                         pwbuf->member = buf; \
699                         buf    += (len + 1); \
700                         buflen -= (len + 1); \
701                 }
702                 GETPWNAM_COPY_MEMBER(pw_name);
703                 GETPWNAM_COPY_MEMBER(pw_passwd);
704                 GETPWNAM_COPY_MEMBER(pw_gecos);
705                 GETPWNAM_COPY_MEMBER(pw_dir);
706                 GETPWNAM_COPY_MEMBER(pw_shell);
708                 pwbuf->pw_uid = pw->pw_uid;
709                 pwbuf->pw_gid = pw->pw_gid;
711                 if (pwbufp != NULL)
712                         *pwbufp = pwbuf;
713         } while (0);
715         pthread_mutex_unlock (&getpwnam_r_lock);
717         return (status);
718 } /* int getpwnam_r */
719 #endif