]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils.c
Increase leak detective backtrace depth by a frame
[people/ms/strongswan.git] / src / libstrongswan / utils.c
CommitLineData
552cc11b 1/*
2a595276 2 * Copyright (C) 2008-2012 Tobias Brunner
552cc11b
MW
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.
552cc11b
MW
15 */
16
17#include "utils.h"
18
6c20579a 19#include <sys/stat.h>
552cc11b 20#include <string.h>
552cc11b 21#include <stdio.h>
6c20579a 22#include <unistd.h>
876961cf 23#include <inttypes.h>
74b14b40 24#include <stdint.h>
d24a74c5 25#include <limits.h>
6c20579a 26#include <dirent.h>
f464d750 27#include <time.h>
2a595276 28#include <pthread.h>
552cc11b 29
fac3bfa5
TB
30#include "enum.h"
31#include "debug.h"
5051bd23 32#include "utils/enumerator.h"
552cc11b 33
a8809bb0 34ENUM(status_names, SUCCESS, NEED_MORE,
552cc11b
MW
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 */
52void *clalloc(void * pointer, size_t size)
53{
54 void *data;
55 data = malloc(size);
7daf5226 56
552cc11b 57 memcpy(data, pointer, size);
7daf5226 58
552cc11b
MW
59 return (data);
60}
61
62/**
63 * Described in header.
64 */
01e43e31 65void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
552cc11b 66{
01e43e31 67 int m, i;
7daf5226 68
01e43e31 69 /* byte wise XOR until dst aligned */
09846603 70 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
4fd233a7 71 {
01e43e31 72 dst[i] ^= src[i];
4fd233a7 73 }
01e43e31 74 /* try to use words if src shares an aligment with dst */
74b14b40 75 switch (((uintptr_t)&src[i] % sizeof(long)))
552cc11b 76 {
01e43e31
MW
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];
552cc11b
MW
102 }
103}
104
ed678b52
MW
105/**
106 * Described in header.
107 */
108void memwipe_noinline(void *ptr, size_t n)
109{
110 memwipe_inline(ptr, n);
111}
112
81736d7d
TB
113/**
114 * Described in header.
115 */
116void *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
d543d9ca
TB
130/**
131 * Described in header.
132 */
133char* 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
6c20579a
TB
152/**
153 * Described in header.
154 */
155bool mkdir_p(const char *path, mode_t mode)
156{
fc1afcc8 157 int len;
6c20579a
TB
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 {
8b0e0910 167 DBG1(DBG_LIB, "path string %s too long", path);
6c20579a
TB
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 {
8b0e0910 188 DBG1(DBG_LIB, "failed to create directory %s", full);
6c20579a
TB
189 return FALSE;
190 }
191 }
192 *pos = '/';
193 pos++;
194 }
195 return TRUE;
196}
197
2a595276
TB
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 */
207static pthread_key_t strerror_buf_key;
208
209/**
210 * Only initialize the key above once
211 */
212static pthread_once_t strerror_buf_key_once = PTHREAD_ONCE_INIT;
213
214/**
215 * Create the key used for the thread-specific error buffer
216 */
217static 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 */
225static 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 */
243const 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 */
bbbffac3
TB
257/* we actually wan't to call strerror(3) below */
258#undef strerror
2a595276
TB
259/*
260 * Described in header.
261 */
262const 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
9a8fdc15
TB
277#ifndef HAVE_CLOSEFROM
278/**
279 * Described in header.
280 */
281void closefrom(int lowfd)
282{
5051bd23
TB
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());
4a4cf41b 288 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
5051bd23
TB
289 {
290 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
291 if (enumerator)
292 {
68fcf917 293 char *rel;
5051bd23
TB
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 */
9a8fdc15
TB
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
3f310c0d
MW
320/**
321 * Return monotonic time
322 */
323time_t time_monotonic(timeval_t *tv)
324{
b2944d71
TB
325#if defined(HAVE_CLOCK_GETTIME) && \
326 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
327 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
328 /* as we use time_monotonic() for condvar operations, we use the
329 * monotonic time source only if it is also supported by pthread. */
3f310c0d 330 timespec_t ts;
7daf5226 331
3f310c0d
MW
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 }
b2944d71 341#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
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.
3d5818ec
MW
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! */
3f310c0d
MW
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
081ae2eb
MW
358/**
359 * return null
360 */
361void *return_null()
362{
363 return NULL;
364}
365
da17b016
MW
366/**
367 * returns TRUE
368 */
369bool return_true()
370{
371 return TRUE;
372}
373
374/**
375 * returns FALSE
376 */
377bool return_false()
378{
379 return FALSE;
380}
381
502edf42
MW
382/**
383 * returns FAILED
384 */
385status_t return_failed()
386{
387 return FAILED;
388}
389
233b853d
MW
390/**
391 * nop operation
392 */
393void nop()
394{
395}
396
efd0fe21 397#ifndef HAVE_GCC_ATOMIC_OPERATIONS
efd0fe21 398
552cc11b 399/**
7daf5226 400 * We use a single mutex for all refcount variables.
552cc11b
MW
401 */
402static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
403
404/**
efd0fe21 405 * Increase refcount
552cc11b
MW
406 */
407void ref_get(refcount_t *ref)
408{
409 pthread_mutex_lock(&ref_mutex);
410 (*ref)++;
411 pthread_mutex_unlock(&ref_mutex);
412}
413
414/**
efd0fe21 415 * Decrease refcount
552cc11b
MW
416 */
417bool ref_put(refcount_t *ref)
418{
419 bool more_refs;
7daf5226 420
552cc11b 421 pthread_mutex_lock(&ref_mutex);
21f411b8 422 more_refs = --(*ref) > 0;
552cc11b
MW
423 pthread_mutex_unlock(&ref_mutex);
424 return !more_refs;
425}
5317dd68
TB
426
427/**
428 * Single mutex for all compare and swap operations.
429 */
430static 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) \
436bool 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
efd0fe21 448#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
552cc11b
MW
449
450/**
d25ce370 451 * Described in header.
552cc11b 452 */
d25ce370
TB
453int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
454 const void *const *args)
552cc11b
MW
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]));
d25ce370 461 bool utc = *((bool*)(args[1]));;
552cc11b 462 struct tm t;
7daf5226 463
552cc11b
MW
464 if (time == UNDEFINED_TIME)
465 {
d25ce370
TB
466 return print_in_hook(dst, len, "--- -- --:--:--%s----",
467 utc ? " UTC " : " ");
552cc11b
MW
468 }
469 if (utc)
470 {
471 gmtime_r(time, &t);
472 }
473 else
474 {
475 localtime_r(time, &t);
476 }
d25ce370
TB
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);
552cc11b
MW
480}
481
482/**
d25ce370 483 * Described in header.
552cc11b 484 */
d25ce370
TB
485int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
486 const void *const *args)
552cc11b
MW
487{
488 char* unit = "second";
d25ce370
TB
489 time_t *arg1 = *((time_t**)(args[0]));
490 time_t *arg2 = *((time_t**)(args[1]));
876961cf 491 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 492
552cc11b
MW
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 }
876961cf
TB
508 return print_in_hook(dst, len, "%" PRIu64 " %s%s", delta, unit,
509 (delta == 1) ? "" : "s");
552cc11b
MW
510}
511
512/**
513 * Number of bytes per line to dump raw data
514 */
515#define BYTES_PER_LINE 16
516
517static char hexdig_upper[] = "0123456789ABCDEF";
518
519/**
d25ce370 520 * Described in header.
552cc11b 521 */
d25ce370
TB
522int mem_printf_hook(char *dst, size_t dstlen,
523 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
524{
525 char *bytes = *((void**)(args[0]));
817ab8a8 526 u_int len = *((int*)(args[1]));
7daf5226 527
552cc11b
MW
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;
7daf5226 536
817ab8a8 537 written += print_in_hook(dst, dstlen, "=> %u bytes @ %p", len, bytes);
7daf5226 538
552cc11b
MW
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
7daf5226 547 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
548 {
549 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 550
552cc11b
MW
551 while (padding--)
552 {
553 *buffer_pos++ = ' ';
554 }
555 *buffer_pos++ = '\0';
556 ascii_buffer[i] = '\0';
7daf5226 557
d25ce370 558 written += print_in_hook(dst, dstlen, "\n%4d: %s %s",
323f9f99 559 line_start, buffer, ascii_buffer);
7daf5226 560
552cc11b
MW
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}