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