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