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