2 * Copyright (C) 2008-2012 Tobias Brunner
3 * Copyright (C) 2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
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>.
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
18 * @defgroup utils_i utils
25 #include <sys/types.h>
29 #include <arpa/inet.h>
35 * strongSwan program return codes
37 #define SS_RC_LIBSTRONGSWAN_INTEGRITY 64
38 #define SS_RC_DAEMON_INTEGRITY 65
39 #define SS_RC_INITIALIZATION_FAILED 66
41 #define SS_RC_FIRST SS_RC_LIBSTRONGSWAN_INTEGRITY
42 #define SS_RC_LAST SS_RC_INITIALIZATION_FAILED
45 * Number of bits in a byte
47 #define BITS_PER_BYTE 8
50 * Default length for various auxiliary text buffers
55 * General purpose boolean type.
61 # define _Bool signed char
62 # endif /* HAVE__BOOL */
66 # define __bool_true_false_are_defined 1
67 #endif /* HAVE_STDBOOL_H */
76 * Helper function that compares two strings for equality
78 static inline bool streq(const char *x
, const char *y
)
80 return strcmp(x
, y
) == 0;
84 * Helper function that compares two strings for equality, length limited
86 static inline bool strneq(const char *x
, const char *y
, size_t len
)
88 return strncmp(x
, y
, len
) == 0;
92 * Helper function that checks if a string starts with a given prefix
94 static inline bool strpfx(const char *x
, const char *prefix
)
96 return strneq(x
, prefix
, strlen(prefix
));
100 * Helper function that compares two strings for equality ignoring case
102 static inline bool strcaseeq(const char *x
, const char *y
)
104 return strcasecmp(x
, y
) == 0;
108 * Helper function that compares two strings for equality ignoring case, length limited
110 static inline bool strncaseeq(const char *x
, const char *y
, size_t len
)
112 return strncasecmp(x
, y
, len
) == 0;
116 * Helper function that checks if a string starts with a given prefix
118 static inline bool strcasepfx(const char *x
, const char *prefix
)
120 return strncaseeq(x
, prefix
, strlen(prefix
));
124 * NULL-safe strdup variant
126 static inline char *strdupnull(const char *s
)
128 return s ?
strdup(s
) : NULL
;
132 * Helper function that compares two binary blobs for equality
134 static inline bool memeq(const void *x
, const void *y
, size_t len
)
136 return memcmp(x
, y
, len
) == 0;
140 * Macro gives back larger of two values.
142 #define max(x,y) ({ \
143 typeof(x) _x = (x); \
144 typeof(y) _y = (y); \
145 _x > _y ? _x : _y; })
149 * Macro gives back smaller of two values.
151 #define min(x,y) ({ \
152 typeof(x) _x = (x); \
153 typeof(y) _y = (y); \
154 _x < _y ? _x : _y; })
157 * Call destructor of an object, if object != NULL
159 #define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
162 * Call offset destructor of an object, if object != NULL
164 #define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
167 * Call function destructor of an object, if object != NULL
169 #define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
172 * Debug macro to follow control flow
174 #define POS printf("%s, line %d\n", __FILE__, __LINE__)
177 * Object allocation/initialization macro, using designated initializer.
179 #define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \
180 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
183 * Method declaration/definition macro, providing private and public interface.
185 * Defines a method name with this as first parameter and a return value ret,
186 * and an alias for this method with a _ prefix, having the this argument
187 * safely casted to the public interface iface.
188 * _name is provided a function pointer, but will get optimized out by GCC.
190 #define METHOD(iface, name, ret, this, ...) \
191 static ret name(union {iface *_public; this;} \
192 __attribute__((transparent_union)), ##__VA_ARGS__); \
193 static typeof(name) *_##name = (typeof(name)*)name; \
194 static ret name(this, ##__VA_ARGS__)
197 * Same as METHOD(), but is defined for two public interfaces.
199 #define METHOD2(iface1, iface2, name, ret, this, ...) \
200 static ret name(union {iface1 *_public1; iface2 *_public2; this;} \
201 __attribute__((transparent_union)), ##__VA_ARGS__); \
202 static typeof(name) *_##name = (typeof(name)*)name; \
203 static ret name(this, ##__VA_ARGS__)
206 * Architecture independent bitfield definition helpers (at least with GCC).
208 * Defines a bitfield with a type t and a fixed size of bitfield members, e.g.:
209 * BITFIELD2(u_int8_t,
213 * The member defined first placed at bit 0.
215 #if BYTE_ORDER == LITTLE_ENDIAN
216 #define BITFIELD2(t, a, b,...) struct { t a; t b; __VA_ARGS__}
217 #define BITFIELD3(t, a, b, c,...) struct { t a; t b; t c; __VA_ARGS__}
218 #define BITFIELD4(t, a, b, c, d,...) struct { t a; t b; t c; t d; __VA_ARGS__}
219 #define BITFIELD5(t, a, b, c, d, e,...) struct { t a; t b; t c; t d; t e; __VA_ARGS__}
220 #elif BYTE_ORDER == BIG_ENDIAN
221 #define BITFIELD2(t, a, b,...) struct { t b; t a; __VA_ARGS__}
222 #define BITFIELD3(t, a, b, c,...) struct { t c; t b; t a; __VA_ARGS__}
223 #define BITFIELD4(t, a, b, c, d,...) struct { t d; t c; t b; t a; __VA_ARGS__}
224 #define BITFIELD5(t, a, b, c, d, e,...) struct { t e; t d; t c; t b; t a; __VA_ARGS__}
228 * Macro to allocate a sized type.
230 #define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
233 * Get the number of elements in an array
235 #define countof(array) (sizeof(array)/sizeof(array[0]))
238 * Ignore result of functions tagged with warn_unused_result attributes
240 #define ignore_result(call) { if(call){}; }
243 * Assign a function as a class method
245 #define ASSIGN(method, function) (method = (typeof(method))function)
250 #define UNDEFINED_TIME 0
253 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
255 #define TIME_32_BIT_SIGNED_MAX 0x7fffffff
258 * define some missing fixed width int types on OpenSolaris.
259 * TODO: since the uintXX_t types are defined by the C99 standard we should
260 * probably use those anyway
264 typedef uint8_t u_int8_t
;
265 typedef uint16_t u_int16_t
;
266 typedef uint32_t u_int32_t
;
267 typedef uint64_t u_int64_t
;
270 typedef enum status_t status_t
;
273 * Return values of function calls.
292 * The suggested operation is already done
302 * One of the arguments is invalid.
307 * Something could not be found.
312 * Error while parsing.
317 * Error while verifying.
322 * Object in invalid state.
327 * Destroy object which called method belongs to.
332 * Another call to the method is required.
338 * enum_names for type status_t.
340 extern enum_name_t
*status_names
;
342 typedef enum tty_escape_t tty_escape_t
;
345 * Excape codes for tty colors
348 /** text properties */
354 /** foreground colors */
365 /** background colors */
378 * Get the escape string for a given TTY color, empty string on non-tty fd
380 char* tty_escape_get(int fd
, tty_escape_t escape
);
383 * deprecated pluto style return value:
384 * error message, NULL for success
386 typedef const char *err_t
;
389 * Handle struct timeval like an own type.
391 typedef struct timeval timeval_t
;
394 * Handle struct timespec like an own type.
396 typedef struct timespec timespec_t
;
399 * Handle struct chunk_t like an own type.
401 typedef struct sockaddr sockaddr_t
;
404 * Same as memcpy, but XORs src into dst instead of copy
406 void memxor(u_int8_t dest
[], u_int8_t src
[], size_t n
);
409 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
411 void memwipe_noinline(void *ptr
, size_t n
);
414 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
416 static inline void memwipe_inline(void *ptr
, size_t n
)
418 volatile char *c
= (volatile char*)ptr
;
421 /* byte wise until long aligned */
422 for (i
= 0; (uintptr_t)&c
[i
] % sizeof(long) && i
< n
; i
++)
427 if (n
>= sizeof(long))
429 for (m
= n
- sizeof(long); i
<= m
; i
+= sizeof(long))
431 *(volatile long*)&c
[i
] = 0;
434 /* byte wise of the rest */
442 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
444 static inline void memwipe(void *ptr
, size_t n
)
450 if (__builtin_constant_p(n
))
452 memwipe_inline(ptr
, n
);
456 memwipe_noinline(ptr
, n
);
461 * A variant of strstr with the characteristics of memchr, where haystack is not
462 * a null-terminated string but simply a memory area of length n.
464 void *memstr(const void *haystack
, const char *needle
, size_t n
);
467 * Translates the characters in the given string, searching for characters
468 * in 'from' and mapping them to characters in 'to'.
469 * The two characters sets 'from' and 'to' must contain the same number of
472 char *translate(char *str
, const char *from
, const char *to
);
475 * Creates a directory and all required parent directories.
477 * @param path path to the new directory
478 * @param mode permissions of the new directory/directories
479 * @return TRUE on success
481 bool mkdir_p(const char *path
, mode_t mode
);
484 * Thread-safe wrapper around strerror and strerror_r.
486 * This is required because the first is not thread-safe (on some platforms)
487 * and the second uses two different signatures (POSIX/GNU) and is impractical
490 * @param errnum error code (i.e. errno)
491 * @return error message
493 const char *safe_strerror(int errnum
);
496 * Replace usages of strerror(3) with thread-safe variant.
498 #define strerror(errnum) safe_strerror(errnum)
500 #ifndef HAVE_CLOSEFROM
502 * Close open file descriptors greater than or equal to lowfd.
504 * @param lowfd start closing file descriptoros from here
506 void closefrom(int lowfd
);
510 * Get a timestamp from a monotonic time source.
512 * While the time()/gettimeofday() functions are affected by leap seconds
513 * and system time changes, this function returns ever increasing monotonic
516 * @param tv timeval struct receiving monotonic timestamps, or NULL
517 * @return monotonic timestamp in seconds
519 time_t time_monotonic(timeval_t
*tv
);
522 * Add the given number of milliseconds to the given timeval struct
524 * @param tv timeval struct to modify
525 * @param ms number of milliseconds
527 static inline void timeval_add_ms(timeval_t
*tv
, u_int ms
)
529 tv
->tv_usec
+= ms
* 1000;
530 while (tv
->tv_usec
>= 1000000 /* 1s */)
532 tv
->tv_usec
-= 1000000;
543 * No-Operation function
560 status_t
return_failed();
565 status_t
return_success();
568 * Write a 16-bit host order value in network order to an unaligned address.
570 * @param host host order 16-bit value
571 * @param network unaligned address to write network order value to
573 static inline void htoun16(void *network
, u_int16_t host
)
575 char *unaligned
= (char*)network
;
578 memcpy(unaligned
, &host
, sizeof(host
));
582 * Write a 32-bit host order value in network order to an unaligned address.
584 * @param host host order 32-bit value
585 * @param network unaligned address to write network order value to
587 static inline void htoun32(void *network
, u_int32_t host
)
589 char *unaligned
= (char*)network
;
592 memcpy((char*)unaligned
, &host
, sizeof(host
));
596 * Write a 64-bit host order value in network order to an unaligned address.
598 * @param host host order 64-bit value
599 * @param network unaligned address to write network order value to
601 static inline void htoun64(void *network
, u_int64_t host
)
603 char *unaligned
= (char*)network
;
606 host
= htobe64(host
);
607 memcpy((char*)unaligned
, &host
, sizeof(host
));
609 u_int32_t high_part
, low_part
;
611 high_part
= host
>> 32;
612 high_part
= htonl(high_part
);
613 low_part
= host
& 0xFFFFFFFFLL
;
614 low_part
= htonl(low_part
);
616 memcpy(unaligned
, &high_part
, sizeof(high_part
));
617 unaligned
+= sizeof(high_part
);
618 memcpy(unaligned
, &low_part
, sizeof(low_part
));
623 * Read a 16-bit value in network order from an unaligned address to host order.
625 * @param network unaligned address to read network order value from
626 * @return host order value
628 static inline u_int16_t
untoh16(void *network
)
630 char *unaligned
= (char*)network
;
633 memcpy(&tmp
, unaligned
, sizeof(tmp
));
638 * Read a 32-bit value in network order from an unaligned address to host order.
640 * @param network unaligned address to read network order value from
641 * @return host order value
643 static inline u_int32_t
untoh32(void *network
)
645 char *unaligned
= (char*)network
;
648 memcpy(&tmp
, unaligned
, sizeof(tmp
));
653 * Read a 64-bit value in network order from an unaligned address to host order.
655 * @param network unaligned address to read network order value from
656 * @return host order value
658 static inline u_int64_t
untoh64(void *network
)
660 char *unaligned
= (char*)network
;
665 memcpy(&tmp
, unaligned
, sizeof(tmp
));
668 u_int32_t high_part
, low_part
;
670 memcpy(&high_part
, unaligned
, sizeof(high_part
));
671 unaligned
+= sizeof(high_part
);
672 memcpy(&low_part
, unaligned
, sizeof(low_part
));
674 high_part
= ntohl(high_part
);
675 low_part
= ntohl(low_part
);
677 return (((u_int64_t
)high_part
) << 32) + low_part
;
682 * Get the padding required to make size a multiple of alignment
684 static inline size_t pad_len(size_t size
, size_t alignment
)
688 remainder
= size
% alignment
;
689 return remainder ? alignment
- remainder
: 0;
693 * Round up size to be multiple of alignment
695 static inline size_t round_up(size_t size
, size_t alignment
)
697 return size
+ pad_len(size
, alignment
);
701 * Round down size to be a multiple of alignment
703 static inline size_t round_down(size_t size
, size_t alignment
)
705 return size
- (size
% alignment
);
709 * Special type to count references
711 typedef u_int refcount_t
;
713 #ifdef HAVE_GCC_ATOMIC_OPERATIONS
715 #define ref_get(ref) __sync_add_and_fetch(ref, 1)
716 #define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
718 #define cas_bool(ptr, oldval, newval) \
719 (__sync_bool_compare_and_swap(ptr, oldval, newval))
720 #define cas_ptr(ptr, oldval, newval) \
721 (__sync_bool_compare_and_swap(ptr, oldval, newval))
723 #else /* !HAVE_GCC_ATOMIC_OPERATIONS */
726 * Get a new reference.
728 * Increments the reference counter atomic.
730 * @param ref pointer to ref counter
731 * @return new value of ref
733 refcount_t
ref_get(refcount_t
*ref
);
736 * Put back a unused reference.
738 * Decrements the reference counter atomic and
739 * says if more references available.
741 * @param ref pointer to ref counter
742 * @return TRUE if no more references counted
744 bool ref_put(refcount_t
*ref
);
747 * Atomically replace value of ptr with newval if it currently equals oldval.
749 * @param ptr pointer to variable
750 * @param oldval old value of the variable
751 * @param newval new value set if possible
752 * @return TRUE if value equaled oldval and newval was written
754 bool cas_bool(bool *ptr
, bool oldval
, bool newval
);
757 * Atomically replace value of ptr with newval if it currently equals oldval.
759 * @param ptr pointer to variable
760 * @param oldval old value of the variable
761 * @param newval new value set if possible
762 * @return TRUE if value equaled oldval and newval was written
764 bool cas_ptr(void **ptr
, void *oldval
, void *newval
);
766 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
768 #ifndef HAVE_FMEMOPEN
770 # define HAVE_FMEMOPEN fallback
772 * fmemopen(3) fallback using BSD funopen.
774 * We could also provide one using fopencookie(), but should we have it we
775 * most likely have fmemopen().
777 * fseek() is currently not supported.
779 FILE *fmemopen(void *buf
, size_t size
, const char *mode
);
780 # endif /* FUNOPEN */
781 #endif /* FMEMOPEN */
784 * printf hook for time_t.
787 * time_t* time, bool utc
789 int time_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
790 const void *const *args
);
793 * printf hook for time_t deltas.
796 * time_t* begin, time_t* end
798 int time_delta_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
799 const void *const *args
);
802 * printf hook for memory areas.
805 * u_char *ptr, u_int len
807 int mem_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
808 const void *const *args
);
810 #endif /** UTILS_H_ @}*/