]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils/utils.c
make TNC Access Requestor ID available to IMVs
[people/ms/strongswan.git] / src / libstrongswan / utils / 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
12642a68 30#include "collections/enumerator.h"
f05b4272 31#include "utils/debug.h"
552cc11b 32
a8809bb0 33ENUM(status_names, SUCCESS, NEED_MORE,
552cc11b
MW
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 */
51void *clalloc(void * pointer, size_t size)
52{
53 void *data;
54 data = malloc(size);
7daf5226 55
552cc11b 56 memcpy(data, pointer, size);
7daf5226 57
552cc11b
MW
58 return (data);
59}
60
61/**
62 * Described in header.
63 */
01e43e31 64void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
552cc11b 65{
01e43e31 66 int m, i;
7daf5226 67
01e43e31 68 /* byte wise XOR until dst aligned */
09846603 69 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
4fd233a7 70 {
01e43e31 71 dst[i] ^= src[i];
4fd233a7 72 }
01e43e31 73 /* try to use words if src shares an aligment with dst */
74b14b40 74 switch (((uintptr_t)&src[i] % sizeof(long)))
552cc11b 75 {
01e43e31
MW
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];
552cc11b
MW
101 }
102}
103
ed678b52
MW
104/**
105 * Described in header.
106 */
107void memwipe_noinline(void *ptr, size_t n)
108{
109 memwipe_inline(ptr, n);
110}
111
81736d7d
TB
112/**
113 * Described in header.
114 */
115void *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
d543d9ca
TB
129/**
130 * Described in header.
131 */
132char* 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
6c20579a
TB
151/**
152 * Described in header.
153 */
154bool mkdir_p(const char *path, mode_t mode)
155{
fc1afcc8 156 int len;
6c20579a
TB
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 {
8b0e0910 166 DBG1(DBG_LIB, "path string %s too long", path);
6c20579a
TB
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 {
8b0e0910 187 DBG1(DBG_LIB, "failed to create directory %s", full);
6c20579a
TB
188 return FALSE;
189 }
190 }
191 *pos = '/';
192 pos++;
193 }
194 return TRUE;
195}
196
2a595276
TB
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 */
206static pthread_key_t strerror_buf_key;
207
208/**
209 * Only initialize the key above once
210 */
211static pthread_once_t strerror_buf_key_once = PTHREAD_ONCE_INIT;
212
213/**
214 * Create the key used for the thread-specific error buffer
215 */
216static 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 */
224static 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 */
242const 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 */
bbbffac3
TB
256/* we actually wan't to call strerror(3) below */
257#undef strerror
2a595276
TB
258/*
259 * Described in header.
260 */
261const 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
9a8fdc15
TB
276#ifndef HAVE_CLOSEFROM
277/**
278 * Described in header.
279 */
280void closefrom(int lowfd)
281{
5051bd23
TB
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());
4a4cf41b 287 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
5051bd23
TB
288 {
289 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
290 if (enumerator)
291 {
68fcf917 292 char *rel;
5051bd23
TB
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 */
9a8fdc15
TB
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
3f310c0d
MW
319/**
320 * Return monotonic time
321 */
322time_t time_monotonic(timeval_t *tv)
323{
b2944d71
TB
324#if defined(HAVE_CLOCK_GETTIME) && \
325 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
326 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
327 /* as we use time_monotonic() for condvar operations, we use the
328 * monotonic time source only if it is also supported by pthread. */
3f310c0d 329 timespec_t ts;
7daf5226 330
3f310c0d
MW
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 }
b2944d71 340#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
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.
3d5818ec
MW
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! */
3f310c0d
MW
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
081ae2eb
MW
357/**
358 * return null
359 */
360void *return_null()
361{
362 return NULL;
363}
364
da17b016
MW
365/**
366 * returns TRUE
367 */
368bool return_true()
369{
370 return TRUE;
371}
372
373/**
374 * returns FALSE
375 */
376bool return_false()
377{
378 return FALSE;
379}
380
502edf42
MW
381/**
382 * returns FAILED
383 */
384status_t return_failed()
385{
386 return FAILED;
387}
388
4755ab50
MW
389/**
390 * returns SUCCESS
391 */
392status_t return_success()
393{
394 return SUCCESS;
395}
396
233b853d
MW
397/**
398 * nop operation
399 */
400void nop()
401{
402}
403
efd0fe21 404#ifndef HAVE_GCC_ATOMIC_OPERATIONS
efd0fe21 405
552cc11b 406/**
7daf5226 407 * We use a single mutex for all refcount variables.
552cc11b
MW
408 */
409static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
410
411/**
efd0fe21 412 * Increase refcount
552cc11b
MW
413 */
414void ref_get(refcount_t *ref)
415{
416 pthread_mutex_lock(&ref_mutex);
417 (*ref)++;
418 pthread_mutex_unlock(&ref_mutex);
419}
420
421/**
efd0fe21 422 * Decrease refcount
552cc11b
MW
423 */
424bool ref_put(refcount_t *ref)
425{
426 bool more_refs;
7daf5226 427
552cc11b 428 pthread_mutex_lock(&ref_mutex);
21f411b8 429 more_refs = --(*ref) > 0;
552cc11b
MW
430 pthread_mutex_unlock(&ref_mutex);
431 return !more_refs;
432}
5317dd68
TB
433
434/**
435 * Single mutex for all compare and swap operations.
436 */
437static 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) \
443bool 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
efd0fe21 455#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
552cc11b
MW
456
457/**
d25ce370 458 * Described in header.
552cc11b 459 */
1b40b74d 460int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 461 const void *const *args)
552cc11b
MW
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]));
d25ce370 468 bool utc = *((bool*)(args[1]));;
552cc11b 469 struct tm t;
7daf5226 470
cf29fc07 471 if (*time == UNDEFINED_TIME)
552cc11b 472 {
1b40b74d 473 return print_in_hook(data, "--- -- --:--:--%s----",
d25ce370 474 utc ? " UTC " : " ");
552cc11b
MW
475 }
476 if (utc)
477 {
478 gmtime_r(time, &t);
479 }
480 else
481 {
482 localtime_r(time, &t);
483 }
1b40b74d 484 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
d25ce370
TB
485 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
486 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
552cc11b
MW
487}
488
489/**
d25ce370 490 * Described in header.
552cc11b 491 */
1b40b74d 492int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 493 const void *const *args)
552cc11b
MW
494{
495 char* unit = "second";
d25ce370
TB
496 time_t *arg1 = *((time_t**)(args[0]));
497 time_t *arg2 = *((time_t**)(args[1]));
876961cf 498 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 499
552cc11b
MW
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 }
1b40b74d 515 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
876961cf 516 (delta == 1) ? "" : "s");
552cc11b
MW
517}
518
519/**
520 * Number of bytes per line to dump raw data
521 */
522#define BYTES_PER_LINE 16
523
524static char hexdig_upper[] = "0123456789ABCDEF";
525
526/**
d25ce370 527 * Described in header.
552cc11b 528 */
1b40b74d 529int mem_printf_hook(printf_hook_data_t *data,
d25ce370 530 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
531{
532 char *bytes = *((void**)(args[0]));
817ab8a8 533 u_int len = *((int*)(args[1]));
7daf5226 534
552cc11b
MW
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;
7daf5226 543
1b40b74d 544 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
7daf5226 545
552cc11b
MW
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
7daf5226 554 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
555 {
556 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 557
552cc11b
MW
558 while (padding--)
559 {
560 *buffer_pos++ = ' ';
561 }
562 *buffer_pos++ = '\0';
563 ascii_buffer[i] = '\0';
7daf5226 564
1b40b74d 565 written += print_in_hook(data, "\n%4d: %s %s",
323f9f99 566 line_start, buffer, ascii_buffer);
7daf5226 567
552cc11b
MW
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}