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