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