]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils/utils.h
unit-tests: Further increase the test vector testing timeout
[people/ms/strongswan.git] / src / libstrongswan / utils / utils.h
CommitLineData
552cc11b 1/*
766141bc 2 * Copyright (C) 2008-2014 Tobias Brunner
552cc11b
MW
3 * Copyright (C) 2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
552cc11b
MW
15 */
16
17/**
bca34c37
TB
18 * @defgroup utils_i utils
19 * @{ @ingroup utils
552cc11b
MW
20 */
21
22#ifndef UTILS_H_
23#define UTILS_H_
24
25#include <sys/types.h>
26#include <stdlib.h>
27#include <stddef.h>
3f310c0d 28#include <sys/time.h>
0be12e35 29#include <string.h>
552cc11b 30
922ee2c5 31#ifdef WIN32
89f19ef8 32# include "compat/windows.h"
922ee2c5
MW
33#else
34# define _GNU_SOURCE
35# include <arpa/inet.h>
36# include <sys/socket.h>
37# include <netdb.h>
38# include <netinet/in.h>
266ee0a1 39# include <sched.h>
fc829ec9 40# include <poll.h>
922ee2c5
MW
41#endif
42
eab241fb
AS
43/**
44 * strongSwan program return codes
45 */
46#define SS_RC_LIBSTRONGSWAN_INTEGRITY 64
47#define SS_RC_DAEMON_INTEGRITY 65
3646c8a1 48#define SS_RC_INITIALIZATION_FAILED 66
eab241fb 49
5d8306de
AS
50#define SS_RC_FIRST SS_RC_LIBSTRONGSWAN_INTEGRITY
51#define SS_RC_LAST SS_RC_INITIALIZATION_FAILED
52
552cc11b
MW
53/**
54 * Number of bits in a byte
55 */
56#define BITS_PER_BYTE 8
57
58/**
59 * Default length for various auxiliary text buffers
60 */
61#define BUF_LEN 512
62
bb6be261
MW
63/**
64 * Build assertion macro for integer expressions, evaluates to 0
65 */
66#define BUILD_ASSERT(x) (sizeof(char[(x) ? 0 : -1]))
67
68/**
69 * Build time check to assert a is an array, evaluates to 0
70 *
71 * The address of an array element has a pointer type, which is not compatible
72 * to the array type.
73 */
74#define BUILD_ASSERT_ARRAY(a) \
75 BUILD_ASSERT(!__builtin_types_compatible_p(typeof(a), typeof(&(a)[0])))
76
552cc11b 77/**
a2a28d90 78 * General purpose boolean type.
552cc11b 79 */
a2a28d90
TB
80#ifdef HAVE_STDBOOL_H
81# include <stdbool.h>
82#else
83# ifndef HAVE__BOOL
84# define _Bool signed char
85# endif /* HAVE__BOOL */
86# define bool _Bool
87# define false 0
88# define true 1
89# define __bool_true_false_are_defined 1
90#endif /* HAVE_STDBOOL_H */
91#ifndef FALSE
92# define FALSE false
93#endif /* FALSE */
94#ifndef TRUE
95# define TRUE true
96#endif /* TRUE */
97
9ee8b3b4
MW
98#include "enum.h"
99#include "utils/strerror.h"
f65779dd
MW
100#ifdef __APPLE__
101# include "compat/apple.h"
102#endif
9ee8b3b4 103
a43f1e56
MW
104/**
105 * Directory separator character in paths on this platform
106 */
107#ifdef WIN32
108# define DIRECTORY_SEPARATOR "\\"
109#else
110# define DIRECTORY_SEPARATOR "/"
111#endif
112
87a79e6a
MW
113/**
114 * Initialize utility functions
115 */
116void utils_init();
117
118/**
119 * Deinitialize utility functions
120 */
121void utils_deinit();
122
a2a28d90
TB
123/**
124 * Helper function that compares two strings for equality
125 */
126static inline bool streq(const char *x, const char *y)
127{
128 return strcmp(x, y) == 0;
129}
552cc11b
MW
130
131/**
985dcab1 132 * Helper function that compares two strings for equality, length limited
552cc11b 133 */
985dcab1
TB
134static inline bool strneq(const char *x, const char *y, size_t len)
135{
136 return strncmp(x, y, len) == 0;
137}
552cc11b 138
f460facd
TB
139/**
140 * Helper function that checks if a string starts with a given prefix
141 */
142static inline bool strpfx(const char *x, const char *prefix)
143{
144 return strneq(x, prefix, strlen(prefix));
145}
146
63176bbc 147/**
a2a28d90 148 * Helper function that compares two strings for equality ignoring case
63176bbc 149 */
a2a28d90
TB
150static inline bool strcaseeq(const char *x, const char *y)
151{
152 return strcasecmp(x, y) == 0;
153}
63176bbc 154
7a3e0a63 155/**
985dcab1 156 * Helper function that compares two strings for equality ignoring case, length limited
7a3e0a63 157 */
985dcab1
TB
158static inline bool strncaseeq(const char *x, const char *y, size_t len)
159{
160 return strncasecmp(x, y, len) == 0;
161}
7a3e0a63 162
32a145fd
TB
163/**
164 * Helper function that checks if a string starts with a given prefix
165 */
166static inline bool strcasepfx(const char *x, const char *prefix)
167{
168 return strncaseeq(x, prefix, strlen(prefix));
169}
170
1038d9fe
MW
171/**
172 * NULL-safe strdup variant
173 */
753ca22f
TB
174static inline char *strdupnull(const char *s)
175{
176 return s ? strdup(s) : NULL;
177}
1038d9fe 178
552cc11b 179/**
985dcab1 180 * Helper function that compares two binary blobs for equality
552cc11b 181 */
985dcab1
TB
182static inline bool memeq(const void *x, const void *y, size_t len)
183{
184 return memcmp(x, y, len) == 0;
185}
552cc11b 186
b8339632
MW
187/**
188 * Same as memeq(), but with a constant runtime, safe for cryptographic use.
189 */
190bool memeq_const(const void *x, const void *y, size_t len);
191
6d4654b9
TB
192/**
193 * Calling memcpy() with NULL pointers, even with n == 0, results in undefined
194 * behavior according to the C standard. This version is guaranteed to not
195 * access the pointers if n is 0.
196 */
197static inline void *memcpy_noop(void *dst, const void *src, size_t n)
198{
199 return n ? memcpy(dst, src, n) : dst;
200}
920d466f
MW
201#ifdef memcpy
202# undef memcpy
203#endif
6d4654b9
TB
204#define memcpy(d,s,n) memcpy_noop(d,s,n)
205
206/**
207 * Calling memmove() with NULL pointers, even with n == 0, results in undefined
208 * behavior according to the C standard. This version is guaranteed to not
209 * access the pointers if n is 0.
210 */
211static inline void *memmove_noop(void *dst, const void *src, size_t n)
212{
213 return n ? memmove(dst, src, n) : dst;
214}
920d466f
MW
215#ifdef memmove
216# undef memmove
217#endif
6d4654b9
TB
218#define memmove(d,s,n) memmove_noop(d,s,n)
219
220/**
221 * Calling memset() with a NULL pointer, even with n == 0, results in undefined
222 * behavior according to the C standard. This version is guaranteed to not
223 * access the pointer if n is 0.
224 */
225static inline void *memset_noop(void *s, int c, size_t n)
226{
227 return n ? memset(s, c, n) : s;
228}
920d466f
MW
229#ifdef memset
230# undef memset
231#endif
6d4654b9
TB
232#define memset(s,c,n) memset_noop(s,c,n)
233
552cc11b
MW
234/**
235 * Macro gives back larger of two values.
236 */
e822fc57
TB
237#define max(x,y) ({ \
238 typeof(x) _x = (x); \
239 typeof(y) _y = (y); \
240 _x > _y ? _x : _y; })
241
552cc11b
MW
242/**
243 * Macro gives back smaller of two values.
244 */
e822fc57
TB
245#define min(x,y) ({ \
246 typeof(x) _x = (x); \
247 typeof(y) _y = (y); \
248 _x < _y ? _x : _y; })
552cc11b
MW
249
250/**
251 * Call destructor of an object, if object != NULL
252 */
253#define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
254
255/**
256 * Call offset destructor of an object, if object != NULL
257 */
258#define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
259
260/**
261 * Call function destructor of an object, if object != NULL
262 */
263#define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
264
265/**
266 * Debug macro to follow control flow
267 */
268#define POS printf("%s, line %d\n", __FILE__, __LINE__)
269
74eed73a
MW
270/**
271 * Object allocation/initialization macro, using designated initializer.
272 */
2e1f4a46
MW
273#define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \
274 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
74eed73a 275
0c832258
MW
276/**
277 * Aligning version of INIT().
278 *
279 * The returned pointer must be freed using free_align(), not free().
280 *
281 * @param this object to allocate/initialize
282 * @param align alignment for allocation, in bytes
283 * @param ... initializer
284 */
285#define INIT_ALIGN(this, align, ...) { \
286 (this) = malloc_align(sizeof(*(this)), align); \
287 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
288
1ef6c0ef
MW
289/**
290 * Object allocation/initialization macro, with extra allocated bytes at tail.
291 *
292 * The extra space gets zero-initialized.
293 *
294 * @param this pointer to object to allocate memory for
295 * @param extra number of bytes to allocate at end of this
296 * @param ... initializer
297 */
298#define INIT_EXTRA(this, extra, ...) { \
299 typeof(extra) _extra = (extra); \
300 (this) = malloc(sizeof(*(this)) + _extra); \
301 *(this) = (typeof(*(this))){ __VA_ARGS__ }; \
302 memset((this) + 1, 0, _extra); }
303
0c832258
MW
304/**
305 * Aligning version of INIT_EXTRA().
306 *
307 * The returned pointer must be freed using free_align(), not free().
308 *
309 * @param this object to allocate/initialize
310 * @param extra number of bytes to allocate at end of this
311 * @param align alignment for allocation, in bytes
312 * @param ... initializer
313 */
314#define INIT_EXTRA_ALIGN(this, extra, align, ...) { \
315 typeof(extra) _extra = (extra); \
316 (this) = malloc_align(sizeof(*(this)) + _extra, align); \
317 *(this) = (typeof(*(this))){ __VA_ARGS__ }; \
318 memset((this) + 1, 0, _extra); }
319
1a1ff9d1
MW
320/**
321 * Method declaration/definition macro, providing private and public interface.
322 *
323 * Defines a method name with this as first parameter and a return value ret,
324 * and an alias for this method with a _ prefix, having the this argument
325 * safely casted to the public interface iface.
326 * _name is provided a function pointer, but will get optimized out by GCC.
327 */
328#define METHOD(iface, name, ret, this, ...) \
23d2bf84
MW
329 static ret name(union {iface *_public; this;} \
330 __attribute__((transparent_union)), ##__VA_ARGS__); \
d185b6ac 331 static typeof(name) *_##name = (typeof(name)*)name; \
23d2bf84
MW
332 static ret name(this, ##__VA_ARGS__)
333
334/**
335 * Same as METHOD(), but is defined for two public interfaces.
336 */
337#define METHOD2(iface1, iface2, name, ret, this, ...) \
338 static ret name(union {iface1 *_public1; iface2 *_public2; this;} \
339 __attribute__((transparent_union)), ##__VA_ARGS__); \
d185b6ac 340 static typeof(name) *_##name = (typeof(name)*)name; \
1a1ff9d1
MW
341 static ret name(this, ##__VA_ARGS__)
342
9e932513
MW
343/**
344 * Callback declaration/definition macro, allowing casted first parameter.
345 *
346 * This is very similar to METHOD, but instead of casting the first parameter
347 * to a public interface, it uses a void*. This allows type safe definition
348 * of a callback function, while using the real type for the first parameter.
349 */
350#define CALLBACK(name, ret, param1, ...) \
351 static ret _cb_##name(union {void *_generic; param1;} \
352 __attribute__((transparent_union)), ##__VA_ARGS__); \
353 static typeof(_cb_##name) *name = (typeof(_cb_##name)*)_cb_##name; \
354 static ret _cb_##name(param1, ##__VA_ARGS__)
355
e79dbda3
TB
356/**
357 * This macro allows counting the number of arguments passed to a macro.
358 * Combined with the VA_ARGS_DISPATCH() macro this can be used to implement
359 * macro overloading based on the number of arguments.
360 * 0 to 10 arguments are currently supported.
361 */
362#define VA_ARGS_NUM(...) _VA_ARGS_NUM(0,##__VA_ARGS__,10,9,8,7,6,5,4,3,2,1,0)
363#define _VA_ARGS_NUM(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NUM,...) NUM
364
365/**
366 * This macro can be used to dispatch a macro call based on the number of given
367 * arguments, for instance:
368 *
369 * @code
370 * #define MY_MACRO(...) VA_ARGS_DISPATCH(MY_MACRO, __VA_ARGS__)(__VA_ARGS__)
371 * #define MY_MACRO1(arg) one_arg(arg)
372 * #define MY_MACRO2(arg1,arg2) two_args(arg1,arg2)
373 * @endcode
374 *
375 * MY_MACRO() can now be called with either one or two arguments, which will
376 * resolve to one_arg(arg) or two_args(arg1,arg2), respectively.
377 */
378#define VA_ARGS_DISPATCH(func, ...) _VA_ARGS_DISPATCH(func, VA_ARGS_NUM(__VA_ARGS__))
379#define _VA_ARGS_DISPATCH(func, num) __VA_ARGS_DISPATCH(func, num)
380#define __VA_ARGS_DISPATCH(func, num) func ## num
381
7ba89ccd
MW
382/**
383 * Architecture independent bitfield definition helpers (at least with GCC).
384 *
385 * Defines a bitfield with a type t and a fixed size of bitfield members, e.g.:
386 * BITFIELD2(u_int8_t,
387 * low: 4,
388 * high: 4,
389 * ) flags;
390 * The member defined first placed at bit 0.
391 */
392#if BYTE_ORDER == LITTLE_ENDIAN
393#define BITFIELD2(t, a, b,...) struct { t a; t b; __VA_ARGS__}
394#define BITFIELD3(t, a, b, c,...) struct { t a; t b; t c; __VA_ARGS__}
395#define BITFIELD4(t, a, b, c, d,...) struct { t a; t b; t c; t d; __VA_ARGS__}
396#define BITFIELD5(t, a, b, c, d, e,...) struct { t a; t b; t c; t d; t e; __VA_ARGS__}
397#elif BYTE_ORDER == BIG_ENDIAN
398#define BITFIELD2(t, a, b,...) struct { t b; t a; __VA_ARGS__}
399#define BITFIELD3(t, a, b, c,...) struct { t c; t b; t a; __VA_ARGS__}
400#define BITFIELD4(t, a, b, c, d,...) struct { t d; t c; t b; t a; __VA_ARGS__}
401#define BITFIELD5(t, a, b, c, d, e,...) struct { t e; t d; t c; t b; t a; __VA_ARGS__}
402#endif
403
552cc11b
MW
404/**
405 * Macro to allocate a sized type.
406 */
407#define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
408
fca4d3ee
MW
409/**
410 * Get the number of elements in an array
411 */
11bf11c1
MW
412#define countof(array) (sizeof(array)/sizeof((array)[0]) \
413 + BUILD_ASSERT_ARRAY(array))
fca4d3ee 414
479f2950
MW
415/**
416 * Ignore result of functions tagged with warn_unused_result attributes
417 */
d0230850 418#define ignore_result(call) { if(call){}; }
479f2950 419
552cc11b
MW
420/**
421 * Assign a function as a class method
422 */
423#define ASSIGN(method, function) (method = (typeof(method))function)
424
425/**
426 * time_t not defined
427 */
428#define UNDEFINED_TIME 0
429
9f0327e6
AS
430/**
431 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
432 */
433#define TIME_32_BIT_SIGNED_MAX 0x7fffffff
434
cc396286
TB
435/**
436 * define some missing fixed width int types on OpenSolaris.
437 * TODO: since the uintXX_t types are defined by the C99 standard we should
438 * probably use those anyway
439 */
922ee2c5 440#if defined __sun || defined WIN32
cc396286
TB
441 #include <stdint.h>
442 typedef uint8_t u_int8_t;
443 typedef uint16_t u_int16_t;
444 typedef uint32_t u_int32_t;
445 typedef uint64_t u_int64_t;
446#endif
447
051064ac
MW
448#ifdef HAVE_INT128
449/**
450 * 128 bit wide signed integer, if supported
451 */
452typedef __int128 int128_t;
453/**
454 * 128 bit wide unsigned integer, if supported
455 */
456typedef unsigned __int128 u_int128_t;
3ba3be97
MW
457
458# define MAX_INT_TYPE int128_t
459# define MAX_UINT_TYPE u_int128_t
460#else
461# define MAX_INT_TYPE int64_t
462# define MAX_UINT_TYPE u_int64_t
051064ac
MW
463#endif
464
552cc11b
MW
465typedef enum status_t status_t;
466
467/**
468 * Return values of function calls.
469 */
470enum status_t {
471 /**
472 * Call succeeded.
473 */
474 SUCCESS,
7daf5226 475
552cc11b
MW
476 /**
477 * Call failed.
478 */
479 FAILED,
7daf5226 480
552cc11b
MW
481 /**
482 * Out of resources.
483 */
484 OUT_OF_RES,
7daf5226 485
552cc11b
MW
486 /**
487 * The suggested operation is already done
488 */
489 ALREADY_DONE,
7daf5226 490
552cc11b
MW
491 /**
492 * Not supported.
493 */
494 NOT_SUPPORTED,
7daf5226 495
552cc11b
MW
496 /**
497 * One of the arguments is invalid.
498 */
499 INVALID_ARG,
7daf5226 500
552cc11b
MW
501 /**
502 * Something could not be found.
503 */
504 NOT_FOUND,
7daf5226 505
552cc11b
MW
506 /**
507 * Error while parsing.
508 */
509 PARSE_ERROR,
7daf5226 510
552cc11b
MW
511 /**
512 * Error while verifying.
513 */
514 VERIFY_ERROR,
7daf5226 515
552cc11b
MW
516 /**
517 * Object in invalid state.
518 */
519 INVALID_STATE,
7daf5226 520
552cc11b
MW
521 /**
522 * Destroy object which called method belongs to.
523 */
524 DESTROY_ME,
7daf5226 525
552cc11b
MW
526 /**
527 * Another call to the method is required.
528 */
529 NEED_MORE,
530};
531
532/**
533 * enum_names for type status_t.
534 */
535extern enum_name_t *status_names;
536
4d174272
MW
537typedef enum tty_escape_t tty_escape_t;
538
539/**
540 * Excape codes for tty colors
541 */
542enum tty_escape_t {
543 /** text properties */
544 TTY_RESET,
545 TTY_BOLD,
546 TTY_UNDERLINE,
547 TTY_BLINKING,
548
549 /** foreground colors */
550 TTY_FG_BLACK,
551 TTY_FG_RED,
552 TTY_FG_GREEN,
553 TTY_FG_YELLOW,
554 TTY_FG_BLUE,
555 TTY_FG_MAGENTA,
556 TTY_FG_CYAN,
557 TTY_FG_WHITE,
558 TTY_FG_DEF,
559
560 /** background colors */
561 TTY_BG_BLACK,
562 TTY_BG_RED,
563 TTY_BG_GREEN,
564 TTY_BG_YELLOW,
565 TTY_BG_BLUE,
566 TTY_BG_MAGENTA,
567 TTY_BG_CYAN,
568 TTY_BG_WHITE,
569 TTY_BG_DEF,
570};
571
572/**
573 * Get the escape string for a given TTY color, empty string on non-tty fd
574 */
575char* tty_escape_get(int fd, tty_escape_t escape);
576
552cc11b
MW
577/**
578 * deprecated pluto style return value:
579 * error message, NULL for success
580 */
581typedef const char *err_t;
582
583/**
584 * Handle struct timeval like an own type.
585 */
586typedef struct timeval timeval_t;
587
588/**
589 * Handle struct timespec like an own type.
590 */
591typedef struct timespec timespec_t;
592
593/**
594 * Handle struct chunk_t like an own type.
595 */
596typedef struct sockaddr sockaddr_t;
597
f206bb74
MW
598/**
599 * malloc(), but returns aligned memory.
600 *
601 * The returned pointer must be freed using free_align(), not free().
602 *
603 * @param size size of allocated data
604 * @param align alignment, up to 255 bytes, usually a power of 2
605 * @return allocated hunk, aligned to align bytes
606 */
607void* malloc_align(size_t size, u_int8_t align);
608
609/**
610 * Free a hunk allocated by malloc_align().
611 *
612 * @param ptr hunk to free
613 */
614void free_align(void *ptr);
615
552cc11b
MW
616/**
617 * Same as memcpy, but XORs src into dst instead of copy
618 */
619void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
620
ed678b52
MW
621/**
622 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
623 */
624void memwipe_noinline(void *ptr, size_t n);
625
626/**
627 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
628 */
629static inline void memwipe_inline(void *ptr, size_t n)
630{
631 volatile char *c = (volatile char*)ptr;
d45b242b 632 size_t m, i;
ed678b52
MW
633
634 /* byte wise until long aligned */
d45b242b 635 for (i = 0; (uintptr_t)&c[i] % sizeof(long) && i < n; i++)
ed678b52
MW
636 {
637 c[i] = 0;
638 }
d45b242b
MW
639 /* word wise */
640 if (n >= sizeof(long))
ed678b52 641 {
d45b242b
MW
642 for (m = n - sizeof(long); i <= m; i += sizeof(long))
643 {
644 *(volatile long*)&c[i] = 0;
645 }
ed678b52
MW
646 }
647 /* byte wise of the rest */
648 for (; i < n; i++)
649 {
650 c[i] = 0;
651 }
652}
653
654/**
655 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
656 */
657static inline void memwipe(void *ptr, size_t n)
658{
c480b5f4
TB
659 if (!ptr)
660 {
661 return;
662 }
ed678b52
MW
663 if (__builtin_constant_p(n))
664 {
665 memwipe_inline(ptr, n);
666 }
667 else
668 {
669 memwipe_noinline(ptr, n);
670 }
671}
672
81736d7d
TB
673/**
674 * A variant of strstr with the characteristics of memchr, where haystack is not
675 * a null-terminated string but simply a memory area of length n.
676 */
677void *memstr(const void *haystack, const char *needle, size_t n);
678
2ed241ae
TB
679/**
680 * Replacement for memrchr(3) if it is not provided by the C library.
681 *
682 * @param s start of the memory area to search
683 * @param c character to search
684 * @param n length of memory area to search
685 * @return pointer to the found character or NULL
686 */
687void *utils_memrchr(const void *s, int c, size_t n);
688
689#ifndef HAVE_MEMRCHR
690#define memrchr(s,c,n) utils_memrchr(s,c,n)
691#endif
692
d543d9ca
TB
693/**
694 * Translates the characters in the given string, searching for characters
695 * in 'from' and mapping them to characters in 'to'.
696 * The two characters sets 'from' and 'to' must contain the same number of
697 * characters.
698 */
699char *translate(char *str, const char *from, const char *to);
700
ccb6758e 701/**
4ab38d98 702 * Replaces all occurrences of search in the given string with replace.
ccb6758e
TB
703 *
704 * Allocates memory only if anything is replaced in the string. The original
705 * string is also returned if any of the arguments are invalid (e.g. if search
706 * is empty or any of them are NULL).
707 *
708 * @param str original string
709 * @param search string to search for and replace
4ab38d98 710 * @param replace string to replace found occurrences with
ccb6758e
TB
711 * @return allocated string, if anything got replaced, str otherwise
712 */
713char *strreplace(const char *str, const char *search, const char *replace);
714
66c0801d
MW
715/**
716 * Portable function to wait for SIGINT/SIGTERM (or equivalent).
717 */
718void wait_sigint();
719
766141bc
TB
720/**
721 * Like dirname(3) returns the directory part of the given null-terminated
722 * pathname, up to but not including the final '/' (or '.' if no '/' is found).
723 * Trailing '/' are not counted as part of the pathname.
724 *
725 * The difference is that it does this in a thread-safe manner (i.e. it does not
726 * use static buffers) and does not modify the original path.
727 *
728 * @param path original pathname
729 * @return allocated directory component
730 */
731char *path_dirname(const char *path);
732
733/**
734 * Like basename(3) returns the filename part of the given null-terminated path,
735 * i.e. the part following the final '/' (or '.' if path is empty or NULL).
736 * Trailing '/' are not counted as part of the pathname.
737 *
738 * The difference is that it does this in a thread-safe manner (i.e. it does not
739 * use static buffers) and does not modify the original path.
740 *
741 * @param path original pathname
742 * @return allocated filename component
743 */
744char *path_basename(const char *path);
745
67b3bcd1
MW
746/**
747 * Check if a given path is absolute.
748 *
749 * @param path path to check
750 * @return TRUE if absolute, FALSE if relative
751 */
752bool path_absolute(const char *path);
753
6c20579a 754/**
7daf5226 755 * Creates a directory and all required parent directories.
6c20579a 756 *
3f310c0d 757 * @param path path to the new directory
7daf5226 758 * @param mode permissions of the new directory/directories
6c20579a
TB
759 * @return TRUE on success
760 */
761bool mkdir_p(const char *path, mode_t mode);
762
9a8fdc15
TB
763#ifndef HAVE_CLOSEFROM
764/**
765 * Close open file descriptors greater than or equal to lowfd.
766 *
4ab38d98 767 * @param lowfd start closing file descriptors from here
9a8fdc15
TB
768 */
769void closefrom(int lowfd);
770#endif
771
3f310c0d
MW
772/**
773 * Get a timestamp from a monotonic time source.
774 *
775 * While the time()/gettimeofday() functions are affected by leap seconds
776 * and system time changes, this function returns ever increasing monotonic
777 * time stamps.
778 *
779 * @param tv timeval struct receiving monotonic timestamps, or NULL
780 * @return monotonic timestamp in seconds
781 */
782time_t time_monotonic(timeval_t *tv);
783
eecd41e3
TB
784/**
785 * Add the given number of milliseconds to the given timeval struct
786 *
787 * @param tv timeval struct to modify
788 * @param ms number of milliseconds
789 */
790static inline void timeval_add_ms(timeval_t *tv, u_int ms)
791{
792 tv->tv_usec += ms * 1000;
819c02db 793 while (tv->tv_usec >= 1000000 /* 1s */)
eecd41e3
TB
794 {
795 tv->tv_usec -= 1000000;
796 tv->tv_sec++;
797 }
798}
799
081ae2eb
MW
800/**
801 * returns null
802 */
803void *return_null();
804
233b853d
MW
805/**
806 * No-Operation function
807 */
808void nop();
809
da17b016
MW
810/**
811 * returns TRUE
812 */
813bool return_true();
814
815/**
816 * returns FALSE
817 */
818bool return_false();
819
502edf42
MW
820/**
821 * returns FAILED
822 */
823status_t return_failed();
824
4755ab50
MW
825/**
826 * returns SUCCESS
827 */
828status_t return_success();
829
0be12e35
MW
830/**
831 * Write a 16-bit host order value in network order to an unaligned address.
832 *
833 * @param host host order 16-bit value
834 * @param network unaligned address to write network order value to
835 */
836static inline void htoun16(void *network, u_int16_t host)
837{
dbee988e
MW
838 char *unaligned = (char*)network;
839
0be12e35 840 host = htons(host);
dbee988e 841 memcpy(unaligned, &host, sizeof(host));
0be12e35
MW
842}
843
844/**
845 * Write a 32-bit host order value in network order to an unaligned address.
846 *
847 * @param host host order 32-bit value
848 * @param network unaligned address to write network order value to
849 */
850static inline void htoun32(void *network, u_int32_t host)
851{
dbee988e
MW
852 char *unaligned = (char*)network;
853
0be12e35 854 host = htonl(host);
dbee988e 855 memcpy((char*)unaligned, &host, sizeof(host));
0be12e35
MW
856}
857
fbeb9454
AS
858/**
859 * Write a 64-bit host order value in network order to an unaligned address.
860 *
a91462df 861 * @param host host order 64-bit value
fbeb9454
AS
862 * @param network unaligned address to write network order value to
863 */
864static inline void htoun64(void *network, u_int64_t host)
865{
866 char *unaligned = (char*)network;
f4e25e60
MW
867
868#ifdef be64toh
869 host = htobe64(host);
870 memcpy((char*)unaligned, &host, sizeof(host));
871#else
fbeb9454
AS
872 u_int32_t high_part, low_part;
873
874 high_part = host >> 32;
875 high_part = htonl(high_part);
876 low_part = host & 0xFFFFFFFFLL;
877 low_part = htonl(low_part);
878
879 memcpy(unaligned, &high_part, sizeof(high_part));
880 unaligned += sizeof(high_part);
881 memcpy(unaligned, &low_part, sizeof(low_part));
f4e25e60 882#endif
fbeb9454
AS
883}
884
0be12e35
MW
885/**
886 * Read a 16-bit value in network order from an unaligned address to host order.
887 *
888 * @param network unaligned address to read network order value from
889 * @return host order value
890 */
891static inline u_int16_t untoh16(void *network)
892{
dbee988e 893 char *unaligned = (char*)network;
0be12e35
MW
894 u_int16_t tmp;
895
dbee988e 896 memcpy(&tmp, unaligned, sizeof(tmp));
0be12e35
MW
897 return ntohs(tmp);
898}
899
900/**
901 * Read a 32-bit value in network order from an unaligned address to host order.
902 *
903 * @param network unaligned address to read network order value from
904 * @return host order value
905 */
906static inline u_int32_t untoh32(void *network)
907{
dbee988e 908 char *unaligned = (char*)network;
0be12e35
MW
909 u_int32_t tmp;
910
dbee988e 911 memcpy(&tmp, unaligned, sizeof(tmp));
f8f4f31a 912 return ntohl(tmp);
0be12e35
MW
913}
914
fbeb9454
AS
915/**
916 * Read a 64-bit value in network order from an unaligned address to host order.
917 *
918 * @param network unaligned address to read network order value from
919 * @return host order value
920 */
921static inline u_int64_t untoh64(void *network)
922{
923 char *unaligned = (char*)network;
f4e25e60
MW
924
925#ifdef be64toh
926 u_int64_t tmp;
927
928 memcpy(&tmp, unaligned, sizeof(tmp));
929 return be64toh(tmp);
930#else
fbeb9454
AS
931 u_int32_t high_part, low_part;
932
933 memcpy(&high_part, unaligned, sizeof(high_part));
934 unaligned += sizeof(high_part);
935 memcpy(&low_part, unaligned, sizeof(low_part));
936
937 high_part = ntohl(high_part);
938 low_part = ntohl(low_part);
939
940 return (((u_int64_t)high_part) << 32) + low_part;
f4e25e60 941#endif
fbeb9454
AS
942}
943
84044f9c 944/**
812ae898 945 * Get the padding required to make size a multiple of alignment
84044f9c 946 */
812ae898 947static inline size_t pad_len(size_t size, size_t alignment)
84044f9c 948{
812ae898 949 size_t remainder;
84044f9c 950
812ae898
TB
951 remainder = size % alignment;
952 return remainder ? alignment - remainder : 0;
953}
954
955/**
956 * Round up size to be multiple of alignment
957 */
958static inline size_t round_up(size_t size, size_t alignment)
959{
960 return size + pad_len(size, alignment);
84044f9c
MW
961}
962
963/**
812ae898 964 * Round down size to be a multiple of alignment
84044f9c 965 */
812ae898 966static inline size_t round_down(size_t size, size_t alignment)
84044f9c 967{
812ae898 968 return size - (size % alignment);
84044f9c
MW
969}
970
552cc11b
MW
971/**
972 * Special type to count references
973 */
4d04e2c6 974typedef u_int refcount_t;
efd0fe21 975
a0c2370e
TB
976/* use __atomic* built-ins with GCC 4.7 and newer */
977#ifdef __GNUC__
978# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 6))
979# define HAVE_GCC_ATOMIC_OPERATIONS
980# endif
981#endif
982
efd0fe21
MW
983#ifdef HAVE_GCC_ATOMIC_OPERATIONS
984
0f603d42
TB
985#define ref_get(ref) __atomic_add_fetch(ref, 1, __ATOMIC_RELAXED)
986/* The relaxed memory model works fine for increments as these (usually) don't
987 * change the state of refcounted objects. But here we have to ensure that we
988 * free the right stuff if ref counted objects are mutable. So we have to sync
989 * with other threads that call ref_put(). It would be sufficient to use
990 * __ATOMIC_RELEASE here and then call __atomic_thread_fence() with
991 * __ATOMIC_ACQUIRE if we reach 0, but since we don't have control over the use
992 * of ref_put() we have to make sure. */
993#define ref_put(ref) (!__atomic_sub_fetch(ref, 1, __ATOMIC_ACQ_REL))
994#define ref_cur(ref) __atomic_load_n(ref, __ATOMIC_RELAXED)
995
996#define _cas_impl(ptr, oldval, newval) ({ typeof(oldval) _old = oldval; \
997 __atomic_compare_exchange_n(ptr, &_old, newval, FALSE, \
998 __ATOMIC_SEQ_CST, __ATOMIC_RELAXED); })
999#define cas_bool(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
1000#define cas_ptr(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
1001
1002#elif defined(HAVE_GCC_SYNC_OPERATIONS)
1003
3160b92a 1004#define ref_get(ref) __sync_add_and_fetch(ref, 1)
efd0fe21 1005#define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
efedd0d2 1006#define ref_cur(ref) __sync_fetch_and_add(ref, 0)
efd0fe21 1007
5317dd68
TB
1008#define cas_bool(ptr, oldval, newval) \
1009 (__sync_bool_compare_and_swap(ptr, oldval, newval))
1010#define cas_ptr(ptr, oldval, newval) \
1011 (__sync_bool_compare_and_swap(ptr, oldval, newval))
1012
0f603d42 1013#else /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
efd0fe21 1014
552cc11b
MW
1015/**
1016 * Get a new reference.
1017 *
efedd0d2 1018 * Increments the reference counter atomically.
552cc11b
MW
1019 *
1020 * @param ref pointer to ref counter
3160b92a 1021 * @return new value of ref
552cc11b 1022 */
3160b92a 1023refcount_t ref_get(refcount_t *ref);
552cc11b
MW
1024
1025/**
1026 * Put back a unused reference.
1027 *
efedd0d2 1028 * Decrements the reference counter atomically and
552cc11b
MW
1029 * says if more references available.
1030 *
1031 * @param ref pointer to ref counter
1032 * @return TRUE if no more references counted
1033 */
1034bool ref_put(refcount_t *ref);
1035
efedd0d2
TB
1036/**
1037 * Get the current value of the reference counter.
1038 *
1039 * @param ref pointer to ref counter
1040 * @return current value of ref
1041 */
1042refcount_t ref_cur(refcount_t *ref);
1043
5317dd68
TB
1044/**
1045 * Atomically replace value of ptr with newval if it currently equals oldval.
1046 *
1047 * @param ptr pointer to variable
1048 * @param oldval old value of the variable
1049 * @param newval new value set if possible
1050 * @return TRUE if value equaled oldval and newval was written
1051 */
1052bool cas_bool(bool *ptr, bool oldval, bool newval);
1053
1054/**
1055 * Atomically replace value of ptr with newval if it currently equals oldval.
1056 *
1057 * @param ptr pointer to variable
1058 * @param oldval old value of the variable
1059 * @param newval new value set if possible
1060 * @return TRUE if value equaled oldval and newval was written
1061 */
1062bool cas_ptr(void **ptr, void *oldval, void *newval);
1063
efd0fe21
MW
1064#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
1065
2077d996
MW
1066#ifndef HAVE_FMEMOPEN
1067# ifdef HAVE_FUNOPEN
9df621d2
MW
1068# define HAVE_FMEMOPEN
1069# define HAVE_FMEMOPEN_FALLBACK
5ac29360 1070# include <stdio.h>
2077d996
MW
1071/**
1072 * fmemopen(3) fallback using BSD funopen.
1073 *
1074 * We could also provide one using fopencookie(), but should we have it we
1075 * most likely have fmemopen().
1076 *
1077 * fseek() is currently not supported.
1078 */
1079FILE *fmemopen(void *buf, size_t size, const char *mode);
1080# endif /* FUNOPEN */
1081#endif /* FMEMOPEN */
1082
552cc11b 1083/**
d25ce370 1084 * printf hook for time_t.
552cc11b 1085 *
7daf5226 1086 * Arguments are:
323f9f99 1087 * time_t* time, bool utc
552cc11b 1088 */
1b40b74d 1089int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 1090 const void *const *args);
552cc11b
MW
1091
1092/**
d25ce370 1093 * printf hook for time_t deltas.
552cc11b 1094 *
7daf5226 1095 * Arguments are:
323f9f99 1096 * time_t* begin, time_t* end
552cc11b 1097 */
1b40b74d 1098int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 1099 const void *const *args);
552cc11b
MW
1100
1101/**
d25ce370 1102 * printf hook for memory areas.
552cc11b 1103 *
7daf5226 1104 * Arguments are:
817ab8a8 1105 * u_char *ptr, u_int len
552cc11b 1106 */
1b40b74d 1107int mem_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 1108 const void *const *args);
552cc11b 1109
1490ff4d 1110#endif /** UTILS_H_ @}*/