Merge branch 'multi-cert'
[strongswan.git] / src / libstrongswan / utils / utils.c
1 /*
2 * Copyright (C) 2008-2012 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 #include <pthread.h>
29
30 #include "collections/enumerator.h"
31 #include "utils/debug.h"
32
33 ENUM(status_names, SUCCESS, NEED_MORE,
34 "SUCCESS",
35 "FAILED",
36 "OUT_OF_RES",
37 "ALREADY_DONE",
38 "NOT_SUPPORTED",
39 "INVALID_ARG",
40 "NOT_FOUND",
41 "PARSE_ERROR",
42 "VERIFY_ERROR",
43 "INVALID_STATE",
44 "DESTROY_ME",
45 "NEED_MORE",
46 );
47
48 /**
49 * Described in header.
50 */
51 void *clalloc(void * pointer, size_t size)
52 {
53 void *data;
54 data = malloc(size);
55
56 memcpy(data, pointer, size);
57
58 return (data);
59 }
60
61 /**
62 * Described in header.
63 */
64 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
65 {
66 int m, i;
67
68 /* byte wise XOR until dst aligned */
69 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
70 {
71 dst[i] ^= src[i];
72 }
73 /* try to use words if src shares an aligment with dst */
74 switch (((uintptr_t)&src[i] % sizeof(long)))
75 {
76 case 0:
77 for (m = n - sizeof(long); i <= m; i += sizeof(long))
78 {
79 *(long*)&dst[i] ^= *(long*)&src[i];
80 }
81 break;
82 case sizeof(int):
83 for (m = n - sizeof(int); i <= m; i += sizeof(int))
84 {
85 *(int*)&dst[i] ^= *(int*)&src[i];
86 }
87 break;
88 case sizeof(short):
89 for (m = n - sizeof(short); i <= m; i += sizeof(short))
90 {
91 *(short*)&dst[i] ^= *(short*)&src[i];
92 }
93 break;
94 default:
95 break;
96 }
97 /* byte wise XOR of the rest */
98 for (; i < n; i++)
99 {
100 dst[i] ^= src[i];
101 }
102 }
103
104 /**
105 * Described in header.
106 */
107 void memwipe_noinline(void *ptr, size_t n)
108 {
109 memwipe_inline(ptr, n);
110 }
111
112 /**
113 * Described in header.
114 */
115 void *memstr(const void *haystack, const char *needle, size_t n)
116 {
117 unsigned const char *pos = haystack;
118 size_t l = strlen(needle);
119 for (; n >= l; ++pos, --n)
120 {
121 if (memeq(pos, needle, l))
122 {
123 return (void*)pos;
124 }
125 }
126 return NULL;
127 }
128
129 /**
130 * Described in header.
131 */
132 char* translate(char *str, const char *from, const char *to)
133 {
134 char *pos = str;
135 if (strlen(from) != strlen(to))
136 {
137 return str;
138 }
139 while (pos && *pos)
140 {
141 char *match;
142 if ((match = strchr(from, *pos)) != NULL)
143 {
144 *pos = to[match - from];
145 }
146 pos++;
147 }
148 return str;
149 }
150
151 /**
152 * Described in header.
153 */
154 bool mkdir_p(const char *path, mode_t mode)
155 {
156 int len;
157 char *pos, full[PATH_MAX];
158 pos = full;
159 if (!path || *path == '\0')
160 {
161 return TRUE;
162 }
163 len = snprintf(full, sizeof(full)-1, "%s", path);
164 if (len < 0 || len >= sizeof(full)-1)
165 {
166 DBG1(DBG_LIB, "path string %s too long", path);
167 return FALSE;
168 }
169 /* ensure that the path ends with a '/' */
170 if (full[len-1] != '/')
171 {
172 full[len++] = '/';
173 full[len] = '\0';
174 }
175 /* skip '/' at the beginning */
176 while (*pos == '/')
177 {
178 pos++;
179 }
180 while ((pos = strchr(pos, '/')))
181 {
182 *pos = '\0';
183 if (access(full, F_OK) < 0)
184 {
185 if (mkdir(full, mode) < 0)
186 {
187 DBG1(DBG_LIB, "failed to create directory %s", full);
188 return FALSE;
189 }
190 }
191 *pos = '/';
192 pos++;
193 }
194 return TRUE;
195 }
196
197
198 /**
199 * The size of the thread-specific error buffer
200 */
201 #define STRERROR_BUF_LEN 256
202
203 /**
204 * Key to store thread-specific error buffer
205 */
206 static pthread_key_t strerror_buf_key;
207
208 /**
209 * Only initialize the key above once
210 */
211 static pthread_once_t strerror_buf_key_once = PTHREAD_ONCE_INIT;
212
213 /**
214 * Create the key used for the thread-specific error buffer
215 */
216 static void create_strerror_buf_key()
217 {
218 pthread_key_create(&strerror_buf_key, free);
219 }
220
221 /**
222 * Retrieve the error buffer assigned to the current thread (or create it)
223 */
224 static inline char *get_strerror_buf()
225 {
226 char *buf;
227
228 pthread_once(&strerror_buf_key_once, create_strerror_buf_key);
229 buf = pthread_getspecific(strerror_buf_key);
230 if (!buf)
231 {
232 buf = malloc(STRERROR_BUF_LEN);
233 pthread_setspecific(strerror_buf_key, buf);
234 }
235 return buf;
236 }
237
238 #ifdef HAVE_STRERROR_R
239 /*
240 * Described in header.
241 */
242 const char *safe_strerror(int errnum)
243 {
244 char *buf = get_strerror_buf(), *msg;
245
246 #ifdef STRERROR_R_CHAR_P
247 /* char* version which may or may not return the original buffer */
248 msg = strerror_r(errnum, buf, STRERROR_BUF_LEN);
249 #else
250 /* int version returns 0 on success */
251 msg = strerror_r(errnum, buf, STRERROR_BUF_LEN) ? "Unknown error" : buf;
252 #endif
253 return msg;
254 }
255 #else /* HAVE_STRERROR_R */
256 /* we actually wan't to call strerror(3) below */
257 #undef strerror
258 /*
259 * Described in header.
260 */
261 const char *safe_strerror(int errnum)
262 {
263 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
264 char *buf = get_strerror_buf();
265
266 /* use a mutex to ensure calling strerror(3) is thread-safe */
267 pthread_mutex_lock(&mutex);
268 strncpy(buf, strerror(errnum), STRERROR_BUF_LEN);
269 pthread_mutex_unlock(&mutex);
270 buf[STRERROR_BUF_LEN - 1] = '\0';
271 return buf;
272 }
273 #endif /* HAVE_STRERROR_R */
274
275
276 #ifndef HAVE_CLOSEFROM
277 /**
278 * Described in header.
279 */
280 void closefrom(int lowfd)
281 {
282 char fd_dir[PATH_MAX];
283 int maxfd, fd, len;
284
285 /* try to close only open file descriptors on Linux... */
286 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
287 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
288 {
289 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
290 if (enumerator)
291 {
292 char *rel;
293 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
294 {
295 fd = atoi(rel);
296 if (fd >= lowfd)
297 {
298 close(fd);
299 }
300 }
301 enumerator->destroy(enumerator);
302 return;
303 }
304 }
305
306 /* ...fall back to closing all fds otherwise */
307 maxfd = (int)sysconf(_SC_OPEN_MAX);
308 if (maxfd < 0)
309 {
310 maxfd = 256;
311 }
312 for (fd = lowfd; fd < maxfd; fd++)
313 {
314 close(fd);
315 }
316 }
317 #endif /* HAVE_CLOSEFROM */
318
319 /**
320 * Return monotonic time
321 */
322 time_t time_monotonic(timeval_t *tv)
323 {
324 #if defined(HAVE_CLOCK_GETTIME) && \
325 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
326 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
327 /* as we use time_monotonic() for condvar operations, we use the
328 * monotonic time source only if it is also supported by pthread. */
329 timespec_t ts;
330
331 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
332 {
333 if (tv)
334 {
335 tv->tv_sec = ts.tv_sec;
336 tv->tv_usec = ts.tv_nsec / 1000;
337 }
338 return ts.tv_sec;
339 }
340 #endif /* HAVE_CLOCK_GETTIME && (...) */
341 /* Fallback to non-monotonic timestamps:
342 * On MAC OS X, creating monotonic timestamps is rather difficult. We
343 * could use mach_absolute_time() and catch sleep/wakeup notifications.
344 * We stick to the simpler (non-monotonic) gettimeofday() for now.
345 * But keep in mind: we need the same time source here as in condvar! */
346 if (!tv)
347 {
348 return time(NULL);
349 }
350 if (gettimeofday(tv, NULL) != 0)
351 { /* should actually never fail if passed pointers are valid */
352 return -1;
353 }
354 return tv->tv_sec;
355 }
356
357 /**
358 * return null
359 */
360 void *return_null()
361 {
362 return NULL;
363 }
364
365 /**
366 * returns TRUE
367 */
368 bool return_true()
369 {
370 return TRUE;
371 }
372
373 /**
374 * returns FALSE
375 */
376 bool return_false()
377 {
378 return FALSE;
379 }
380
381 /**
382 * returns FAILED
383 */
384 status_t return_failed()
385 {
386 return FAILED;
387 }
388
389 /**
390 * returns SUCCESS
391 */
392 status_t return_success()
393 {
394 return SUCCESS;
395 }
396
397 /**
398 * nop operation
399 */
400 void nop()
401 {
402 }
403
404 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
405
406 /**
407 * We use a single mutex for all refcount variables.
408 */
409 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
410
411 /**
412 * Increase refcount
413 */
414 void ref_get(refcount_t *ref)
415 {
416 pthread_mutex_lock(&ref_mutex);
417 (*ref)++;
418 pthread_mutex_unlock(&ref_mutex);
419 }
420
421 /**
422 * Decrease refcount
423 */
424 bool ref_put(refcount_t *ref)
425 {
426 bool more_refs;
427
428 pthread_mutex_lock(&ref_mutex);
429 more_refs = --(*ref) > 0;
430 pthread_mutex_unlock(&ref_mutex);
431 return !more_refs;
432 }
433
434 /**
435 * Single mutex for all compare and swap operations.
436 */
437 static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
438
439 /**
440 * Compare and swap if equal to old value
441 */
442 #define _cas_impl(name, type) \
443 bool cas_##name(type *ptr, type oldval, type newval) \
444 { \
445 bool swapped; \
446 pthread_mutex_lock(&cas_mutex); \
447 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
448 pthread_mutex_unlock(&cas_mutex); \
449 return swapped; \
450 }
451
452 _cas_impl(bool, bool)
453 _cas_impl(ptr, void*)
454
455 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
456
457 /**
458 * Described in header.
459 */
460 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
461 const void *const *args)
462 {
463 static const char* months[] = {
464 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
465 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
466 };
467 time_t *time = *((time_t**)(args[0]));
468 bool utc = *((bool*)(args[1]));;
469 struct tm t;
470
471 if (*time == UNDEFINED_TIME)
472 {
473 return print_in_hook(data, "--- -- --:--:--%s----",
474 utc ? " UTC " : " ");
475 }
476 if (utc)
477 {
478 gmtime_r(time, &t);
479 }
480 else
481 {
482 localtime_r(time, &t);
483 }
484 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
485 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
486 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
487 }
488
489 /**
490 * Described in header.
491 */
492 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
493 const void *const *args)
494 {
495 char* unit = "second";
496 time_t *arg1 = *((time_t**)(args[0]));
497 time_t *arg2 = *((time_t**)(args[1]));
498 u_int64_t delta = llabs(*arg1 - *arg2);
499
500 if (delta > 2 * 60 * 60 * 24)
501 {
502 delta /= 60 * 60 * 24;
503 unit = "day";
504 }
505 else if (delta > 2 * 60 * 60)
506 {
507 delta /= 60 * 60;
508 unit = "hour";
509 }
510 else if (delta > 2 * 60)
511 {
512 delta /= 60;
513 unit = "minute";
514 }
515 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
516 (delta == 1) ? "" : "s");
517 }
518
519 /**
520 * Number of bytes per line to dump raw data
521 */
522 #define BYTES_PER_LINE 16
523
524 static char hexdig_upper[] = "0123456789ABCDEF";
525
526 /**
527 * Described in header.
528 */
529 int mem_printf_hook(printf_hook_data_t *data,
530 printf_hook_spec_t *spec, const void *const *args)
531 {
532 char *bytes = *((void**)(args[0]));
533 u_int len = *((int*)(args[1]));
534
535 char buffer[BYTES_PER_LINE * 3];
536 char ascii_buffer[BYTES_PER_LINE + 1];
537 char *buffer_pos = buffer;
538 char *bytes_pos = bytes;
539 char *bytes_roof = bytes + len;
540 int line_start = 0;
541 int i = 0;
542 int written = 0;
543
544 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
545
546 while (bytes_pos < bytes_roof)
547 {
548 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
549 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
550
551 ascii_buffer[i++] =
552 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
553
554 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
555 {
556 int padding = 3 * (BYTES_PER_LINE - i);
557
558 while (padding--)
559 {
560 *buffer_pos++ = ' ';
561 }
562 *buffer_pos++ = '\0';
563 ascii_buffer[i] = '\0';
564
565 written += print_in_hook(data, "\n%4d: %s %s",
566 line_start, buffer, ascii_buffer);
567
568 buffer_pos = buffer;
569 line_start += BYTES_PER_LINE;
570 i = 0;
571 }
572 else
573 {
574 *buffer_pos++ = ' ';
575 }
576 }
577 return written;
578 }