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