Add snprintf wrapper for GCC 8.2/3
[collectd.git] / src / utils / common / 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
33 #include "plugin.h"
34
35 #if HAVE_PWD_H
36 #include <pwd.h>
37 #endif
38
39 #define sfree(ptr)                                                             \
40   do {                                                                         \
41     free(ptr);                                                                 \
42     (ptr) = NULL;                                                              \
43   } while (0)
44
45 #define STATIC_ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
46
47 #define IS_TRUE(s)                                                             \
48   ((strcasecmp("true", (s)) == 0) || (strcasecmp("yes", (s)) == 0) ||          \
49    (strcasecmp("on", (s)) == 0))
50 #define IS_FALSE(s)                                                            \
51   ((strcasecmp("false", (s)) == 0) || (strcasecmp("no", (s)) == 0) ||          \
52    (strcasecmp("off", (s)) == 0))
53
54 struct rate_to_value_state_s {
55   value_t last_value;
56   cdtime_t last_time;
57   gauge_t residual;
58 };
59 typedef struct rate_to_value_state_s rate_to_value_state_t;
60
61 struct value_to_rate_state_s {
62   value_t last_value;
63   cdtime_t last_time;
64 };
65 typedef struct value_to_rate_state_s value_to_rate_state_t;
66
67 char *sstrncpy(char *dest, const char *src, size_t n);
68
69 __attribute__((format(printf, 3, 4))) int ssnprintf(char *str, size_t size,
70                                                     char const *format, ...);
71
72 __attribute__((format(printf, 1, 2))) char *ssnprintf_alloc(char const *format,
73                                                             ...);
74
75 char *sstrdup(const char *s);
76 void *smalloc(size_t size);
77 char *sstrerror(int errnum, char *buf, size_t buflen);
78
79 #ifndef ERRBUF_SIZE
80 #define ERRBUF_SIZE 256
81 #endif
82
83 #define STRERROR(e) sstrerror((e), (char[ERRBUF_SIZE]){0}, ERRBUF_SIZE)
84 #define STRERRNO STRERROR(errno)
85
86 /*
87  * NAME
88  *   sread
89  *
90  * DESCRIPTION
91  *   Reads exactly `n' bytes or fails. Syntax and other behavior is analogous
92  *   to `read(2)'.
93  *
94  * PARAMETERS
95  *   `fd'          File descriptor to write to.
96  *   `buf'         Buffer that is to be written.
97  *   `count'       Number of bytes in the buffer.
98  *
99  * RETURN VALUE
100  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
101  *   case.
102  */
103 int sread(int fd, void *buf, size_t count);
104
105 /*
106  * NAME
107  *   swrite
108  *
109  * DESCRIPTION
110  *   Writes exactly `n' bytes or fails. Syntax and other behavior is analogous
111  *   to `write(2)'.
112  *
113  * PARAMETERS
114  *   `fd'          File descriptor to write to.
115  *   `buf'         Buffer that is to be written.
116  *   `count'       Number of bytes in the buffer.
117  *
118  * RETURN VALUE
119  *   Zero upon success or non-zero if an error occurred. `errno' is set in this
120  *   case.
121  */
122 int swrite(int fd, const void *buf, size_t count);
123
124 /*
125  * NAME
126  *   strsplit
127  *
128  * DESCRIPTION
129  *   Splits a string into parts and stores pointers to the parts in `fields'.
130  *   The characters split at are: " ", "\t", "\r", and "\n".
131  *
132  * PARAMETERS
133  *   `string'      String to split. This string will be modified. `fields' will
134  *                 contain pointers to parts of this string, so free'ing it
135  *                 will destroy `fields' as well.
136  *   `fields'      Array of strings where pointers to the parts will be stored.
137  *   `size'        Number of elements in the array. No more than `size'
138  *                 pointers will be stored in `fields'.
139  *
140  * RETURN VALUE
141  *    Returns the number of parts stored in `fields'.
142  */
143 int strsplit(char *string, char **fields, size_t size);
144
145 /*
146  * NAME
147  *   strjoin
148  *
149  * DESCRIPTION
150  *   Joins together several parts of a string using `sep' as a separator. This
151  *   is equivalent to the Perl built-in `join'.
152  *
153  * PARAMETERS
154  *   `dst'         Buffer where the result is stored. Can be NULL if you need to
155  *                 determine the required buffer size only.
156  *   `dst_len'     Length of the destination buffer. No more than this many
157  *                 bytes will be written to the memory pointed to by `dst',
158  *                 including the trailing null-byte. Must be zero if dst is
159  *                 NULL.
160  *   `fields'      Array of strings to be joined.
161  *   `fields_num'  Number of elements in the `fields' array.
162  *   `sep'         String to be inserted between any two elements of `fields'.
163  *                 This string is neither prepended nor appended to the result.
164  *                 Instead of passing "" (empty string) one can pass NULL.
165  *
166  * RETURN VALUE
167  *   Returns the number of characters in the resulting string, excluding a
168  *   tailing null byte. If this value is greater than or equal to "dst_len", the
169  *   result in "dst" is truncated (but still null terminated). On error a
170  *   negative value is returned.
171  */
172 int strjoin(char *dst, size_t dst_len, char **fields, size_t fields_num,
173             const char *sep);
174
175 /*
176  * NAME
177  *   escape_slashes
178  *
179  * DESCRIPTION
180  *   Removes slashes ("/") from "buffer". If buffer contains a single slash,
181  *   the result will be "root". Leading slashes are removed. All other slashes
182  *   are replaced with underscores ("_").
183  *   This function is used by plugin_dispatch_values() to escape all parts of
184  *   the identifier.
185  *
186  * PARAMETERS
187  *   `buffer'         String to be escaped.
188  *   `buffer_size'    Size of the buffer. No more then this many bytes will be
189  *                    written to `buffer', including the trailing null-byte.
190  *
191  * RETURN VALUE
192  *   Returns zero upon success and a value smaller than zero upon failure.
193  */
194 int escape_slashes(char *buffer, size_t buffer_size);
195
196 /**
197  * NAME
198  *   escape_string
199  *
200  * DESCRIPTION
201  *   escape_string quotes and escapes a string to be usable with collectd's
202  *   plain text protocol. "simple" strings are left as they are, for example if
203  *   buffer is 'simple' before the call, it will remain 'simple'. However, if
204  *   buffer contains 'more "complex"' before the call, the returned buffer will
205  *   contain '"more \"complex\""'.
206  *
207  *   If the buffer is too small to contain the escaped string, the string will
208  *   be truncated. However, leading and trailing double quotes, as well as an
209  *   ending null byte are guaranteed.
210  *
211  * RETURN VALUE
212  *   Returns zero on success, even if the string was truncated. Non-zero on
213  *   failure.
214  */
215 int escape_string(char *buffer, size_t buffer_size);
216
217 /*
218  * NAME
219  *   replace_special
220  *
221  * DESCRIPTION
222  *   Replaces any special characters (anything that's not alpha-numeric or a
223  *   dash) with an underscore.
224  *
225  *   E.g. "foo$bar&" would become "foo_bar_".
226  *
227  * PARAMETERS
228  *   `buffer'      String to be handled.
229  *   `buffer_size' Length of the string. The function returns after
230  *                 encountering a null-byte or reading this many bytes.
231  */
232 void replace_special(char *buffer, size_t buffer_size);
233
234 /*
235  * NAME
236  *   strunescape
237  *
238  * DESCRIPTION
239  *   Replaces any escaped characters in a string with the appropriate special
240  *   characters. The following escaped characters are recognized:
241  *
242  *     \t -> <tab>
243  *     \n -> <newline>
244  *     \r -> <carriage return>
245  *
246  *   For all other escacped characters only the backslash will be removed.
247  *
248  * PARAMETERS
249  *   `buf'         String to be unescaped.
250  *   `buf_len'     Length of the string, including the terminating null-byte.
251  *
252  * RETURN VALUE
253  *   Returns zero upon success, a value less than zero else.
254  */
255 int strunescape(char *buf, size_t buf_len);
256
257 /**
258  * Removed trailing newline characters (CR and LF) from buffer, which must be
259  * null terminated. Returns the length of the resulting string.
260  */
261 __attribute__((nonnull(1))) size_t strstripnewline(char *buffer);
262
263 /*
264  * NAME
265  *   timeval_cmp
266  *
267  * DESCRIPTION
268  *   Compare the two time values `tv0' and `tv1' and store the absolut value
269  *   of the difference in the time value pointed to by `delta' if it does not
270  *   equal NULL.
271  *
272  * RETURN VALUE
273  *   Returns an integer less than, equal to, or greater than zero if `tv0' is
274  *   less than, equal to, or greater than `tv1' respectively.
275  */
276 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta);
277
278 /* make sure tv_usec stores less than a second */
279 #define NORMALIZE_TIMEVAL(tv)                                                  \
280   do {                                                                         \
281     (tv).tv_sec += (tv).tv_usec / 1000000;                                     \
282     (tv).tv_usec = (tv).tv_usec % 1000000;                                     \
283   } while (0)
284
285 /* make sure tv_sec stores less than a second */
286 #define NORMALIZE_TIMESPEC(tv)                                                 \
287   do {                                                                         \
288     (tv).tv_sec += (tv).tv_nsec / 1000000000;                                  \
289     (tv).tv_nsec = (tv).tv_nsec % 1000000000;                                  \
290   } while (0)
291
292 int check_create_dir(const char *file_orig);
293
294 #ifdef HAVE_LIBKSTAT
295 #if HAVE_KSTAT_H
296 #include <kstat.h>
297 #endif
298 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name);
299 long long get_kstat_value(kstat_t *ksp, char *name);
300 #endif
301
302 #ifndef HAVE_HTONLL
303 unsigned long long ntohll(unsigned long long n);
304 unsigned long long htonll(unsigned long long n);
305 #endif
306
307 #if FP_LAYOUT_NEED_NOTHING
308 #define ntohd(d) (d)
309 #define htond(d) (d)
310 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
311 double ntohd(double d);
312 double htond(double d);
313 #else
314 #error                                                                         \
315     "Don't know how to convert between host and network representation of doubles."
316 #endif
317
318 int format_name(char *ret, int ret_len, const char *hostname,
319                 const char *plugin, const char *plugin_instance,
320                 const char *type, const char *type_instance);
321 #define FORMAT_VL(ret, ret_len, vl)                                            \
322   format_name(ret, ret_len, (vl)->host, (vl)->plugin, (vl)->plugin_instance,   \
323               (vl)->type, (vl)->type_instance)
324 int format_values(char *ret, size_t ret_len, const data_set_t *ds,
325                   const value_list_t *vl, bool store_rates);
326
327 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
328                      char **ret_plugin_instance, char **ret_type,
329                      char **ret_type_instance, char *default_host);
330 int parse_identifier_vl(const char *str, value_list_t *vl);
331 int parse_value(const char *value, value_t *ret_value, int ds_type);
332 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds);
333
334 /* parse_value_file reads "path" and parses its content as an integer or
335  * floating point, depending on "ds_type". On success, the value is stored in
336  * "ret_value" and zero is returned. On failure, a non-zero value is returned.
337  */
338 int parse_value_file(char const *path, value_t *ret_value, int ds_type);
339
340 #if !HAVE_GETPWNAM_R
341 struct passwd;
342 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
343                struct passwd **pwbufp);
344 #endif
345
346 int notification_init(notification_t *n, int severity, const char *message,
347                       const char *host, const char *plugin,
348                       const char *plugin_instance, const char *type,
349                       const char *type_instance);
350 #define NOTIFICATION_INIT_VL(n, vl)                                            \
351   notification_init(n, NOTIF_FAILURE, NULL, (vl)->host, (vl)->plugin,          \
352                     (vl)->plugin_instance, (vl)->type, (vl)->type_instance)
353
354 typedef int (*dirwalk_callback_f)(const char *dirname, const char *filename,
355                                   void *user_data);
356 int walk_directory(const char *dir, dirwalk_callback_f callback,
357                    void *user_data, int hidden);
358 /* Returns the number of bytes read or negative on error. */
359 ssize_t read_file_contents(char const *filename, char *buf, size_t bufsize);
360
361 counter_t counter_diff(counter_t old_value, counter_t new_value);
362
363 /* Convert a rate back to a value_t. When converting to a derive_t, counter_t
364  * or absolute_t, take fractional residuals into account. This is important
365  * when scaling counters, for example.
366  * Returns zero on success. Returns EAGAIN when called for the first time; in
367  * this case the value_t is invalid and the next call should succeed. Other
368  * return values indicate an error. */
369 int rate_to_value(value_t *ret_value, gauge_t rate,
370                   rate_to_value_state_t *state, int ds_type, cdtime_t t);
371
372 int value_to_rate(gauge_t *ret_rate, value_t value, int ds_type, cdtime_t t,
373                   value_to_rate_state_t *state);
374
375 /* Converts a service name (a string) to a port number
376  * (in the range [1-65535]). Returns less than zero on error. */
377 int service_name_to_port_number(const char *service_name);
378
379 /* Sets various, non-default, socket options */
380 void set_sock_opts(int sockfd);
381
382 /** Parse a string to a derive_t value. Returns zero on success or non-zero on
383  * failure. If failure is returned, ret_value is not touched. */
384 int strtoderive(const char *string, derive_t *ret_value);
385
386 /** Parse a string to a gauge_t value. Returns zero on success or non-zero on
387  * failure. If failure is returned, ret_value is not touched. */
388 int strtogauge(const char *string, gauge_t *ret_value);
389
390 int strarray_add(char ***ret_array, size_t *ret_array_len, char const *str);
391 void strarray_free(char **array, size_t array_len);
392
393 /** Check if the current process benefits from the capability passed in
394  * argument. Returns zero if it does, less than zero if it doesn't or on error.
395  * See capabilities(7) for the list of possible capabilities.
396  * */
397 int check_capability(int arg);
398
399 #endif /* COMMON_H */