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