365b74f30091599c8d4d703da184c899cd20e26a
[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 #include "common.h"
24 #include "utils_debug.h"
25
26 #ifdef HAVE_MATH_H
27 #  include <math.h>
28 #endif
29
30 /* for ntohl and htonl */
31 #if HAVE_ARPA_INET_H
32 # include <arpa/inet.h>
33 #endif
34
35 #ifdef HAVE_LIBKSTAT
36 extern kstat_ctl_t *kc;
37 #endif
38
39 void sstrncpy (char *d, const char *s, int len)
40 {
41         strncpy (d, s, len);
42         d[len - 1] = '\0';
43 }
44
45 char *sstrdup (const char *s)
46 {
47         char *r;
48
49         if (s == NULL)
50                 return (NULL);
51
52         if((r = strdup (s)) == NULL)
53         {
54                 DBG ("Not enough memory.");
55                 exit(3);
56         }
57
58         return (r);
59 }
60
61 void *smalloc (size_t size)
62 {
63         void *r;
64
65         if ((r = malloc (size)) == NULL)
66         {
67                 DBG("Not enough memory.");
68                 exit(3);
69         }
70
71         return r;
72 }
73
74 #if 0
75 void sfree (void **ptr)
76 {
77         if (ptr == NULL)
78                 return;
79
80         if (*ptr != NULL)
81                 free (*ptr);
82
83         *ptr = NULL;
84 }
85 #endif
86
87 ssize_t sread (int fd, void *buf, size_t count)
88 {
89         char    *ptr;
90         size_t   nleft;
91         ssize_t  status;
92
93         ptr   = (char *) buf;
94         nleft = count;
95
96         while (nleft > 0)
97         {
98                 status = read (fd, (void *) ptr, nleft);
99
100                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
101                         continue;
102
103                 if (status < 0)
104                         return (status);
105
106                 if (status == 0)
107                 {
108                         DBG ("Received EOF from fd %i. "
109                                         "Closing fd and returning error.",
110                                         fd);
111                         close (fd);
112                         return (-1);
113                 }
114
115                 assert (nleft >= status);
116
117                 nleft = nleft - status;
118                 ptr   = ptr   + status;
119         }
120
121         return (0);
122 }
123
124
125 ssize_t swrite (int fd, const void *buf, size_t count)
126 {
127         const char *ptr;
128         size_t      nleft;
129         ssize_t     status;
130
131         ptr   = (const char *) buf;
132         nleft = count;
133
134         while (nleft > 0)
135         {
136                 status = write (fd, (const void *) ptr, nleft);
137
138                 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
139                         continue;
140
141                 if (status < 0)
142                         return (status);
143
144                 nleft = nleft - status;
145                 ptr   = ptr   + status;
146         }
147
148         return (0);
149 }
150
151 int strsplit (char *string, char **fields, size_t size)
152 {
153         size_t i;
154         char *ptr;
155
156         i = 0;
157         ptr = string;
158         while ((fields[i] = strtok (ptr, " \t")) != NULL)
159         {
160                 ptr = NULL;
161                 i++;
162
163                 if (i >= size)
164                         break;
165         }
166
167         return (i);
168 }
169
170 int strjoin (char *dst, size_t dst_len,
171                 char **fields, size_t fields_num,
172                 const char *sep)
173 {
174         int field_len;
175         int sep_len;
176         int i;
177
178         memset (dst, '\0', dst_len);
179
180         if (fields_num <= 0)
181                 return (-1);
182
183         sep_len = 0;
184         if (sep != NULL)
185                 sep_len = strlen (sep);
186
187         for (i = 0; i < fields_num; i++)
188         {
189                 if ((i > 0) && (sep_len > 0))
190                 {
191                         if (dst_len <= sep_len)
192                                 return (-1);
193
194                         strncat (dst, sep, dst_len);
195                         dst_len -= sep_len;
196                 }
197
198                 field_len = strlen (fields[i]);
199
200                 if (dst_len <= field_len)
201                         return (-1);
202
203                 strncat (dst, fields[i], dst_len);
204                 dst_len -= field_len;
205         }
206
207         return (strlen (dst));
208 }
209
210 int strsubstitute (char *str, char c_from, char c_to)
211 {
212         int ret;
213
214         if (str == NULL)
215                 return (-1);
216
217         ret = 0;
218         while (*str != '\0')
219         {
220                 if (*str == c_from)
221                 {
222                         *str = c_to;
223                         ret++;
224                 }
225                 str++;
226         }
227
228         return (ret);
229 }
230
231 int escape_slashes (char *buf, int buf_len)
232 {
233         int i;
234
235         if (strcmp (buf, "/") == 0)
236         {
237                 if (buf_len < 5)
238                         return (-1);
239
240                 strncpy (buf, "root", buf_len);
241                 return (0);
242         }
243
244         /* Move one to the left */
245         memmove (buf, buf + 1, buf_len - 1);
246
247         for (i = 0; i < buf_len - 1; i++)
248         {
249                 if (buf[i] == '\0')
250                         break;
251                 else if (buf[i] == '/')
252                         buf[i] = '_';
253         }
254         buf[i] = '\0';
255
256         return (0);
257 }
258
259 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
260 {
261         if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
262                 return (-2);
263
264         if ((tv0->tv_sec < tv1->tv_sec)
265                         || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
266                 return (-1);
267
268         ret->tv_sec  = tv0->tv_sec - tv1->tv_sec;
269         ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
270
271         if (ret->tv_nsec < 0)
272         {
273                 assert (ret->tv_sec > 0);
274
275                 ret->tv_nsec += 1000000000;
276                 ret->tv_sec  -= 1;
277         }
278
279         return (0);
280 }
281
282 int check_create_dir (const char *file_orig)
283 {
284         struct stat statbuf;
285
286         char  file_copy[512];
287         char  dir[512];
288         int   dir_len = 512;
289         char *fields[16];
290         int   fields_num;
291         char *ptr;
292         int   last_is_file = 1;
293         int   len;
294         int   i;
295
296         /*
297          * Sanity checks first
298          */
299         if (file_orig == NULL)
300                 return (-1);
301
302         if ((len = strlen (file_orig)) < 1)
303                 return (-1);
304         else if (len >= 512)
305                 return (-1);
306
307         /*
308          * If `file_orig' ends in a slash the last component is a directory,
309          * otherwise it's a file. Act accordingly..
310          */
311         if (file_orig[len - 1] == '/')
312                 last_is_file = 0;
313
314         /*
315          * Create a copy for `strtok' to destroy
316          */
317         strncpy (file_copy, file_orig, 512);
318         file_copy[511] = '\0';
319
320         /*
321          * Break into components. This will eat up several slashes in a row and
322          * remove leading and trailing slashes..
323          */
324         ptr = file_copy;
325         fields_num = 0;
326         while ((fields[fields_num] = strtok (ptr, "/")) != NULL)
327         {
328                 ptr = NULL;
329                 fields_num++;
330
331                 if (fields_num >= 16)
332                         break;
333         }
334
335         /*
336          * For each component, do..
337          */
338         for (i = 0; i < (fields_num - last_is_file); i++)
339         {
340                 /*
341                  * Do not create directories that start with a dot. This
342                  * prevents `../../' attacks and other likely malicious
343                  * behavior.
344                  */
345                 if (fields[i][0] == '.')
346                 {
347                         syslog (LOG_ERR, "Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
348                         return (-2);
349                 }
350
351                 /*
352                  * Join the components together again
353                  */
354                 if (strjoin (dir, dir_len, fields, i + 1, "/") < 0)
355                 {
356                         syslog (LOG_ERR, "strjoin failed: `%s', component #%i", file_orig, i);
357                         return (-1);
358                 }
359
360                 if (stat (dir, &statbuf) == -1)
361                 {
362                         if (errno == ENOENT)
363                         {
364                                 if (mkdir (dir, 0755) == -1)
365                                 {
366                                         syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
367                                         return (-1);
368                                 }
369                         }
370                         else
371                         {
372                                 syslog (LOG_ERR, "stat (%s): %s", dir, strerror (errno));
373                                 return (-1);
374                         }
375                 }
376                 else if (!S_ISDIR (statbuf.st_mode))
377                 {
378                         syslog (LOG_ERR, "stat (%s): Not a directory!", dir);
379                         return (-1);
380                 }
381         }
382
383         return (0);
384 }
385
386 #ifdef HAVE_LIBKSTAT
387 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
388 {
389         char ident[128];
390         
391         if (kc == NULL)
392                 return (-1);
393
394         snprintf (ident, 128, "%s,%i,%s", module, instance, name);
395         ident[127] = '\0';
396
397         if (*ksp_ptr == NULL)
398         {
399                 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
400                 {
401                         syslog (LOG_ERR, "Cound not find kstat %s", ident);
402                         return (-1);
403                 }
404
405                 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
406                 {
407                         syslog (LOG_WARNING, "kstat %s has wrong type", ident);
408                         *ksp_ptr = NULL;
409                         return (-1);
410                 }
411         }
412
413 #ifdef assert
414         assert (*ksp_ptr != NULL);
415         assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
416 #endif
417
418         if (kstat_read (kc, *ksp_ptr, NULL) == -1)
419         {
420                 syslog (LOG_WARNING, "kstat %s could not be read", ident);
421                 return (-1);
422         }
423
424         if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
425         {
426                 syslog (LOG_WARNING, "kstat %s has wrong type", ident);
427                 return (-1);
428         }
429
430         return (0);
431 }
432
433 long long get_kstat_value (kstat_t *ksp, char *name)
434 {
435         kstat_named_t *kn;
436         long long retval = -1LL;
437
438 #ifdef assert
439         assert (ksp != NULL);
440         assert (ksp->ks_type == KSTAT_TYPE_NAMED);
441 #else
442         if (ksp == NULL)
443         {
444                 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
445                 return (-1LL);
446         }
447         else if (ksp->ks_type != KSTAT_TYPE_NAMED)
448         {
449                 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
450                 return (-1LL);
451         }
452 #endif
453
454         if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
455                 return (retval);
456
457         if (kn->data_type == KSTAT_DATA_INT32)
458                 retval = (long long) kn->value.i32;
459         else if (kn->data_type == KSTAT_DATA_UINT32)
460                 retval = (long long) kn->value.ui32;
461         else if (kn->data_type == KSTAT_DATA_INT64)
462                 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
463         else if (kn->data_type == KSTAT_DATA_UINT64)
464                 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
465         else
466                 syslog (LOG_WARNING, "get_kstat_value: Not a numeric value: %s", name);
467                  
468         return (retval);
469 }
470 #endif /* HAVE_LIBKSTAT */
471
472 unsigned long long ntohll (unsigned long long n)
473 {
474 #if __BYTE_ORDER == __BIG_ENDIAN
475         return (n);
476 #else
477         return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
478 #endif
479 }
480
481 unsigned long long htonll (unsigned long long n)
482 {
483 #if __BYTE_ORDER == __BIG_ENDIAN
484         return (n);
485 #else
486         return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
487 #endif
488 }