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