2 * collectd - src/common.c
3 * Copyright (C) 2005,2006 Florian octo Forster
5 * This program is free software; you can redistribute it and/
6 * or modify it under the terms of the GNU General Public Li-
7 * cence as published by the Free Software Foundation; either
8 * version 2 of the Licence, or any later version.
10 * This program is distributed in the hope that it will be use-
11 * ful, but WITHOUT ANY WARRANTY; without even the implied war-
12 * ranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public Licence for more details.
15 * You should have received a copy of the GNU General Public
16 * Licence along with this program; if not, write to the Free
17 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
21 * Florian octo Forster <octo at verplant.org>
22 * Niki W. Waibel <niki.waibel@gmx.net>
26 #include "utils_debug.h"
32 /* for ntohl and htonl */
34 # include <arpa/inet.h>
37 extern int operating_mode;
40 extern kstat_ctl_t *kc;
43 void sstrncpy (char *d, const char *s, int len)
49 char *sstrdup (const char *s)
56 if((r = strdup (s)) == NULL)
58 DBG ("Not enough memory.");
65 void *smalloc (size_t size)
69 if ((r = malloc (size)) == NULL)
71 DBG("Not enough memory.");
79 void sfree (void **ptr)
91 ssize_t sread (int fd, void *buf, size_t count)
102 status = read (fd, (void *) ptr, nleft);
104 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
112 DBG ("Received EOF from fd %i. "
113 "Closing fd and returning error.",
119 assert (nleft >= status);
121 nleft = nleft - status;
129 ssize_t swrite (int fd, const void *buf, size_t count)
135 ptr = (const char *) buf;
140 status = write (fd, (const void *) ptr, nleft);
142 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
148 nleft = nleft - status;
155 int strsplit (char *string, char **fields, size_t size)
162 while ((fields[i] = strtok (ptr, " \t")) != NULL)
174 int strjoin (char *dst, size_t dst_len,
175 char **fields, size_t fields_num,
182 memset (dst, '\0', dst_len);
189 sep_len = strlen (sep);
191 for (i = 0; i < fields_num; i++)
193 if ((i > 0) && (sep_len > 0))
195 if (dst_len <= sep_len)
198 strncat (dst, sep, dst_len);
202 field_len = strlen (fields[i]);
204 if (dst_len <= field_len)
207 strncat (dst, fields[i], dst_len);
208 dst_len -= field_len;
211 return (strlen (dst));
214 int strsubstitute (char *str, char c_from, char c_to)
235 int escape_slashes (char *buf, int buf_len)
239 if (strcmp (buf, "/") == 0)
244 strncpy (buf, "root", buf_len);
248 /* Move one to the left */
249 memmove (buf, buf + 1, buf_len - 1);
251 for (i = 0; i < buf_len - 1; i++)
255 else if (buf[i] == '/')
263 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
265 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
268 if ((tv0->tv_sec < tv1->tv_sec)
269 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
272 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
273 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
275 if (ret->tv_nsec < 0)
277 assert (ret->tv_sec > 0);
279 ret->tv_nsec += 1000000000;
286 int check_create_dir (const char *file_orig)
296 int last_is_file = 1;
301 * Sanity checks first
303 if (file_orig == NULL)
306 if ((len = strlen (file_orig)) < 1)
312 * If `file_orig' ends in a slash the last component is a directory,
313 * otherwise it's a file. Act accordingly..
315 if (file_orig[len - 1] == '/')
319 * Create a copy for `strtok' to destroy
321 strncpy (file_copy, file_orig, 512);
322 file_copy[511] = '\0';
325 * Break into components. This will eat up several slashes in a row and
326 * remove leading and trailing slashes..
330 while ((fields[fields_num] = strtok (ptr, "/")) != NULL)
335 if (fields_num >= 16)
340 * For each component, do..
342 for (i = 0; i < (fields_num - last_is_file); i++)
345 * Do not create directories that start with a dot. This
346 * prevents `../../' attacks and other likely malicious
349 if (fields[i][0] == '.')
351 syslog (LOG_ERR, "Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
356 * Join the components together again
358 if (strjoin (dir, dir_len, fields, i + 1, "/") < 0)
360 syslog (LOG_ERR, "strjoin failed: `%s', component #%i", file_orig, i);
364 if (stat (dir, &statbuf) == -1)
368 if (mkdir (dir, 0755) == -1)
370 syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
376 syslog (LOG_ERR, "stat (%s): %s", dir, strerror (errno));
380 else if (!S_ISDIR (statbuf.st_mode))
382 syslog (LOG_ERR, "stat (%s): Not a directory!", dir);
390 static int log_create_file (char *filename, char **ds_def, int ds_num)
395 if (check_create_dir (filename))
398 log = fopen (filename, "w");
401 syslog (LOG_WARNING, "Failed to create %s: %s", filename,
406 fprintf (log, "epoch");
407 for (i = 0; i < ds_num; i++)
412 name = strchr (ds_def[i], ':');
415 syslog (LOG_WARNING, "Invalid DS definition '%s' for %s",
416 ds_def[i], filename);
423 tmp = strchr (name, ':');
426 syslog (LOG_WARNING, "Invalid DS definition '%s' for %s",
427 ds_def[i], filename);
433 /* The `%.*s' is needed because there is no null-byte behind
435 fprintf(log, ",%.*s", (int) (tmp - name), name);
443 int log_update_file (char *host, char *file, char *values,
444 char **ds_def, int ds_num)
449 char full_file[1024];
451 /* Cook the values a bit: Substitute colons with commas */
452 strsubstitute (values, ':', ',');
454 /* host == NULL => local mode */
457 if (snprintf (full_file, 1024, "%s/%s", host, file) >= 1024)
462 if (snprintf (full_file, 1024, "%s", file) >= 1024)
466 strncpy (full_file, file, 1024);
468 tmp = full_file + strlen (full_file) - 4;
469 assert ((tmp != NULL) && (tmp > full_file));
471 /* Change the filename for logfiles. */
472 if (strncmp (tmp, ".rrd", 4) == 0)
477 /* TODO: Find a way to minimize the calls to `localtime', since
478 * they are pretty expensive.. */
480 tm = localtime (&now);
482 strftime (tmp, 1024 - (tmp - full_file), "-%Y-%m-%d", tm);
484 /* `localtime(3)' returns a pointer to static data,
485 * therefore the pointer may not be free'd. */
488 DBG ("The filename ends with `%s' which is unexpected.", tmp);
490 if (stat (full_file, &statbuf) == -1)
494 if (log_create_file (full_file, ds_def, ds_num))
499 syslog (LOG_ERR, "stat %s: %s", full_file, strerror (errno));
503 else if (!S_ISREG (statbuf.st_mode))
505 syslog (LOG_ERR, "stat %s: Not a regular file!", full_file);
510 fp = fopen (full_file, "a");
513 syslog (LOG_WARNING, "Failed to append to %s: %s", full_file,
517 fprintf(fp, "%s\n", values);
521 } /* int log_update_file */
525 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
532 snprintf (ident, 128, "%s,%i,%s", module, instance, name);
535 if (*ksp_ptr == NULL)
537 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
539 syslog (LOG_ERR, "Cound not find kstat %s", ident);
543 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
545 syslog (LOG_WARNING, "kstat %s has wrong type", ident);
552 assert (*ksp_ptr != NULL);
553 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
556 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
558 syslog (LOG_WARNING, "kstat %s could not be read", ident);
562 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
564 syslog (LOG_WARNING, "kstat %s has wrong type", ident);
571 long long get_kstat_value (kstat_t *ksp, char *name)
574 long long retval = -1LL;
577 assert (ksp != NULL);
578 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
582 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
585 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
587 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
592 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
595 if (kn->data_type == KSTAT_DATA_INT32)
596 retval = (long long) kn->value.i32;
597 else if (kn->data_type == KSTAT_DATA_UINT32)
598 retval = (long long) kn->value.ui32;
599 else if (kn->data_type == KSTAT_DATA_INT64)
600 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
601 else if (kn->data_type == KSTAT_DATA_UINT64)
602 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
604 syslog (LOG_WARNING, "get_kstat_value: Not a numeric value: %s", name);
608 #endif /* HAVE_LIBKSTAT */
610 unsigned long long ntohll (unsigned long long n)
612 #if __BYTE_ORDER == __BIG_ENDIAN
615 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
619 unsigned long long htonll (unsigned long long n)
621 #if __BYTE_ORDER == __BIG_ENDIAN
624 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);