utils: Check if the parameter passed to countof() is actually an array type
[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 + BUILD_ASSERT_ARRAY(array))
361
362 /**
363 * Ignore result of functions tagged with warn_unused_result attributes
364 */
365 #define ignore_result(call) { if(call){}; }
366
367 /**
368 * Assign a function as a class method
369 */
370 #define ASSIGN(method, function) (method = (typeof(method))function)
371
372 /**
373 * time_t not defined
374 */
375 #define UNDEFINED_TIME 0
376
377 /**
378 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
379 */
380 #define TIME_32_BIT_SIGNED_MAX 0x7fffffff
381
382 /**
383 * define some missing fixed width int types on OpenSolaris.
384 * TODO: since the uintXX_t types are defined by the C99 standard we should
385 * probably use those anyway
386 */
387 #if defined __sun || defined WIN32
388 #include <stdint.h>
389 typedef uint8_t u_int8_t;
390 typedef uint16_t u_int16_t;
391 typedef uint32_t u_int32_t;
392 typedef uint64_t u_int64_t;
393 #endif
394
395 typedef enum status_t status_t;
396
397 /**
398 * Return values of function calls.
399 */
400 enum status_t {
401 /**
402 * Call succeeded.
403 */
404 SUCCESS,
405
406 /**
407 * Call failed.
408 */
409 FAILED,
410
411 /**
412 * Out of resources.
413 */
414 OUT_OF_RES,
415
416 /**
417 * The suggested operation is already done
418 */
419 ALREADY_DONE,
420
421 /**
422 * Not supported.
423 */
424 NOT_SUPPORTED,
425
426 /**
427 * One of the arguments is invalid.
428 */
429 INVALID_ARG,
430
431 /**
432 * Something could not be found.
433 */
434 NOT_FOUND,
435
436 /**
437 * Error while parsing.
438 */
439 PARSE_ERROR,
440
441 /**
442 * Error while verifying.
443 */
444 VERIFY_ERROR,
445
446 /**
447 * Object in invalid state.
448 */
449 INVALID_STATE,
450
451 /**
452 * Destroy object which called method belongs to.
453 */
454 DESTROY_ME,
455
456 /**
457 * Another call to the method is required.
458 */
459 NEED_MORE,
460 };
461
462 /**
463 * enum_names for type status_t.
464 */
465 extern enum_name_t *status_names;
466
467 typedef enum tty_escape_t tty_escape_t;
468
469 /**
470 * Excape codes for tty colors
471 */
472 enum tty_escape_t {
473 /** text properties */
474 TTY_RESET,
475 TTY_BOLD,
476 TTY_UNDERLINE,
477 TTY_BLINKING,
478
479 /** foreground colors */
480 TTY_FG_BLACK,
481 TTY_FG_RED,
482 TTY_FG_GREEN,
483 TTY_FG_YELLOW,
484 TTY_FG_BLUE,
485 TTY_FG_MAGENTA,
486 TTY_FG_CYAN,
487 TTY_FG_WHITE,
488 TTY_FG_DEF,
489
490 /** background colors */
491 TTY_BG_BLACK,
492 TTY_BG_RED,
493 TTY_BG_GREEN,
494 TTY_BG_YELLOW,
495 TTY_BG_BLUE,
496 TTY_BG_MAGENTA,
497 TTY_BG_CYAN,
498 TTY_BG_WHITE,
499 TTY_BG_DEF,
500 };
501
502 /**
503 * Get the escape string for a given TTY color, empty string on non-tty fd
504 */
505 char* tty_escape_get(int fd, tty_escape_t escape);
506
507 /**
508 * deprecated pluto style return value:
509 * error message, NULL for success
510 */
511 typedef const char *err_t;
512
513 /**
514 * Handle struct timeval like an own type.
515 */
516 typedef struct timeval timeval_t;
517
518 /**
519 * Handle struct timespec like an own type.
520 */
521 typedef struct timespec timespec_t;
522
523 /**
524 * Handle struct chunk_t like an own type.
525 */
526 typedef struct sockaddr sockaddr_t;
527
528 /**
529 * Same as memcpy, but XORs src into dst instead of copy
530 */
531 void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
532
533 /**
534 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
535 */
536 void memwipe_noinline(void *ptr, size_t n);
537
538 /**
539 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
540 */
541 static inline void memwipe_inline(void *ptr, size_t n)
542 {
543 volatile char *c = (volatile char*)ptr;
544 size_t m, i;
545
546 /* byte wise until long aligned */
547 for (i = 0; (uintptr_t)&c[i] % sizeof(long) && i < n; i++)
548 {
549 c[i] = 0;
550 }
551 /* word wise */
552 if (n >= sizeof(long))
553 {
554 for (m = n - sizeof(long); i <= m; i += sizeof(long))
555 {
556 *(volatile long*)&c[i] = 0;
557 }
558 }
559 /* byte wise of the rest */
560 for (; i < n; i++)
561 {
562 c[i] = 0;
563 }
564 }
565
566 /**
567 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
568 */
569 static inline void memwipe(void *ptr, size_t n)
570 {
571 if (!ptr)
572 {
573 return;
574 }
575 if (__builtin_constant_p(n))
576 {
577 memwipe_inline(ptr, n);
578 }
579 else
580 {
581 memwipe_noinline(ptr, n);
582 }
583 }
584
585 /**
586 * A variant of strstr with the characteristics of memchr, where haystack is not
587 * a null-terminated string but simply a memory area of length n.
588 */
589 void *memstr(const void *haystack, const char *needle, size_t n);
590
591 /**
592 * Replacement for memrchr(3) if it is not provided by the C library.
593 *
594 * @param s start of the memory area to search
595 * @param c character to search
596 * @param n length of memory area to search
597 * @return pointer to the found character or NULL
598 */
599 void *utils_memrchr(const void *s, int c, size_t n);
600
601 #ifndef HAVE_MEMRCHR
602 #define memrchr(s,c,n) utils_memrchr(s,c,n)
603 #endif
604
605 /**
606 * Translates the characters in the given string, searching for characters
607 * in 'from' and mapping them to characters in 'to'.
608 * The two characters sets 'from' and 'to' must contain the same number of
609 * characters.
610 */
611 char *translate(char *str, const char *from, const char *to);
612
613 /**
614 * Replaces all occurrences of search in the given string with replace.
615 *
616 * Allocates memory only if anything is replaced in the string. The original
617 * string is also returned if any of the arguments are invalid (e.g. if search
618 * is empty or any of them are NULL).
619 *
620 * @param str original string
621 * @param search string to search for and replace
622 * @param replace string to replace found occurrences with
623 * @return allocated string, if anything got replaced, str otherwise
624 */
625 char *strreplace(const char *str, const char *search, const char *replace);
626
627 /**
628 * Portable function to wait for SIGINT/SIGTERM (or equivalent).
629 */
630 void wait_sigint();
631
632 /**
633 * Like dirname(3) returns the directory part of the given null-terminated
634 * pathname, up to but not including the final '/' (or '.' if no '/' is found).
635 * Trailing '/' are not counted as part of the pathname.
636 *
637 * The difference is that it does this in a thread-safe manner (i.e. it does not
638 * use static buffers) and does not modify the original path.
639 *
640 * @param path original pathname
641 * @return allocated directory component
642 */
643 char *path_dirname(const char *path);
644
645 /**
646 * Like basename(3) returns the filename part of the given null-terminated path,
647 * i.e. the part following the final '/' (or '.' if path is empty or NULL).
648 * Trailing '/' are not counted as part of the pathname.
649 *
650 * The difference is that it does this in a thread-safe manner (i.e. it does not
651 * use static buffers) and does not modify the original path.
652 *
653 * @param path original pathname
654 * @return allocated filename component
655 */
656 char *path_basename(const char *path);
657
658 /**
659 * Check if a given path is absolute.
660 *
661 * @param path path to check
662 * @return TRUE if absolute, FALSE if relative
663 */
664 bool path_absolute(const char *path);
665
666 /**
667 * Creates a directory and all required parent directories.
668 *
669 * @param path path to the new directory
670 * @param mode permissions of the new directory/directories
671 * @return TRUE on success
672 */
673 bool mkdir_p(const char *path, mode_t mode);
674
675 #ifndef HAVE_CLOSEFROM
676 /**
677 * Close open file descriptors greater than or equal to lowfd.
678 *
679 * @param lowfd start closing file descriptors from here
680 */
681 void closefrom(int lowfd);
682 #endif
683
684 /**
685 * Get a timestamp from a monotonic time source.
686 *
687 * While the time()/gettimeofday() functions are affected by leap seconds
688 * and system time changes, this function returns ever increasing monotonic
689 * time stamps.
690 *
691 * @param tv timeval struct receiving monotonic timestamps, or NULL
692 * @return monotonic timestamp in seconds
693 */
694 time_t time_monotonic(timeval_t *tv);
695
696 /**
697 * Add the given number of milliseconds to the given timeval struct
698 *
699 * @param tv timeval struct to modify
700 * @param ms number of milliseconds
701 */
702 static inline void timeval_add_ms(timeval_t *tv, u_int ms)
703 {
704 tv->tv_usec += ms * 1000;
705 while (tv->tv_usec >= 1000000 /* 1s */)
706 {
707 tv->tv_usec -= 1000000;
708 tv->tv_sec++;
709 }
710 }
711
712 /**
713 * returns null
714 */
715 void *return_null();
716
717 /**
718 * No-Operation function
719 */
720 void nop();
721
722 /**
723 * returns TRUE
724 */
725 bool return_true();
726
727 /**
728 * returns FALSE
729 */
730 bool return_false();
731
732 /**
733 * returns FAILED
734 */
735 status_t return_failed();
736
737 /**
738 * returns SUCCESS
739 */
740 status_t return_success();
741
742 /**
743 * Write a 16-bit host order value in network order to an unaligned address.
744 *
745 * @param host host order 16-bit value
746 * @param network unaligned address to write network order value to
747 */
748 static inline void htoun16(void *network, u_int16_t host)
749 {
750 char *unaligned = (char*)network;
751
752 host = htons(host);
753 memcpy(unaligned, &host, sizeof(host));
754 }
755
756 /**
757 * Write a 32-bit host order value in network order to an unaligned address.
758 *
759 * @param host host order 32-bit value
760 * @param network unaligned address to write network order value to
761 */
762 static inline void htoun32(void *network, u_int32_t host)
763 {
764 char *unaligned = (char*)network;
765
766 host = htonl(host);
767 memcpy((char*)unaligned, &host, sizeof(host));
768 }
769
770 /**
771 * Write a 64-bit host order value in network order to an unaligned address.
772 *
773 * @param host host order 64-bit value
774 * @param network unaligned address to write network order value to
775 */
776 static inline void htoun64(void *network, u_int64_t host)
777 {
778 char *unaligned = (char*)network;
779
780 #ifdef be64toh
781 host = htobe64(host);
782 memcpy((char*)unaligned, &host, sizeof(host));
783 #else
784 u_int32_t high_part, low_part;
785
786 high_part = host >> 32;
787 high_part = htonl(high_part);
788 low_part = host & 0xFFFFFFFFLL;
789 low_part = htonl(low_part);
790
791 memcpy(unaligned, &high_part, sizeof(high_part));
792 unaligned += sizeof(high_part);
793 memcpy(unaligned, &low_part, sizeof(low_part));
794 #endif
795 }
796
797 /**
798 * Read a 16-bit value in network order from an unaligned address to host order.
799 *
800 * @param network unaligned address to read network order value from
801 * @return host order value
802 */
803 static inline u_int16_t untoh16(void *network)
804 {
805 char *unaligned = (char*)network;
806 u_int16_t tmp;
807
808 memcpy(&tmp, unaligned, sizeof(tmp));
809 return ntohs(tmp);
810 }
811
812 /**
813 * Read a 32-bit value in network order from an unaligned address to host order.
814 *
815 * @param network unaligned address to read network order value from
816 * @return host order value
817 */
818 static inline u_int32_t untoh32(void *network)
819 {
820 char *unaligned = (char*)network;
821 u_int32_t tmp;
822
823 memcpy(&tmp, unaligned, sizeof(tmp));
824 return ntohl(tmp);
825 }
826
827 /**
828 * Read a 64-bit value in network order from an unaligned address to host order.
829 *
830 * @param network unaligned address to read network order value from
831 * @return host order value
832 */
833 static inline u_int64_t untoh64(void *network)
834 {
835 char *unaligned = (char*)network;
836
837 #ifdef be64toh
838 u_int64_t tmp;
839
840 memcpy(&tmp, unaligned, sizeof(tmp));
841 return be64toh(tmp);
842 #else
843 u_int32_t high_part, low_part;
844
845 memcpy(&high_part, unaligned, sizeof(high_part));
846 unaligned += sizeof(high_part);
847 memcpy(&low_part, unaligned, sizeof(low_part));
848
849 high_part = ntohl(high_part);
850 low_part = ntohl(low_part);
851
852 return (((u_int64_t)high_part) << 32) + low_part;
853 #endif
854 }
855
856 /**
857 * Get the padding required to make size a multiple of alignment
858 */
859 static inline size_t pad_len(size_t size, size_t alignment)
860 {
861 size_t remainder;
862
863 remainder = size % alignment;
864 return remainder ? alignment - remainder : 0;
865 }
866
867 /**
868 * Round up size to be multiple of alignment
869 */
870 static inline size_t round_up(size_t size, size_t alignment)
871 {
872 return size + pad_len(size, alignment);
873 }
874
875 /**
876 * Round down size to be a multiple of alignment
877 */
878 static inline size_t round_down(size_t size, size_t alignment)
879 {
880 return size - (size % alignment);
881 }
882
883 /**
884 * Special type to count references
885 */
886 typedef u_int refcount_t;
887
888 /* use __atomic* built-ins with GCC 4.7 and newer */
889 #ifdef __GNUC__
890 # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 6))
891 # define HAVE_GCC_ATOMIC_OPERATIONS
892 # endif
893 #endif
894
895 #ifdef HAVE_GCC_ATOMIC_OPERATIONS
896
897 #define ref_get(ref) __atomic_add_fetch(ref, 1, __ATOMIC_RELAXED)
898 /* The relaxed memory model works fine for increments as these (usually) don't
899 * change the state of refcounted objects. But here we have to ensure that we
900 * free the right stuff if ref counted objects are mutable. So we have to sync
901 * with other threads that call ref_put(). It would be sufficient to use
902 * __ATOMIC_RELEASE here and then call __atomic_thread_fence() with
903 * __ATOMIC_ACQUIRE if we reach 0, but since we don't have control over the use
904 * of ref_put() we have to make sure. */
905 #define ref_put(ref) (!__atomic_sub_fetch(ref, 1, __ATOMIC_ACQ_REL))
906 #define ref_cur(ref) __atomic_load_n(ref, __ATOMIC_RELAXED)
907
908 #define _cas_impl(ptr, oldval, newval) ({ typeof(oldval) _old = oldval; \
909 __atomic_compare_exchange_n(ptr, &_old, newval, FALSE, \
910 __ATOMIC_SEQ_CST, __ATOMIC_RELAXED); })
911 #define cas_bool(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
912 #define cas_ptr(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
913
914 #elif defined(HAVE_GCC_SYNC_OPERATIONS)
915
916 #define ref_get(ref) __sync_add_and_fetch(ref, 1)
917 #define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
918 #define ref_cur(ref) __sync_fetch_and_add(ref, 0)
919
920 #define cas_bool(ptr, oldval, newval) \
921 (__sync_bool_compare_and_swap(ptr, oldval, newval))
922 #define cas_ptr(ptr, oldval, newval) \
923 (__sync_bool_compare_and_swap(ptr, oldval, newval))
924
925 #else /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
926
927 /**
928 * Get a new reference.
929 *
930 * Increments the reference counter atomically.
931 *
932 * @param ref pointer to ref counter
933 * @return new value of ref
934 */
935 refcount_t ref_get(refcount_t *ref);
936
937 /**
938 * Put back a unused reference.
939 *
940 * Decrements the reference counter atomically and
941 * says if more references available.
942 *
943 * @param ref pointer to ref counter
944 * @return TRUE if no more references counted
945 */
946 bool ref_put(refcount_t *ref);
947
948 /**
949 * Get the current value of the reference counter.
950 *
951 * @param ref pointer to ref counter
952 * @return current value of ref
953 */
954 refcount_t ref_cur(refcount_t *ref);
955
956 /**
957 * Atomically replace value of ptr with newval if it currently equals oldval.
958 *
959 * @param ptr pointer to variable
960 * @param oldval old value of the variable
961 * @param newval new value set if possible
962 * @return TRUE if value equaled oldval and newval was written
963 */
964 bool cas_bool(bool *ptr, bool oldval, bool newval);
965
966 /**
967 * Atomically replace value of ptr with newval if it currently equals oldval.
968 *
969 * @param ptr pointer to variable
970 * @param oldval old value of the variable
971 * @param newval new value set if possible
972 * @return TRUE if value equaled oldval and newval was written
973 */
974 bool cas_ptr(void **ptr, void *oldval, void *newval);
975
976 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
977
978 #ifndef HAVE_FMEMOPEN
979 # ifdef HAVE_FUNOPEN
980 # define HAVE_FMEMOPEN
981 # define HAVE_FMEMOPEN_FALLBACK
982 # include <stdio.h>
983 /**
984 * fmemopen(3) fallback using BSD funopen.
985 *
986 * We could also provide one using fopencookie(), but should we have it we
987 * most likely have fmemopen().
988 *
989 * fseek() is currently not supported.
990 */
991 FILE *fmemopen(void *buf, size_t size, const char *mode);
992 # endif /* FUNOPEN */
993 #endif /* FMEMOPEN */
994
995 /**
996 * printf hook for time_t.
997 *
998 * Arguments are:
999 * time_t* time, bool utc
1000 */
1001 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
1002 const void *const *args);
1003
1004 /**
1005 * printf hook for time_t deltas.
1006 *
1007 * Arguments are:
1008 * time_t* begin, time_t* end
1009 */
1010 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
1011 const void *const *args);
1012
1013 /**
1014 * printf hook for memory areas.
1015 *
1016 * Arguments are:
1017 * u_char *ptr, u_int len
1018 */
1019 int mem_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
1020 const void *const *args);
1021
1022 #endif /** UTILS_H_ @}*/