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