{GPL, other}: Relicense to MIT license.
[collectd.git] / src / common.h
1 /**
2  * collectd - src/common.h
3  * Copyright (C) 2005-2014  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Niki W. Waibel <niki.waibel@gmx.net>
26 **/
27
28 #ifndef COMMON_H
29 #define COMMON_H
30
31 #include "collectd.h"
32 #include "plugin.h"
33
34 #if HAVE_PWD_H
35 # include <pwd.h>
36 #endif
37
38 #define sfree(ptr) \
39         do { \
40                 if((ptr) != NULL) { \
41                         free(ptr); \
42                 } \
43                 (ptr) = NULL; \
44         } while (0)
45
46 #define STATIC_ARRAY_SIZE(a) (sizeof (a) / sizeof (*(a)))
47
48 #define IS_TRUE(s) ((strcasecmp ("true", (s)) == 0) \
49                 || (strcasecmp ("yes", (s)) == 0) \
50                 || (strcasecmp ("on", (s)) == 0))
51 #define IS_FALSE(s) ((strcasecmp ("false", (s)) == 0) \
52                 || (strcasecmp ("no", (s)) == 0) \
53                 || (strcasecmp ("off", (s)) == 0))
54
55 struct rate_to_value_state_s
56 {
57   value_t last_value;
58   cdtime_t last_time;
59   gauge_t residual;
60 };
61 typedef struct rate_to_value_state_s rate_to_value_state_t;
62
63 struct value_to_rate_state_s
64 {
65   value_t last_value;
66   cdtime_t last_time;
67 };
68 typedef struct value_to_rate_state_s value_to_rate_state_t;
69
70 char *sstrncpy (char *dest, const char *src, size_t n);
71
72 __attribute__ ((format(printf,3,4)))
73 int ssnprintf (char *dest, size_t n, const char *format, ...);
74
75 __attribute__ ((format(printf,1,2)))
76 char *ssnprintf_alloc (char const *format, ...);
77
78 char *sstrdup(const char *s);
79 void *smalloc(size_t size);
80 char *sstrerror (int errnum, char *buf, size_t buflen);
81
82 /*
83  * NAME
84  *   sread
85  *
86  * DESCRIPTION
87  *   Reads exactly `n' bytes or fails. Syntax and other behavior is analogous
88  *   to `read(2)'. If EOF is received the file descriptor is closed and an
89  *   error is returned.
90  *
91  * PARAMETERS
92  *   `fd'          File descriptor to write to.
93  *   `buf'         Buffer that is to be written.
94  *   `count'       Number of bytes in the buffer.
95  *
96  * RETURN VALUE
97  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
98  *   case.
99  */
100 ssize_t sread (int fd, void *buf, size_t count);
101
102 /*
103  * NAME
104  *   swrite
105  *
106  * DESCRIPTION
107  *   Writes exactly `n' bytes or fails. Syntax and other behavior is analogous
108  *   to `write(2)'.
109  *
110  * PARAMETERS
111  *   `fd'          File descriptor to write to.
112  *   `buf'         Buffer that is to be written.
113  *   `count'       Number of bytes in the buffer.
114  *
115  * RETURN VALUE
116  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
117  *   case.
118  */
119 ssize_t swrite (int fd, const void *buf, size_t count);
120
121 /*
122  * NAME
123  *   strsplit
124  *
125  * DESCRIPTION
126  *   Splits a string into parts and stores pointers to the parts in `fields'.
127  *   The characters split at are: " ", "\t", "\r", and "\n".
128  *
129  * PARAMETERS
130  *   `string'      String to split. This string will be modified. `fields' will
131  *                 contain pointers to parts of this string, so free'ing it
132  *                 will destroy `fields' as well.
133  *   `fields'      Array of strings where pointers to the parts will be stored.
134  *   `size'        Number of elements in the array. No more than `size'
135  *                 pointers will be stored in `fields'.
136  *
137  * RETURN VALUE
138  *    Returns the number of parts stored in `fields'.
139  */
140 int strsplit (char *string, char **fields, size_t size);
141
142 /*
143  * NAME
144  *   strjoin
145  *
146  * DESCRIPTION
147  *   Joins together several parts of a string using `sep' as a separator. This
148  *   is equivalent to the Perl built-in `join'.
149  *
150  * PARAMETERS
151  *   `dst'         Buffer where the result is stored.
152  *   `dst_len'     Length of the destination buffer. No more than this many
153  *                 bytes will be written to the memory pointed to by `dst',
154  *                 including the trailing null-byte.
155  *   `fields'      Array of strings to be joined.
156  *   `fields_num'  Number of elements in the `fields' array.
157  *   `sep'         String to be inserted between any two elements of `fields'.
158  *                 This string is neither prepended nor appended to the result.
159  *                 Instead of passing "" (empty string) one can pass NULL.
160  *
161  * RETURN VALUE
162  *   Returns the number of characters in `dst', NOT including the trailing
163  *   null-byte. If an error occurred (empty array or `dst' too small) a value
164  *   smaller than zero will be returned.
165  */
166 int strjoin (char *dst, size_t dst_len, char **fields, size_t fields_num, const char *sep);
167
168 /*
169  * NAME
170  *   escape_slashes
171  *
172  * DESCRIPTION
173  *   Removes slashes ("/") from "buffer". If buffer contains a single slash,
174  *   the result will be "root". Leading slashes are removed. All other slashes
175  *   are replaced with underscores ("_").
176  *   This function is used by plugin_dispatch_values() to escape all parts of
177  *   the identifier.
178  *
179  * PARAMETERS
180  *   `buffer'         String to be escaped.
181  *   `buffer_size'    Size of the buffer. No more then this many bytes will be
182  *                    written to `buffer', including the trailing null-byte.
183  *
184  * RETURN VALUE
185  *   Returns zero upon success and a value smaller than zero upon failure.
186  */
187 int escape_slashes (char *buffer, size_t buffer_size);
188
189 /*
190  * NAME
191  *   replace_special
192  *
193  * DESCRIPTION
194  *   Replaces any special characters (anything that's not alpha-numeric or a
195  *   dash) with an underscore.
196  *
197  *   E.g. "foo$bar&" would become "foo_bar_".
198  *
199  * PARAMETERS
200  *   `buffer'      String to be handled.
201  *   `buffer_size' Length of the string. The function returns after
202  *                 encountering a null-byte or reading this many bytes.
203  */
204 void replace_special (char *buffer, size_t buffer_size);
205
206 int strsubstitute (char *str, char c_from, char c_to);
207
208 /*
209  * NAME
210  *   strunescape
211  *
212  * DESCRIPTION
213  *   Replaces any escaped characters in a string with the appropriate special
214  *   characters. The following escaped characters are recognized:
215  *
216  *     \t -> <tab>
217  *     \n -> <newline>
218  *     \r -> <carriage return>
219  *
220  *   For all other escacped characters only the backslash will be removed.
221  *
222  * PARAMETERS
223  *   `buf'         String to be unescaped.
224  *   `buf_len'     Length of the string, including the terminating null-byte.
225  *
226  * RETURN VALUE
227  *   Returns zero upon success, a value less than zero else.
228  */
229 int strunescape (char *buf, size_t buf_len);
230
231 /**
232  * Removed trailing newline characters (CR and LF) from buffer, which must be
233  * null terminated. Returns the length of the resulting string.
234  */
235 __attribute__((nonnull (1)))
236 size_t strstripnewline (char *buffer);
237
238 /*
239  * NAME
240  *   timeval_cmp
241  *
242  * DESCRIPTION
243  *   Compare the two time values `tv0' and `tv1' and store the absolut value
244  *   of the difference in the time value pointed to by `delta' if it does not
245  *   equal NULL.
246  *
247  * RETURN VALUE
248  *   Returns an integer less than, equal to, or greater than zero if `tv0' is
249  *   less than, equal to, or greater than `tv1' respectively.
250  */
251 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta);
252
253 /* make sure tv_usec stores less than a second */
254 #define NORMALIZE_TIMEVAL(tv) \
255         do { \
256                 (tv).tv_sec += (tv).tv_usec / 1000000; \
257                 (tv).tv_usec = (tv).tv_usec % 1000000; \
258         } while (0)
259
260 /* make sure tv_sec stores less than a second */
261 #define NORMALIZE_TIMESPEC(tv) \
262         do { \
263                 (tv).tv_sec += (tv).tv_nsec / 1000000000; \
264                 (tv).tv_nsec = (tv).tv_nsec % 1000000000; \
265         } while (0)
266
267 int check_create_dir (const char *file_orig);
268
269 #ifdef HAVE_LIBKSTAT
270 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name);
271 long long get_kstat_value (kstat_t *ksp, char *name);
272 #endif
273
274 #ifndef HAVE_HTONLL
275 unsigned long long ntohll (unsigned long long n);
276 unsigned long long htonll (unsigned long long n);
277 #endif
278
279 #if FP_LAYOUT_NEED_NOTHING
280 # define ntohd(d) (d)
281 # define htond(d) (d)
282 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
283 double ntohd (double d);
284 double htond (double d);
285 #else
286 # error "Don't know how to convert between host and network representation of doubles."
287 #endif
288
289 int format_name (char *ret, int ret_len,
290                 const char *hostname,
291                 const char *plugin, const char *plugin_instance,
292                 const char *type, const char *type_instance);
293 #define FORMAT_VL(ret, ret_len, vl) \
294         format_name (ret, ret_len, (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
295                         (vl)->type, (vl)->type_instance)
296 int format_values (char *ret, size_t ret_len,
297                 const data_set_t *ds, const value_list_t *vl,
298                 _Bool store_rates);
299
300 int parse_identifier (char *str, char **ret_host,
301                 char **ret_plugin, char **ret_plugin_instance,
302                 char **ret_type, char **ret_type_instance);
303 int parse_identifier_vl (const char *str, value_list_t *vl);
304 int parse_value (const char *value, value_t *ret_value, int ds_type);
305 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds);
306
307 #if !HAVE_GETPWNAM_R
308 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
309                 size_t buflen, struct passwd **pwbufp);
310 #endif
311
312 int notification_init (notification_t *n, int severity, const char *message,
313                 const char *host,
314                 const char *plugin, const char *plugin_instance,
315                 const char *type, const char *type_instance);
316 #define NOTIFICATION_INIT_VL(n, vl) \
317         notification_init (n, NOTIF_FAILURE, NULL, \
318                         (vl)->host, (vl)->plugin, (vl)->plugin_instance, \
319                         (vl)->type, (vl)->type_instance)
320
321 typedef int (*dirwalk_callback_f)(const char *dirname, const char *filename,
322                 void *user_data);
323 int walk_directory (const char *dir, dirwalk_callback_f callback,
324                 void *user_data, int hidden);
325 /* Returns the number of bytes read or negative on error. */
326 ssize_t read_file_contents (char const *filename, char *buf, size_t bufsize);
327
328 counter_t counter_diff (counter_t old_value, counter_t new_value);
329
330 /* Convert a rate back to a value_t. When converting to a derive_t, counter_t
331  * or absoltue_t, take fractional residuals into account. This is important
332  * when scaling counters, for example.
333  * Returns zero on success. Returns EAGAIN when called for the first time; in
334  * this case the value_t is invalid and the next call should succeed. Other
335  * return values indicate an error. */
336 int rate_to_value (value_t *ret_value, gauge_t rate,
337                 rate_to_value_state_t *state, int ds_type, cdtime_t t);
338
339 int value_to_rate (value_t *ret_rate, derive_t value,
340                 value_to_rate_state_t *state, int ds_type, cdtime_t t);
341
342 /* Converts a service name (a string) to a port number
343  * (in the range [1-65535]). Returns less than zero on error. */
344 int service_name_to_port_number (const char *service_name);
345
346 /** Parse a string to a derive_t value. Returns zero on success or non-zero on
347  * failure. If failure is returned, ret_value is not touched. */
348 int strtoderive (const char *string, derive_t *ret_value);
349
350 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str);
351 void strarray_free (char **array, size_t array_len);
352
353 #endif /* COMMON_H */