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