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