d055f712d50447be9cf8570593f64101cb57e5e6
[strongswan.git] / src / libstrongswan / utils / utils.h
1 /*
2 * Copyright (C) 2008-2012 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 <arpa/inet.h>
30 #include <string.h>
31
32 #include "enum.h"
33
34 /**
35 * strongSwan program return codes
36 */
37 #define SS_RC_LIBSTRONGSWAN_INTEGRITY 64
38 #define SS_RC_DAEMON_INTEGRITY 65
39 #define SS_RC_INITIALIZATION_FAILED 66
40
41 #define SS_RC_FIRST SS_RC_LIBSTRONGSWAN_INTEGRITY
42 #define SS_RC_LAST SS_RC_INITIALIZATION_FAILED
43
44 /**
45 * Number of bits in a byte
46 */
47 #define BITS_PER_BYTE 8
48
49 /**
50 * Default length for various auxiliary text buffers
51 */
52 #define BUF_LEN 512
53
54 /**
55 * General purpose boolean type.
56 */
57 #ifdef HAVE_STDBOOL_H
58 # include <stdbool.h>
59 #else
60 # ifndef HAVE__BOOL
61 # define _Bool signed char
62 # endif /* HAVE__BOOL */
63 # define bool _Bool
64 # define false 0
65 # define true 1
66 # define __bool_true_false_are_defined 1
67 #endif /* HAVE_STDBOOL_H */
68 #ifndef FALSE
69 # define FALSE false
70 #endif /* FALSE */
71 #ifndef TRUE
72 # define TRUE true
73 #endif /* TRUE */
74
75 /**
76 * Helper function that compares two strings for equality
77 */
78 static inline bool streq(const char *x, const char *y)
79 {
80 return strcmp(x, y) == 0;
81 }
82
83 /**
84 * Helper function that compares two strings for equality, length limited
85 */
86 static inline bool strneq(const char *x, const char *y, size_t len)
87 {
88 return strncmp(x, y, len) == 0;
89 }
90
91 /**
92 * Helper function that checks if a string starts with a given prefix
93 */
94 static inline bool strpfx(const char *x, const char *prefix)
95 {
96 return strneq(x, prefix, strlen(prefix));
97 }
98
99 /**
100 * Helper function that compares two strings for equality ignoring case
101 */
102 static inline bool strcaseeq(const char *x, const char *y)
103 {
104 return strcasecmp(x, y) == 0;
105 }
106
107 /**
108 * Helper function that compares two strings for equality ignoring case, length limited
109 */
110 static inline bool strncaseeq(const char *x, const char *y, size_t len)
111 {
112 return strncasecmp(x, y, len) == 0;
113 }
114
115 /**
116 * NULL-safe strdup variant
117 */
118 static inline char *strdupnull(const char *s)
119 {
120 return s ? strdup(s) : NULL;
121 }
122
123 /**
124 * Helper function that compares two binary blobs for equality
125 */
126 static inline bool memeq(const void *x, const void *y, size_t len)
127 {
128 return memcmp(x, y, len) == 0;
129 }
130
131 /**
132 * Macro gives back larger of two values.
133 */
134 #define max(x,y) ({ \
135 typeof(x) _x = (x); \
136 typeof(y) _y = (y); \
137 _x > _y ? _x : _y; })
138
139
140 /**
141 * Macro gives back smaller of two values.
142 */
143 #define min(x,y) ({ \
144 typeof(x) _x = (x); \
145 typeof(y) _y = (y); \
146 _x < _y ? _x : _y; })
147
148 /**
149 * Call destructor of an object, if object != NULL
150 */
151 #define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
152
153 /**
154 * Call offset destructor of an object, if object != NULL
155 */
156 #define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
157
158 /**
159 * Call function destructor of an object, if object != NULL
160 */
161 #define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
162
163 /**
164 * Debug macro to follow control flow
165 */
166 #define POS printf("%s, line %d\n", __FILE__, __LINE__)
167
168 /**
169 * Object allocation/initialization macro, using designated initializer.
170 */
171 #define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \
172 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
173
174 /**
175 * Method declaration/definition macro, providing private and public interface.
176 *
177 * Defines a method name with this as first parameter and a return value ret,
178 * and an alias for this method with a _ prefix, having the this argument
179 * safely casted to the public interface iface.
180 * _name is provided a function pointer, but will get optimized out by GCC.
181 */
182 #define METHOD(iface, name, ret, this, ...) \
183 static ret name(union {iface *_public; this;} \
184 __attribute__((transparent_union)), ##__VA_ARGS__); \
185 static typeof(name) *_##name = (typeof(name)*)name; \
186 static ret name(this, ##__VA_ARGS__)
187
188 /**
189 * Same as METHOD(), but is defined for two public interfaces.
190 */
191 #define METHOD2(iface1, iface2, name, ret, this, ...) \
192 static ret name(union {iface1 *_public1; iface2 *_public2; this;} \
193 __attribute__((transparent_union)), ##__VA_ARGS__); \
194 static typeof(name) *_##name = (typeof(name)*)name; \
195 static ret name(this, ##__VA_ARGS__)
196
197 /**
198 * Architecture independent bitfield definition helpers (at least with GCC).
199 *
200 * Defines a bitfield with a type t and a fixed size of bitfield members, e.g.:
201 * BITFIELD2(u_int8_t,
202 * low: 4,
203 * high: 4,
204 * ) flags;
205 * The member defined first placed at bit 0.
206 */
207 #if BYTE_ORDER == LITTLE_ENDIAN
208 #define BITFIELD2(t, a, b,...) struct { t a; t b; __VA_ARGS__}
209 #define BITFIELD3(t, a, b, c,...) struct { t a; t b; t c; __VA_ARGS__}
210 #define BITFIELD4(t, a, b, c, d,...) struct { t a; t b; t c; t d; __VA_ARGS__}
211 #define BITFIELD5(t, a, b, c, d, e,...) struct { t a; t b; t c; t d; t e; __VA_ARGS__}
212 #elif BYTE_ORDER == BIG_ENDIAN
213 #define BITFIELD2(t, a, b,...) struct { t b; t a; __VA_ARGS__}
214 #define BITFIELD3(t, a, b, c,...) struct { t c; t b; t a; __VA_ARGS__}
215 #define BITFIELD4(t, a, b, c, d,...) struct { t d; t c; t b; t a; __VA_ARGS__}
216 #define BITFIELD5(t, a, b, c, d, e,...) struct { t e; t d; t c; t b; t a; __VA_ARGS__}
217 #endif
218
219 /**
220 * Macro to allocate a sized type.
221 */
222 #define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
223
224 /**
225 * Get the number of elements in an array
226 */
227 #define countof(array) (sizeof(array)/sizeof(array[0]))
228
229 /**
230 * Ignore result of functions tagged with warn_unused_result attributes
231 */
232 #define ignore_result(call) { if(call){}; }
233
234 /**
235 * Assign a function as a class method
236 */
237 #define ASSIGN(method, function) (method = (typeof(method))function)
238
239 /**
240 * time_t not defined
241 */
242 #define UNDEFINED_TIME 0
243
244 /**
245 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
246 */
247 #define TIME_32_BIT_SIGNED_MAX 0x7fffffff
248
249 /**
250 * define some missing fixed width int types on OpenSolaris.
251 * TODO: since the uintXX_t types are defined by the C99 standard we should
252 * probably use those anyway
253 */
254 #ifdef __sun
255 #include <stdint.h>
256 typedef uint8_t u_int8_t;
257 typedef uint16_t u_int16_t;
258 typedef uint32_t u_int32_t;
259 typedef uint64_t u_int64_t;
260 #endif
261
262 typedef enum status_t status_t;
263
264 /**
265 * Return values of function calls.
266 */
267 enum status_t {
268 /**
269 * Call succeeded.
270 */
271 SUCCESS,
272
273 /**
274 * Call failed.
275 */
276 FAILED,
277
278 /**
279 * Out of resources.
280 */
281 OUT_OF_RES,
282
283 /**
284 * The suggested operation is already done
285 */
286 ALREADY_DONE,
287
288 /**
289 * Not supported.
290 */
291 NOT_SUPPORTED,
292
293 /**
294 * One of the arguments is invalid.
295 */
296 INVALID_ARG,
297
298 /**
299 * Something could not be found.
300 */
301 NOT_FOUND,
302
303 /**
304 * Error while parsing.
305 */
306 PARSE_ERROR,
307
308 /**
309 * Error while verifying.
310 */
311 VERIFY_ERROR,
312
313 /**
314 * Object in invalid state.
315 */
316 INVALID_STATE,
317
318 /**
319 * Destroy object which called method belongs to.
320 */
321 DESTROY_ME,
322
323 /**
324 * Another call to the method is required.
325 */
326 NEED_MORE,
327 };
328
329 /**
330 * enum_names for type status_t.
331 */
332 extern enum_name_t *status_names;
333
334 typedef enum tty_escape_t tty_escape_t;
335
336 /**
337 * Excape codes for tty colors
338 */
339 enum tty_escape_t {
340 /** text properties */
341 TTY_RESET,
342 TTY_BOLD,
343 TTY_UNDERLINE,
344 TTY_BLINKING,
345
346 /** foreground colors */
347 TTY_FG_BLACK,
348 TTY_FG_RED,
349 TTY_FG_GREEN,
350 TTY_FG_YELLOW,
351 TTY_FG_BLUE,
352 TTY_FG_MAGENTA,
353 TTY_FG_CYAN,
354 TTY_FG_WHITE,
355 TTY_FG_DEF,
356
357 /** background colors */
358 TTY_BG_BLACK,
359 TTY_BG_RED,
360 TTY_BG_GREEN,
361 TTY_BG_YELLOW,
362 TTY_BG_BLUE,
363 TTY_BG_MAGENTA,
364 TTY_BG_CYAN,
365 TTY_BG_WHITE,
366 TTY_BG_DEF,
367 };
368
369 /**
370 * Get the escape string for a given TTY color, empty string on non-tty fd
371 */
372 char* tty_escape_get(int fd, tty_escape_t escape);
373
374 /**
375 * deprecated pluto style return value:
376 * error message, NULL for success
377 */
378 typedef const char *err_t;
379
380 /**
381 * Handle struct timeval like an own type.
382 */
383 typedef struct timeval timeval_t;
384
385 /**
386 * Handle struct timespec like an own type.
387 */
388 typedef struct timespec timespec_t;
389
390 /**
391 * Handle struct chunk_t like an own type.
392 */
393 typedef struct sockaddr sockaddr_t;
394
395 /**
396 * Same as memcpy, but XORs src into dst instead of copy
397 */
398 void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
399
400 /**
401 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
402 */
403 void memwipe_noinline(void *ptr, size_t n);
404
405 /**
406 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
407 */
408 static inline void memwipe_inline(void *ptr, size_t n)
409 {
410 volatile char *c = (volatile char*)ptr;
411 size_t m, i;
412
413 /* byte wise until long aligned */
414 for (i = 0; (uintptr_t)&c[i] % sizeof(long) && i < n; i++)
415 {
416 c[i] = 0;
417 }
418 /* word wise */
419 if (n >= sizeof(long))
420 {
421 for (m = n - sizeof(long); i <= m; i += sizeof(long))
422 {
423 *(volatile long*)&c[i] = 0;
424 }
425 }
426 /* byte wise of the rest */
427 for (; i < n; i++)
428 {
429 c[i] = 0;
430 }
431 }
432
433 /**
434 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
435 */
436 static inline void memwipe(void *ptr, size_t n)
437 {
438 if (!ptr)
439 {
440 return;
441 }
442 if (__builtin_constant_p(n))
443 {
444 memwipe_inline(ptr, n);
445 }
446 else
447 {
448 memwipe_noinline(ptr, n);
449 }
450 }
451
452 /**
453 * A variant of strstr with the characteristics of memchr, where haystack is not
454 * a null-terminated string but simply a memory area of length n.
455 */
456 void *memstr(const void *haystack, const char *needle, size_t n);
457
458 /**
459 * Translates the characters in the given string, searching for characters
460 * in 'from' and mapping them to characters in 'to'.
461 * The two characters sets 'from' and 'to' must contain the same number of
462 * characters.
463 */
464 char *translate(char *str, const char *from, const char *to);
465
466 /**
467 * Creates a directory and all required parent directories.
468 *
469 * @param path path to the new directory
470 * @param mode permissions of the new directory/directories
471 * @return TRUE on success
472 */
473 bool mkdir_p(const char *path, mode_t mode);
474
475 /**
476 * Thread-safe wrapper around strerror and strerror_r.
477 *
478 * This is required because the first is not thread-safe (on some platforms)
479 * and the second uses two different signatures (POSIX/GNU) and is impractical
480 * to use anyway.
481 *
482 * @param errnum error code (i.e. errno)
483 * @return error message
484 */
485 const char *safe_strerror(int errnum);
486
487 /**
488 * Replace usages of strerror(3) with thread-safe variant.
489 */
490 #define strerror(errnum) safe_strerror(errnum)
491
492 #ifndef HAVE_CLOSEFROM
493 /**
494 * Close open file descriptors greater than or equal to lowfd.
495 *
496 * @param lowfd start closing file descriptoros from here
497 */
498 void closefrom(int lowfd);
499 #endif
500
501 /**
502 * Get a timestamp from a monotonic time source.
503 *
504 * While the time()/gettimeofday() functions are affected by leap seconds
505 * and system time changes, this function returns ever increasing monotonic
506 * time stamps.
507 *
508 * @param tv timeval struct receiving monotonic timestamps, or NULL
509 * @return monotonic timestamp in seconds
510 */
511 time_t time_monotonic(timeval_t *tv);
512
513 /**
514 * Add the given number of milliseconds to the given timeval struct
515 *
516 * @param tv timeval struct to modify
517 * @param ms number of milliseconds
518 */
519 static inline void timeval_add_ms(timeval_t *tv, u_int ms)
520 {
521 tv->tv_usec += ms * 1000;
522 while (tv->tv_usec >= 1000000 /* 1s */)
523 {
524 tv->tv_usec -= 1000000;
525 tv->tv_sec++;
526 }
527 }
528
529 /**
530 * returns null
531 */
532 void *return_null();
533
534 /**
535 * No-Operation function
536 */
537 void nop();
538
539 /**
540 * returns TRUE
541 */
542 bool return_true();
543
544 /**
545 * returns FALSE
546 */
547 bool return_false();
548
549 /**
550 * returns FAILED
551 */
552 status_t return_failed();
553
554 /**
555 * returns SUCCESS
556 */
557 status_t return_success();
558
559 /**
560 * Write a 16-bit host order value in network order to an unaligned address.
561 *
562 * @param host host order 16-bit value
563 * @param network unaligned address to write network order value to
564 */
565 static inline void htoun16(void *network, u_int16_t host)
566 {
567 char *unaligned = (char*)network;
568
569 host = htons(host);
570 memcpy(unaligned, &host, sizeof(host));
571 }
572
573 /**
574 * Write a 32-bit host order value in network order to an unaligned address.
575 *
576 * @param host host order 32-bit value
577 * @param network unaligned address to write network order value to
578 */
579 static inline void htoun32(void *network, u_int32_t host)
580 {
581 char *unaligned = (char*)network;
582
583 host = htonl(host);
584 memcpy((char*)unaligned, &host, sizeof(host));
585 }
586
587 /**
588 * Write a 64-bit host order value in network order to an unaligned address.
589 *
590 * @param host host order 64-bit value
591 * @param network unaligned address to write network order value to
592 */
593 static inline void htoun64(void *network, u_int64_t host)
594 {
595 char *unaligned = (char*)network;
596
597 #ifdef be64toh
598 host = htobe64(host);
599 memcpy((char*)unaligned, &host, sizeof(host));
600 #else
601 u_int32_t high_part, low_part;
602
603 high_part = host >> 32;
604 high_part = htonl(high_part);
605 low_part = host & 0xFFFFFFFFLL;
606 low_part = htonl(low_part);
607
608 memcpy(unaligned, &high_part, sizeof(high_part));
609 unaligned += sizeof(high_part);
610 memcpy(unaligned, &low_part, sizeof(low_part));
611 #endif
612 }
613
614 /**
615 * Read a 16-bit value in network order from an unaligned address to host order.
616 *
617 * @param network unaligned address to read network order value from
618 * @return host order value
619 */
620 static inline u_int16_t untoh16(void *network)
621 {
622 char *unaligned = (char*)network;
623 u_int16_t tmp;
624
625 memcpy(&tmp, unaligned, sizeof(tmp));
626 return ntohs(tmp);
627 }
628
629 /**
630 * Read a 32-bit value in network order from an unaligned address to host order.
631 *
632 * @param network unaligned address to read network order value from
633 * @return host order value
634 */
635 static inline u_int32_t untoh32(void *network)
636 {
637 char *unaligned = (char*)network;
638 u_int32_t tmp;
639
640 memcpy(&tmp, unaligned, sizeof(tmp));
641 return ntohl(tmp);
642 }
643
644 /**
645 * Read a 64-bit value in network order from an unaligned address to host order.
646 *
647 * @param network unaligned address to read network order value from
648 * @return host order value
649 */
650 static inline u_int64_t untoh64(void *network)
651 {
652 char *unaligned = (char*)network;
653
654 #ifdef be64toh
655 u_int64_t tmp;
656
657 memcpy(&tmp, unaligned, sizeof(tmp));
658 return be64toh(tmp);
659 #else
660 u_int32_t high_part, low_part;
661
662 memcpy(&high_part, unaligned, sizeof(high_part));
663 unaligned += sizeof(high_part);
664 memcpy(&low_part, unaligned, sizeof(low_part));
665
666 high_part = ntohl(high_part);
667 low_part = ntohl(low_part);
668
669 return (((u_int64_t)high_part) << 32) + low_part;
670 #endif
671 }
672
673 /**
674 * Round up size to be multiple of alignement
675 */
676 static inline size_t round_up(size_t size, int alignement)
677 {
678 int remainder;
679
680 remainder = size % alignement;
681 if (remainder)
682 {
683 size += alignement - remainder;
684 }
685 return size;
686 }
687
688 /**
689 * Round down size to be a multiple of alignement
690 */
691 static inline size_t round_down(size_t size, int alignement)
692 {
693 return size - (size % alignement);
694 }
695
696 /**
697 * Special type to count references
698 */
699 typedef u_int refcount_t;
700
701 #ifdef HAVE_GCC_ATOMIC_OPERATIONS
702
703 #define ref_get(ref) __sync_add_and_fetch(ref, 1)
704 #define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
705
706 #define cas_bool(ptr, oldval, newval) \
707 (__sync_bool_compare_and_swap(ptr, oldval, newval))
708 #define cas_ptr(ptr, oldval, newval) \
709 (__sync_bool_compare_and_swap(ptr, oldval, newval))
710
711 #else /* !HAVE_GCC_ATOMIC_OPERATIONS */
712
713 /**
714 * Get a new reference.
715 *
716 * Increments the reference counter atomic.
717 *
718 * @param ref pointer to ref counter
719 * @return new value of ref
720 */
721 refcount_t ref_get(refcount_t *ref);
722
723 /**
724 * Put back a unused reference.
725 *
726 * Decrements the reference counter atomic and
727 * says if more references available.
728 *
729 * @param ref pointer to ref counter
730 * @return TRUE if no more references counted
731 */
732 bool ref_put(refcount_t *ref);
733
734 /**
735 * Atomically replace value of ptr with newval if it currently equals oldval.
736 *
737 * @param ptr pointer to variable
738 * @param oldval old value of the variable
739 * @param newval new value set if possible
740 * @return TRUE if value equaled oldval and newval was written
741 */
742 bool cas_bool(bool *ptr, bool oldval, bool newval);
743
744 /**
745 * Atomically replace value of ptr with newval if it currently equals oldval.
746 *
747 * @param ptr pointer to variable
748 * @param oldval old value of the variable
749 * @param newval new value set if possible
750 * @return TRUE if value equaled oldval and newval was written
751 */
752 bool cas_ptr(void **ptr, void *oldval, void *newval);
753
754 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
755
756 /**
757 * printf hook for time_t.
758 *
759 * Arguments are:
760 * time_t* time, bool utc
761 */
762 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
763 const void *const *args);
764
765 /**
766 * printf hook for time_t deltas.
767 *
768 * Arguments are:
769 * time_t* begin, time_t* end
770 */
771 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
772 const void *const *args);
773
774 /**
775 * printf hook for memory areas.
776 *
777 * Arguments are:
778 * u_char *ptr, u_int len
779 */
780 int mem_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
781 const void *const *args);
782
783 #endif /** UTILS_H_ @}*/