1129ea3a6e67cd936301efbbfec8a9902fa446a4
[strongswan.git] / src / libstrongswan / utils.c
1 /*
2 * Copyright (C) 2008-2010 Tobias Brunner
3 * Copyright (C) 2005-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 #include "utils.h"
18
19 #include <sys/stat.h>
20 #include <string.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <inttypes.h>
24 #include <stdint.h>
25 #include <limits.h>
26 #include <dirent.h>
27 #include <time.h>
28
29 #include "enum.h"
30 #include "debug.h"
31
32 ENUM(status_names, SUCCESS, NEED_MORE,
33 "SUCCESS",
34 "FAILED",
35 "OUT_OF_RES",
36 "ALREADY_DONE",
37 "NOT_SUPPORTED",
38 "INVALID_ARG",
39 "NOT_FOUND",
40 "PARSE_ERROR",
41 "VERIFY_ERROR",
42 "INVALID_STATE",
43 "DESTROY_ME",
44 "NEED_MORE",
45 );
46
47 /**
48 * Described in header.
49 */
50 void *clalloc(void * pointer, size_t size)
51 {
52 void *data;
53 data = malloc(size);
54
55 memcpy(data, pointer, size);
56
57 return (data);
58 }
59
60 /**
61 * Described in header.
62 */
63 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
64 {
65 int m, i;
66
67 /* byte wise XOR until dst aligned */
68 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
69 {
70 dst[i] ^= src[i];
71 }
72 /* try to use words if src shares an aligment with dst */
73 switch (((uintptr_t)&src[i] % sizeof(long)))
74 {
75 case 0:
76 for (m = n - sizeof(long); i <= m; i += sizeof(long))
77 {
78 *(long*)&dst[i] ^= *(long*)&src[i];
79 }
80 break;
81 case sizeof(int):
82 for (m = n - sizeof(int); i <= m; i += sizeof(int))
83 {
84 *(int*)&dst[i] ^= *(int*)&src[i];
85 }
86 break;
87 case sizeof(short):
88 for (m = n - sizeof(short); i <= m; i += sizeof(short))
89 {
90 *(short*)&dst[i] ^= *(short*)&src[i];
91 }
92 break;
93 default:
94 break;
95 }
96 /* byte wise XOR of the rest */
97 for (; i < n; i++)
98 {
99 dst[i] ^= src[i];
100 }
101 }
102
103 /**
104 * Described in header.
105 */
106 void memwipe_noinline(void *ptr, size_t n)
107 {
108 memwipe_inline(ptr, n);
109 }
110
111 /**
112 * Described in header.
113 */
114 void *memstr(const void *haystack, const char *needle, size_t n)
115 {
116 unsigned const char *pos = haystack;
117 size_t l = strlen(needle);
118 for (; n >= l; ++pos, --n)
119 {
120 if (memeq(pos, needle, l))
121 {
122 return (void*)pos;
123 }
124 }
125 return NULL;
126 }
127
128 /**
129 * Described in header.
130 */
131 char* translate(char *str, const char *from, const char *to)
132 {
133 char *pos = str;
134 if (strlen(from) != strlen(to))
135 {
136 return str;
137 }
138 while (pos && *pos)
139 {
140 char *match;
141 if ((match = strchr(from, *pos)) != NULL)
142 {
143 *pos = to[match - from];
144 }
145 pos++;
146 }
147 return str;
148 }
149
150 /**
151 * Described in header.
152 */
153 bool mkdir_p(const char *path, mode_t mode)
154 {
155 int len;
156 char *pos, full[PATH_MAX];
157 pos = full;
158 if (!path || *path == '\0')
159 {
160 return TRUE;
161 }
162 len = snprintf(full, sizeof(full)-1, "%s", path);
163 if (len < 0 || len >= sizeof(full)-1)
164 {
165 DBG1(DBG_LIB, "path string %s too long", path);
166 return FALSE;
167 }
168 /* ensure that the path ends with a '/' */
169 if (full[len-1] != '/')
170 {
171 full[len++] = '/';
172 full[len] = '\0';
173 }
174 /* skip '/' at the beginning */
175 while (*pos == '/')
176 {
177 pos++;
178 }
179 while ((pos = strchr(pos, '/')))
180 {
181 *pos = '\0';
182 if (access(full, F_OK) < 0)
183 {
184 if (mkdir(full, mode) < 0)
185 {
186 DBG1(DBG_LIB, "failed to create directory %s", full);
187 return FALSE;
188 }
189 }
190 *pos = '/';
191 pos++;
192 }
193 return TRUE;
194 }
195
196 /**
197 * Return monotonic time
198 */
199 time_t time_monotonic(timeval_t *tv)
200 {
201 #if defined(HAVE_CLOCK_GETTIME) && \
202 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
203 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
204 /* as we use time_monotonic() for condvar operations, we use the
205 * monotonic time source only if it is also supported by pthread. */
206 timespec_t ts;
207
208 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
209 {
210 if (tv)
211 {
212 tv->tv_sec = ts.tv_sec;
213 tv->tv_usec = ts.tv_nsec / 1000;
214 }
215 return ts.tv_sec;
216 }
217 #endif /* HAVE_CLOCK_GETTIME && (...) */
218 /* Fallback to non-monotonic timestamps:
219 * On MAC OS X, creating monotonic timestamps is rather difficult. We
220 * could use mach_absolute_time() and catch sleep/wakeup notifications.
221 * We stick to the simpler (non-monotonic) gettimeofday() for now.
222 * But keep in mind: we need the same time source here as in condvar! */
223 if (!tv)
224 {
225 return time(NULL);
226 }
227 if (gettimeofday(tv, NULL) != 0)
228 { /* should actually never fail if passed pointers are valid */
229 return -1;
230 }
231 return tv->tv_sec;
232 }
233
234 /**
235 * return null
236 */
237 void *return_null()
238 {
239 return NULL;
240 }
241
242 /**
243 * returns TRUE
244 */
245 bool return_true()
246 {
247 return TRUE;
248 }
249
250 /**
251 * returns FALSE
252 */
253 bool return_false()
254 {
255 return FALSE;
256 }
257
258 /**
259 * returns FAILED
260 */
261 status_t return_failed()
262 {
263 return FAILED;
264 }
265
266 /**
267 * nop operation
268 */
269 void nop()
270 {
271 }
272
273 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
274 #include <pthread.h>
275
276 /**
277 * We use a single mutex for all refcount variables.
278 */
279 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
280
281 /**
282 * Increase refcount
283 */
284 void ref_get(refcount_t *ref)
285 {
286 pthread_mutex_lock(&ref_mutex);
287 (*ref)++;
288 pthread_mutex_unlock(&ref_mutex);
289 }
290
291 /**
292 * Decrease refcount
293 */
294 bool ref_put(refcount_t *ref)
295 {
296 bool more_refs;
297
298 pthread_mutex_lock(&ref_mutex);
299 more_refs = --(*ref) > 0;
300 pthread_mutex_unlock(&ref_mutex);
301 return !more_refs;
302 }
303 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
304
305 /**
306 * Described in header.
307 */
308 int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
309 const void *const *args)
310 {
311 static const char* months[] = {
312 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
313 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
314 };
315 time_t *time = *((time_t**)(args[0]));
316 bool utc = *((bool*)(args[1]));;
317 struct tm t;
318
319 if (time == UNDEFINED_TIME)
320 {
321 return print_in_hook(dst, len, "--- -- --:--:--%s----",
322 utc ? " UTC " : " ");
323 }
324 if (utc)
325 {
326 gmtime_r(time, &t);
327 }
328 else
329 {
330 localtime_r(time, &t);
331 }
332 return print_in_hook(dst, len, "%s %02d %02d:%02d:%02d%s%04d",
333 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
334 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
335 }
336
337 /**
338 * Described in header.
339 */
340 int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
341 const void *const *args)
342 {
343 char* unit = "second";
344 time_t *arg1 = *((time_t**)(args[0]));
345 time_t *arg2 = *((time_t**)(args[1]));
346 u_int64_t delta = llabs(*arg1 - *arg2);
347
348 if (delta > 2 * 60 * 60 * 24)
349 {
350 delta /= 60 * 60 * 24;
351 unit = "day";
352 }
353 else if (delta > 2 * 60 * 60)
354 {
355 delta /= 60 * 60;
356 unit = "hour";
357 }
358 else if (delta > 2 * 60)
359 {
360 delta /= 60;
361 unit = "minute";
362 }
363 return print_in_hook(dst, len, "%" PRIu64 " %s%s", delta, unit,
364 (delta == 1) ? "" : "s");
365 }
366
367 /**
368 * Number of bytes per line to dump raw data
369 */
370 #define BYTES_PER_LINE 16
371
372 static char hexdig_upper[] = "0123456789ABCDEF";
373
374 /**
375 * Described in header.
376 */
377 int mem_printf_hook(char *dst, size_t dstlen,
378 printf_hook_spec_t *spec, const void *const *args)
379 {
380 char *bytes = *((void**)(args[0]));
381 int len = *((size_t*)(args[1]));
382
383 char buffer[BYTES_PER_LINE * 3];
384 char ascii_buffer[BYTES_PER_LINE + 1];
385 char *buffer_pos = buffer;
386 char *bytes_pos = bytes;
387 char *bytes_roof = bytes + len;
388 int line_start = 0;
389 int i = 0;
390 int written = 0;
391
392 written += print_in_hook(dst, dstlen, "=> %d bytes @ %p", len, bytes);
393
394 while (bytes_pos < bytes_roof)
395 {
396 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
397 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
398
399 ascii_buffer[i++] =
400 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
401
402 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
403 {
404 int padding = 3 * (BYTES_PER_LINE - i);
405
406 while (padding--)
407 {
408 *buffer_pos++ = ' ';
409 }
410 *buffer_pos++ = '\0';
411 ascii_buffer[i] = '\0';
412
413 written += print_in_hook(dst, dstlen, "\n%4d: %s %s",
414 line_start, buffer, ascii_buffer);
415
416 buffer_pos = buffer;
417 line_start += BYTES_PER_LINE;
418 i = 0;
419 }
420 else
421 {
422 *buffer_pos++ = ' ';
423 }
424 }
425 return written;
426 }