f07e8358246e2acd42b6806c349c78f23a28611f
[strongswan.git] / src / libstrongswan / utils.h
1 /*
2 * Copyright (C) 2008-2009 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
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 binary blobs for equality
71 */
72 #define memeq(x,y,len) (memcmp(x, y, len) == 0)
73
74 /**
75 * Macro gives back larger of two values.
76 */
77 #define max(x,y) ({ \
78 typeof(x) _x = (x); \
79 typeof(y) _y = (y); \
80 _x > _y ? _x : _y; })
81
82
83 /**
84 * Macro gives back smaller of two values.
85 */
86 #define min(x,y) ({ \
87 typeof(x) _x = (x); \
88 typeof(y) _y = (y); \
89 _x < _y ? _x : _y; })
90
91 /**
92 * Call destructor of an object, if object != NULL
93 */
94 #define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
95
96 /**
97 * Call offset destructor of an object, if object != NULL
98 */
99 #define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
100
101 /**
102 * Call function destructor of an object, if object != NULL
103 */
104 #define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
105
106 /**
107 * Debug macro to follow control flow
108 */
109 #define POS printf("%s, line %d\n", __FILE__, __LINE__)
110
111 /**
112 * Object allocation/initialization macro, using designated initializer.
113 */
114 #define INIT(this, ...) { (this) = malloc(sizeof(*this)); \
115 *(this) = (typeof(*this)){ __VA_ARGS__ }; }
116
117 /**
118 * Method declaration/definition macro, providing private and public interface.
119 *
120 * Defines a method name with this as first parameter and a return value ret,
121 * and an alias for this method with a _ prefix, having the this argument
122 * safely casted to the public interface iface.
123 * _name is provided a function pointer, but will get optimized out by GCC.
124 */
125 #define METHOD(iface, name, ret, this, ...) \
126 static ret name(union {iface *_public; this;} __attribute__((transparent_union)), ##__VA_ARGS__); \
127 const static typeof(name) *_##name = (const typeof(name)*)name; \
128 static ret name(this, ##__VA_ARGS__)
129
130 /**
131 * Macro to allocate a sized type.
132 */
133 #define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
134
135 /**
136 * Get the number of elements in an array
137 */
138 #define countof(array) (sizeof(array)/sizeof(array[0]))
139
140 /**
141 * Ignore result of functions tagged with warn_unused_result attributes
142 */
143 #define ignore_result(call) { if(call); }
144
145 /**
146 * Assign a function as a class method
147 */
148 #define ASSIGN(method, function) (method = (typeof(method))function)
149
150 /**
151 * time_t not defined
152 */
153 #define UNDEFINED_TIME 0
154
155 /**
156 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
157 */
158 #define TIME_32_BIT_SIGNED_MAX 0x7fffffff
159
160 /**
161 * General purpose boolean type.
162 */
163 #ifdef HAVE_STDBOOL_H
164 # include <stdbool.h>
165 #else
166 # ifndef HAVE__BOOL
167 # define _Bool signed char
168 # endif /* HAVE__BOOL */
169 # define bool _Bool
170 # define false 0
171 # define true 1
172 # define __bool_true_false_are_defined 1
173 #endif /* HAVE_STDBOOL_H */
174 #ifndef FALSE
175 # define FALSE false
176 #endif /* FALSE */
177 #ifndef TRUE
178 # define TRUE true
179 #endif /* TRUE */
180
181 /**
182 * define some missing fixed width int types on OpenSolaris.
183 * TODO: since the uintXX_t types are defined by the C99 standard we should
184 * probably use those anyway
185 */
186 #ifdef __sun
187 #include <stdint.h>
188 typedef uint8_t u_int8_t;
189 typedef uint16_t u_int16_t;
190 typedef uint32_t u_int32_t;
191 typedef uint64_t u_int64_t;
192 #endif
193
194 typedef enum status_t status_t;
195
196 /**
197 * Return values of function calls.
198 */
199 enum status_t {
200 /**
201 * Call succeeded.
202 */
203 SUCCESS,
204
205 /**
206 * Call failed.
207 */
208 FAILED,
209
210 /**
211 * Out of resources.
212 */
213 OUT_OF_RES,
214
215 /**
216 * The suggested operation is already done
217 */
218 ALREADY_DONE,
219
220 /**
221 * Not supported.
222 */
223 NOT_SUPPORTED,
224
225 /**
226 * One of the arguments is invalid.
227 */
228 INVALID_ARG,
229
230 /**
231 * Something could not be found.
232 */
233 NOT_FOUND,
234
235 /**
236 * Error while parsing.
237 */
238 PARSE_ERROR,
239
240 /**
241 * Error while verifying.
242 */
243 VERIFY_ERROR,
244
245 /**
246 * Object in invalid state.
247 */
248 INVALID_STATE,
249
250 /**
251 * Destroy object which called method belongs to.
252 */
253 DESTROY_ME,
254
255 /**
256 * Another call to the method is required.
257 */
258 NEED_MORE,
259 };
260
261 /**
262 * enum_names for type status_t.
263 */
264 extern enum_name_t *status_names;
265
266 /**
267 * deprecated pluto style return value:
268 * error message, NULL for success
269 */
270 typedef const char *err_t;
271
272 /**
273 * Handle struct timeval like an own type.
274 */
275 typedef struct timeval timeval_t;
276
277 /**
278 * Handle struct timespec like an own type.
279 */
280 typedef struct timespec timespec_t;
281
282 /**
283 * Handle struct chunk_t like an own type.
284 */
285 typedef struct sockaddr sockaddr_t;
286
287 /**
288 * Clone a data to a newly allocated buffer
289 */
290 void *clalloc(void *pointer, size_t size);
291
292 /**
293 * Same as memcpy, but XORs src into dst instead of copy
294 */
295 void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
296
297 /**
298 * A variant of strstr with the characteristics of memchr, where haystack is not
299 * a null-terminated string but simply a memory area of length n.
300 */
301 void *memstr(const void *haystack, const char *needle, size_t n);
302
303 /**
304 * Creates a directory and all required parent directories.
305 *
306 * @param path path to the new directory
307 * @param mode permissions of the new directory/directories
308 * @return TRUE on success
309 */
310 bool mkdir_p(const char *path, mode_t mode);
311
312 /**
313 * Get a timestamp from a monotonic time source.
314 *
315 * While the time()/gettimeofday() functions are affected by leap seconds
316 * and system time changes, this function returns ever increasing monotonic
317 * time stamps.
318 *
319 * @param tv timeval struct receiving monotonic timestamps, or NULL
320 * @return monotonic timestamp in seconds
321 */
322 time_t time_monotonic(timeval_t *tv);
323
324 /**
325 * returns null
326 */
327 void *return_null();
328
329 /**
330 * No-Operation function
331 */
332 void nop();
333
334 /**
335 * returns TRUE
336 */
337 bool return_true();
338
339 /**
340 * returns FALSE
341 */
342 bool return_false();
343
344 /**
345 * Write a 16-bit host order value in network order to an unaligned address.
346 *
347 * @param host host order 16-bit value
348 * @param network unaligned address to write network order value to
349 */
350 static inline void htoun16(void *network, u_int16_t host)
351 {
352 host = htons(host);
353 memcpy(network, &host, sizeof(host));
354 }
355
356 /**
357 * Write a 32-bit host order value in network order to an unaligned address.
358 *
359 * @param host host order 32-bit value
360 * @param network unaligned address to write network order value to
361 */
362 static inline void htoun32(void *network, u_int32_t host)
363 {
364 host = htonl(host);
365 memcpy(network, &host, sizeof(host));
366 }
367
368 /**
369 * Read a 16-bit value in network order from an unaligned address to host order.
370 *
371 * @param network unaligned address to read network order value from
372 * @return host order value
373 */
374 static inline u_int16_t untoh16(void *network)
375 {
376 u_int16_t tmp;
377
378 memcpy(&tmp, network, sizeof(tmp));
379 return ntohs(tmp);
380 }
381
382 /**
383 * Read a 32-bit value in network order from an unaligned address to host order.
384 *
385 * @param network unaligned address to read network order value from
386 * @return host order value
387 */
388 static inline u_int32_t untoh32(void *network)
389 {
390 u_int32_t tmp;
391
392 memcpy(&tmp, network, sizeof(tmp));
393 return ntohs(tmp);
394 }
395
396 /**
397 * Special type to count references
398 */
399 typedef volatile u_int refcount_t;
400
401
402 #ifdef HAVE_GCC_ATOMIC_OPERATIONS
403
404 #define ref_get(ref) {__sync_fetch_and_add(ref, 1); }
405 #define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
406
407 #else /* !HAVE_GCC_ATOMIC_OPERATIONS */
408
409 /**
410 * Get a new reference.
411 *
412 * Increments the reference counter atomic.
413 *
414 * @param ref pointer to ref counter
415 */
416 void ref_get(refcount_t *ref);
417
418 /**
419 * Put back a unused reference.
420 *
421 * Decrements the reference counter atomic and
422 * says if more references available.
423 *
424 * @param ref pointer to ref counter
425 * @return TRUE if no more references counted
426 */
427 bool ref_put(refcount_t *ref);
428
429 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
430
431 /**
432 * printf hook for time_t.
433 *
434 * Arguments are:
435 * time_t* time, bool utc
436 */
437 int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
438 const void *const *args);
439
440 /**
441 * printf hook for time_t deltas.
442 *
443 * Arguments are:
444 * time_t* begin, time_t* end
445 */
446 int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
447 const void *const *args);
448
449 /**
450 * printf hook for memory areas.
451 *
452 * Arguments are:
453 * u_char *ptr, int len
454 */
455 int mem_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
456 const void *const *args);
457
458 #endif /** UTILS_H_ @}*/