5cd0a34b12e8c7c7fbfe45b2b65e77517f60ea12
[strongswan.git] / src / libstrongswan / utils / utils.h
1 /*
2 * Copyright (C) 2008-2013 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 * Helper function that checks if a string starts with a given prefix
117 */
118 static inline bool strcasepfx(const char *x, const char *prefix)
119 {
120 return strncaseeq(x, prefix, strlen(prefix));
121 }
122
123 /**
124 * NULL-safe strdup variant
125 */
126 static inline char *strdupnull(const char *s)
127 {
128 return s ? strdup(s) : NULL;
129 }
130
131 /**
132 * Helper function that compares two binary blobs for equality
133 */
134 static inline bool memeq(const void *x, const void *y, size_t len)
135 {
136 return memcmp(x, y, len) == 0;
137 }
138
139 /**
140 * Macro gives back larger of two values.
141 */
142 #define max(x,y) ({ \
143 typeof(x) _x = (x); \
144 typeof(y) _y = (y); \
145 _x > _y ? _x : _y; })
146
147
148 /**
149 * Macro gives back smaller of two values.
150 */
151 #define min(x,y) ({ \
152 typeof(x) _x = (x); \
153 typeof(y) _y = (y); \
154 _x < _y ? _x : _y; })
155
156 /**
157 * Call destructor of an object, if object != NULL
158 */
159 #define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
160
161 /**
162 * Call offset destructor of an object, if object != NULL
163 */
164 #define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
165
166 /**
167 * Call function destructor of an object, if object != NULL
168 */
169 #define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
170
171 /**
172 * Debug macro to follow control flow
173 */
174 #define POS printf("%s, line %d\n", __FILE__, __LINE__)
175
176 /**
177 * Object allocation/initialization macro, using designated initializer.
178 */
179 #define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \
180 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
181
182 /**
183 * Method declaration/definition macro, providing private and public interface.
184 *
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.
189 */
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__)
195
196 /**
197 * Same as METHOD(), but is defined for two public interfaces.
198 */
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__)
204
205 /**
206 * Architecture independent bitfield definition helpers (at least with GCC).
207 *
208 * Defines a bitfield with a type t and a fixed size of bitfield members, e.g.:
209 * BITFIELD2(u_int8_t,
210 * low: 4,
211 * high: 4,
212 * ) flags;
213 * The member defined first placed at bit 0.
214 */
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__}
225 #endif
226
227 /**
228 * Macro to allocate a sized type.
229 */
230 #define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
231
232 /**
233 * Get the number of elements in an array
234 */
235 #define countof(array) (sizeof(array)/sizeof(array[0]))
236
237 /**
238 * Ignore result of functions tagged with warn_unused_result attributes
239 */
240 #define ignore_result(call) { if(call){}; }
241
242 /**
243 * Assign a function as a class method
244 */
245 #define ASSIGN(method, function) (method = (typeof(method))function)
246
247 /**
248 * time_t not defined
249 */
250 #define UNDEFINED_TIME 0
251
252 /**
253 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
254 */
255 #define TIME_32_BIT_SIGNED_MAX 0x7fffffff
256
257 /**
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
261 */
262 #ifdef __sun
263 #include <stdint.h>
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;
268 #endif
269
270 typedef enum status_t status_t;
271
272 /**
273 * Return values of function calls.
274 */
275 enum status_t {
276 /**
277 * Call succeeded.
278 */
279 SUCCESS,
280
281 /**
282 * Call failed.
283 */
284 FAILED,
285
286 /**
287 * Out of resources.
288 */
289 OUT_OF_RES,
290
291 /**
292 * The suggested operation is already done
293 */
294 ALREADY_DONE,
295
296 /**
297 * Not supported.
298 */
299 NOT_SUPPORTED,
300
301 /**
302 * One of the arguments is invalid.
303 */
304 INVALID_ARG,
305
306 /**
307 * Something could not be found.
308 */
309 NOT_FOUND,
310
311 /**
312 * Error while parsing.
313 */
314 PARSE_ERROR,
315
316 /**
317 * Error while verifying.
318 */
319 VERIFY_ERROR,
320
321 /**
322 * Object in invalid state.
323 */
324 INVALID_STATE,
325
326 /**
327 * Destroy object which called method belongs to.
328 */
329 DESTROY_ME,
330
331 /**
332 * Another call to the method is required.
333 */
334 NEED_MORE,
335 };
336
337 /**
338 * enum_names for type status_t.
339 */
340 extern enum_name_t *status_names;
341
342 typedef enum tty_escape_t tty_escape_t;
343
344 /**
345 * Excape codes for tty colors
346 */
347 enum tty_escape_t {
348 /** text properties */
349 TTY_RESET,
350 TTY_BOLD,
351 TTY_UNDERLINE,
352 TTY_BLINKING,
353
354 /** foreground colors */
355 TTY_FG_BLACK,
356 TTY_FG_RED,
357 TTY_FG_GREEN,
358 TTY_FG_YELLOW,
359 TTY_FG_BLUE,
360 TTY_FG_MAGENTA,
361 TTY_FG_CYAN,
362 TTY_FG_WHITE,
363 TTY_FG_DEF,
364
365 /** background colors */
366 TTY_BG_BLACK,
367 TTY_BG_RED,
368 TTY_BG_GREEN,
369 TTY_BG_YELLOW,
370 TTY_BG_BLUE,
371 TTY_BG_MAGENTA,
372 TTY_BG_CYAN,
373 TTY_BG_WHITE,
374 TTY_BG_DEF,
375 };
376
377 /**
378 * Get the escape string for a given TTY color, empty string on non-tty fd
379 */
380 char* tty_escape_get(int fd, tty_escape_t escape);
381
382 /**
383 * deprecated pluto style return value:
384 * error message, NULL for success
385 */
386 typedef const char *err_t;
387
388 /**
389 * Handle struct timeval like an own type.
390 */
391 typedef struct timeval timeval_t;
392
393 /**
394 * Handle struct timespec like an own type.
395 */
396 typedef struct timespec timespec_t;
397
398 /**
399 * Handle struct chunk_t like an own type.
400 */
401 typedef struct sockaddr sockaddr_t;
402
403 /**
404 * Same as memcpy, but XORs src into dst instead of copy
405 */
406 void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
407
408 /**
409 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
410 */
411 void memwipe_noinline(void *ptr, size_t n);
412
413 /**
414 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
415 */
416 static inline void memwipe_inline(void *ptr, size_t n)
417 {
418 volatile char *c = (volatile char*)ptr;
419 size_t m, i;
420
421 /* byte wise until long aligned */
422 for (i = 0; (uintptr_t)&c[i] % sizeof(long) && i < n; i++)
423 {
424 c[i] = 0;
425 }
426 /* word wise */
427 if (n >= sizeof(long))
428 {
429 for (m = n - sizeof(long); i <= m; i += sizeof(long))
430 {
431 *(volatile long*)&c[i] = 0;
432 }
433 }
434 /* byte wise of the rest */
435 for (; i < n; i++)
436 {
437 c[i] = 0;
438 }
439 }
440
441 /**
442 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
443 */
444 static inline void memwipe(void *ptr, size_t n)
445 {
446 if (!ptr)
447 {
448 return;
449 }
450 if (__builtin_constant_p(n))
451 {
452 memwipe_inline(ptr, n);
453 }
454 else
455 {
456 memwipe_noinline(ptr, n);
457 }
458 }
459
460 /**
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.
463 */
464 void *memstr(const void *haystack, const char *needle, size_t n);
465
466 /**
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
470 * characters.
471 */
472 char *translate(char *str, const char *from, const char *to);
473
474 /**
475 * Replaces all occurrences of search in the given string with replace.
476 *
477 * Allocates memory only if anything is replaced in the string. The original
478 * string is also returned if any of the arguments are invalid (e.g. if search
479 * is empty or any of them are NULL).
480 *
481 * @param str original string
482 * @param search string to search for and replace
483 * @param replace string to replace found occurrences with
484 * @return allocated string, if anything got replaced, str otherwise
485 */
486 char *strreplace(const char *str, const char *search, const char *replace);
487
488 /**
489 * Creates a directory and all required parent directories.
490 *
491 * @param path path to the new directory
492 * @param mode permissions of the new directory/directories
493 * @return TRUE on success
494 */
495 bool mkdir_p(const char *path, mode_t mode);
496
497 /**
498 * Thread-safe wrapper around strerror and strerror_r.
499 *
500 * This is required because the first is not thread-safe (on some platforms)
501 * and the second uses two different signatures (POSIX/GNU) and is impractical
502 * to use anyway.
503 *
504 * @param errnum error code (i.e. errno)
505 * @return error message
506 */
507 const char *safe_strerror(int errnum);
508
509 /**
510 * Replace usages of strerror(3) with thread-safe variant.
511 */
512 #define strerror(errnum) safe_strerror(errnum)
513
514 #ifndef HAVE_CLOSEFROM
515 /**
516 * Close open file descriptors greater than or equal to lowfd.
517 *
518 * @param lowfd start closing file descriptors from here
519 */
520 void closefrom(int lowfd);
521 #endif
522
523 /**
524 * Get a timestamp from a monotonic time source.
525 *
526 * While the time()/gettimeofday() functions are affected by leap seconds
527 * and system time changes, this function returns ever increasing monotonic
528 * time stamps.
529 *
530 * @param tv timeval struct receiving monotonic timestamps, or NULL
531 * @return monotonic timestamp in seconds
532 */
533 time_t time_monotonic(timeval_t *tv);
534
535 /**
536 * Add the given number of milliseconds to the given timeval struct
537 *
538 * @param tv timeval struct to modify
539 * @param ms number of milliseconds
540 */
541 static inline void timeval_add_ms(timeval_t *tv, u_int ms)
542 {
543 tv->tv_usec += ms * 1000;
544 while (tv->tv_usec >= 1000000 /* 1s */)
545 {
546 tv->tv_usec -= 1000000;
547 tv->tv_sec++;
548 }
549 }
550
551 /**
552 * returns null
553 */
554 void *return_null();
555
556 /**
557 * No-Operation function
558 */
559 void nop();
560
561 /**
562 * returns TRUE
563 */
564 bool return_true();
565
566 /**
567 * returns FALSE
568 */
569 bool return_false();
570
571 /**
572 * returns FAILED
573 */
574 status_t return_failed();
575
576 /**
577 * returns SUCCESS
578 */
579 status_t return_success();
580
581 /**
582 * Write a 16-bit host order value in network order to an unaligned address.
583 *
584 * @param host host order 16-bit value
585 * @param network unaligned address to write network order value to
586 */
587 static inline void htoun16(void *network, u_int16_t host)
588 {
589 char *unaligned = (char*)network;
590
591 host = htons(host);
592 memcpy(unaligned, &host, sizeof(host));
593 }
594
595 /**
596 * Write a 32-bit host order value in network order to an unaligned address.
597 *
598 * @param host host order 32-bit value
599 * @param network unaligned address to write network order value to
600 */
601 static inline void htoun32(void *network, u_int32_t host)
602 {
603 char *unaligned = (char*)network;
604
605 host = htonl(host);
606 memcpy((char*)unaligned, &host, sizeof(host));
607 }
608
609 /**
610 * Write a 64-bit host order value in network order to an unaligned address.
611 *
612 * @param host host order 64-bit value
613 * @param network unaligned address to write network order value to
614 */
615 static inline void htoun64(void *network, u_int64_t host)
616 {
617 char *unaligned = (char*)network;
618
619 #ifdef be64toh
620 host = htobe64(host);
621 memcpy((char*)unaligned, &host, sizeof(host));
622 #else
623 u_int32_t high_part, low_part;
624
625 high_part = host >> 32;
626 high_part = htonl(high_part);
627 low_part = host & 0xFFFFFFFFLL;
628 low_part = htonl(low_part);
629
630 memcpy(unaligned, &high_part, sizeof(high_part));
631 unaligned += sizeof(high_part);
632 memcpy(unaligned, &low_part, sizeof(low_part));
633 #endif
634 }
635
636 /**
637 * Read a 16-bit value in network order from an unaligned address to host order.
638 *
639 * @param network unaligned address to read network order value from
640 * @return host order value
641 */
642 static inline u_int16_t untoh16(void *network)
643 {
644 char *unaligned = (char*)network;
645 u_int16_t tmp;
646
647 memcpy(&tmp, unaligned, sizeof(tmp));
648 return ntohs(tmp);
649 }
650
651 /**
652 * Read a 32-bit value in network order from an unaligned address to host order.
653 *
654 * @param network unaligned address to read network order value from
655 * @return host order value
656 */
657 static inline u_int32_t untoh32(void *network)
658 {
659 char *unaligned = (char*)network;
660 u_int32_t tmp;
661
662 memcpy(&tmp, unaligned, sizeof(tmp));
663 return ntohl(tmp);
664 }
665
666 /**
667 * Read a 64-bit value in network order from an unaligned address to host order.
668 *
669 * @param network unaligned address to read network order value from
670 * @return host order value
671 */
672 static inline u_int64_t untoh64(void *network)
673 {
674 char *unaligned = (char*)network;
675
676 #ifdef be64toh
677 u_int64_t tmp;
678
679 memcpy(&tmp, unaligned, sizeof(tmp));
680 return be64toh(tmp);
681 #else
682 u_int32_t high_part, low_part;
683
684 memcpy(&high_part, unaligned, sizeof(high_part));
685 unaligned += sizeof(high_part);
686 memcpy(&low_part, unaligned, sizeof(low_part));
687
688 high_part = ntohl(high_part);
689 low_part = ntohl(low_part);
690
691 return (((u_int64_t)high_part) << 32) + low_part;
692 #endif
693 }
694
695 /**
696 * Get the padding required to make size a multiple of alignment
697 */
698 static inline size_t pad_len(size_t size, size_t alignment)
699 {
700 size_t remainder;
701
702 remainder = size % alignment;
703 return remainder ? alignment - remainder : 0;
704 }
705
706 /**
707 * Round up size to be multiple of alignment
708 */
709 static inline size_t round_up(size_t size, size_t alignment)
710 {
711 return size + pad_len(size, alignment);
712 }
713
714 /**
715 * Round down size to be a multiple of alignment
716 */
717 static inline size_t round_down(size_t size, size_t alignment)
718 {
719 return size - (size % alignment);
720 }
721
722 /**
723 * Special type to count references
724 */
725 typedef u_int refcount_t;
726
727 #ifdef HAVE_GCC_ATOMIC_OPERATIONS
728
729 #define ref_get(ref) __sync_add_and_fetch(ref, 1)
730 #define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
731
732 #define cas_bool(ptr, oldval, newval) \
733 (__sync_bool_compare_and_swap(ptr, oldval, newval))
734 #define cas_ptr(ptr, oldval, newval) \
735 (__sync_bool_compare_and_swap(ptr, oldval, newval))
736
737 #else /* !HAVE_GCC_ATOMIC_OPERATIONS */
738
739 /**
740 * Get a new reference.
741 *
742 * Increments the reference counter atomic.
743 *
744 * @param ref pointer to ref counter
745 * @return new value of ref
746 */
747 refcount_t ref_get(refcount_t *ref);
748
749 /**
750 * Put back a unused reference.
751 *
752 * Decrements the reference counter atomic and
753 * says if more references available.
754 *
755 * @param ref pointer to ref counter
756 * @return TRUE if no more references counted
757 */
758 bool ref_put(refcount_t *ref);
759
760 /**
761 * Atomically replace value of ptr with newval if it currently equals oldval.
762 *
763 * @param ptr pointer to variable
764 * @param oldval old value of the variable
765 * @param newval new value set if possible
766 * @return TRUE if value equaled oldval and newval was written
767 */
768 bool cas_bool(bool *ptr, bool oldval, bool newval);
769
770 /**
771 * Atomically replace value of ptr with newval if it currently equals oldval.
772 *
773 * @param ptr pointer to variable
774 * @param oldval old value of the variable
775 * @param newval new value set if possible
776 * @return TRUE if value equaled oldval and newval was written
777 */
778 bool cas_ptr(void **ptr, void *oldval, void *newval);
779
780 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
781
782 #ifndef HAVE_FMEMOPEN
783 # ifdef HAVE_FUNOPEN
784 # define HAVE_FMEMOPEN
785 # define HAVE_FMEMOPEN_FALLBACK
786 # include <stdio.h>
787 /**
788 * fmemopen(3) fallback using BSD funopen.
789 *
790 * We could also provide one using fopencookie(), but should we have it we
791 * most likely have fmemopen().
792 *
793 * fseek() is currently not supported.
794 */
795 FILE *fmemopen(void *buf, size_t size, const char *mode);
796 # endif /* FUNOPEN */
797 #endif /* FMEMOPEN */
798
799 /**
800 * printf hook for time_t.
801 *
802 * Arguments are:
803 * time_t* time, bool utc
804 */
805 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
806 const void *const *args);
807
808 /**
809 * printf hook for time_t deltas.
810 *
811 * Arguments are:
812 * time_t* begin, time_t* end
813 */
814 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
815 const void *const *args);
816
817 /**
818 * printf hook for memory areas.
819 *
820 * Arguments are:
821 * u_char *ptr, u_int len
822 */
823 int mem_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
824 const void *const *args);
825
826 #endif /** UTILS_H_ @}*/