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