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