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