]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils.c
Show some uname() info in "ipsec statusall"
[people/ms/strongswan.git] / src / libstrongswan / utils.c
CommitLineData
552cc11b 1/*
9a8fdc15 2 * Copyright (C) 2008-2011 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>
552cc11b 28
fac3bfa5
TB
29#include "enum.h"
30#include "debug.h"
5051bd23 31#include "utils/enumerator.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
9a8fdc15
TB
197#ifndef HAVE_CLOSEFROM
198/**
199 * Described in header.
200 */
201void closefrom(int lowfd)
202{
5051bd23
TB
203 char fd_dir[PATH_MAX];
204 int maxfd, fd, len;
205
206 /* try to close only open file descriptors on Linux... */
207 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
4a4cf41b 208 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
5051bd23
TB
209 {
210 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
211 if (enumerator)
212 {
68fcf917 213 char *rel;
5051bd23
TB
214 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
215 {
216 fd = atoi(rel);
217 if (fd >= lowfd)
218 {
219 close(fd);
220 }
221 }
222 enumerator->destroy(enumerator);
223 return;
224 }
225 }
226
227 /* ...fall back to closing all fds otherwise */
9a8fdc15
TB
228 maxfd = (int)sysconf(_SC_OPEN_MAX);
229 if (maxfd < 0)
230 {
231 maxfd = 256;
232 }
233 for (fd = lowfd; fd < maxfd; fd++)
234 {
235 close(fd);
236 }
237}
238#endif /* HAVE_CLOSEFROM */
239
3f310c0d
MW
240/**
241 * Return monotonic time
242 */
243time_t time_monotonic(timeval_t *tv)
244{
b2944d71
TB
245#if defined(HAVE_CLOCK_GETTIME) && \
246 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
247 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
248 /* as we use time_monotonic() for condvar operations, we use the
249 * monotonic time source only if it is also supported by pthread. */
3f310c0d 250 timespec_t ts;
7daf5226 251
3f310c0d
MW
252 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
253 {
254 if (tv)
255 {
256 tv->tv_sec = ts.tv_sec;
257 tv->tv_usec = ts.tv_nsec / 1000;
258 }
259 return ts.tv_sec;
260 }
b2944d71 261#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
262 /* Fallback to non-monotonic timestamps:
263 * On MAC OS X, creating monotonic timestamps is rather difficult. We
264 * could use mach_absolute_time() and catch sleep/wakeup notifications.
3d5818ec
MW
265 * We stick to the simpler (non-monotonic) gettimeofday() for now.
266 * But keep in mind: we need the same time source here as in condvar! */
3f310c0d
MW
267 if (!tv)
268 {
269 return time(NULL);
270 }
271 if (gettimeofday(tv, NULL) != 0)
272 { /* should actually never fail if passed pointers are valid */
273 return -1;
274 }
275 return tv->tv_sec;
276}
277
081ae2eb
MW
278/**
279 * return null
280 */
281void *return_null()
282{
283 return NULL;
284}
285
da17b016
MW
286/**
287 * returns TRUE
288 */
289bool return_true()
290{
291 return TRUE;
292}
293
294/**
295 * returns FALSE
296 */
297bool return_false()
298{
299 return FALSE;
300}
301
502edf42
MW
302/**
303 * returns FAILED
304 */
305status_t return_failed()
306{
307 return FAILED;
308}
309
233b853d
MW
310/**
311 * nop operation
312 */
313void nop()
314{
315}
316
efd0fe21
MW
317#ifndef HAVE_GCC_ATOMIC_OPERATIONS
318#include <pthread.h>
319
552cc11b 320/**
7daf5226 321 * We use a single mutex for all refcount variables.
552cc11b
MW
322 */
323static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
324
325/**
efd0fe21 326 * Increase refcount
552cc11b
MW
327 */
328void ref_get(refcount_t *ref)
329{
330 pthread_mutex_lock(&ref_mutex);
331 (*ref)++;
332 pthread_mutex_unlock(&ref_mutex);
333}
334
335/**
efd0fe21 336 * Decrease refcount
552cc11b
MW
337 */
338bool ref_put(refcount_t *ref)
339{
340 bool more_refs;
7daf5226 341
552cc11b 342 pthread_mutex_lock(&ref_mutex);
21f411b8 343 more_refs = --(*ref) > 0;
552cc11b
MW
344 pthread_mutex_unlock(&ref_mutex);
345 return !more_refs;
346}
5317dd68
TB
347
348/**
349 * Single mutex for all compare and swap operations.
350 */
351static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
352
353/**
354 * Compare and swap if equal to old value
355 */
356#define _cas_impl(name, type) \
357bool cas_##name(type *ptr, type oldval, type newval) \
358{ \
359 bool swapped; \
360 pthread_mutex_lock(&cas_mutex); \
361 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
362 pthread_mutex_unlock(&cas_mutex); \
363 return swapped; \
364}
365
366_cas_impl(bool, bool)
367_cas_impl(ptr, void*)
368
efd0fe21 369#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
552cc11b
MW
370
371/**
d25ce370 372 * Described in header.
552cc11b 373 */
d25ce370
TB
374int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
375 const void *const *args)
552cc11b
MW
376{
377 static const char* months[] = {
378 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
379 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
380 };
381 time_t *time = *((time_t**)(args[0]));
d25ce370 382 bool utc = *((bool*)(args[1]));;
552cc11b 383 struct tm t;
7daf5226 384
552cc11b
MW
385 if (time == UNDEFINED_TIME)
386 {
d25ce370
TB
387 return print_in_hook(dst, len, "--- -- --:--:--%s----",
388 utc ? " UTC " : " ");
552cc11b
MW
389 }
390 if (utc)
391 {
392 gmtime_r(time, &t);
393 }
394 else
395 {
396 localtime_r(time, &t);
397 }
d25ce370
TB
398 return print_in_hook(dst, len, "%s %02d %02d:%02d:%02d%s%04d",
399 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
400 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
552cc11b
MW
401}
402
403/**
d25ce370 404 * Described in header.
552cc11b 405 */
d25ce370
TB
406int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
407 const void *const *args)
552cc11b
MW
408{
409 char* unit = "second";
d25ce370
TB
410 time_t *arg1 = *((time_t**)(args[0]));
411 time_t *arg2 = *((time_t**)(args[1]));
876961cf 412 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 413
552cc11b
MW
414 if (delta > 2 * 60 * 60 * 24)
415 {
416 delta /= 60 * 60 * 24;
417 unit = "day";
418 }
419 else if (delta > 2 * 60 * 60)
420 {
421 delta /= 60 * 60;
422 unit = "hour";
423 }
424 else if (delta > 2 * 60)
425 {
426 delta /= 60;
427 unit = "minute";
428 }
876961cf
TB
429 return print_in_hook(dst, len, "%" PRIu64 " %s%s", delta, unit,
430 (delta == 1) ? "" : "s");
552cc11b
MW
431}
432
433/**
434 * Number of bytes per line to dump raw data
435 */
436#define BYTES_PER_LINE 16
437
438static char hexdig_upper[] = "0123456789ABCDEF";
439
440/**
d25ce370 441 * Described in header.
552cc11b 442 */
d25ce370
TB
443int mem_printf_hook(char *dst, size_t dstlen,
444 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
445{
446 char *bytes = *((void**)(args[0]));
817ab8a8 447 u_int len = *((int*)(args[1]));
7daf5226 448
552cc11b
MW
449 char buffer[BYTES_PER_LINE * 3];
450 char ascii_buffer[BYTES_PER_LINE + 1];
451 char *buffer_pos = buffer;
452 char *bytes_pos = bytes;
453 char *bytes_roof = bytes + len;
454 int line_start = 0;
455 int i = 0;
456 int written = 0;
7daf5226 457
817ab8a8 458 written += print_in_hook(dst, dstlen, "=> %u bytes @ %p", len, bytes);
7daf5226 459
552cc11b
MW
460 while (bytes_pos < bytes_roof)
461 {
462 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
463 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
464
465 ascii_buffer[i++] =
466 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
467
7daf5226 468 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
469 {
470 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 471
552cc11b
MW
472 while (padding--)
473 {
474 *buffer_pos++ = ' ';
475 }
476 *buffer_pos++ = '\0';
477 ascii_buffer[i] = '\0';
7daf5226 478
d25ce370 479 written += print_in_hook(dst, dstlen, "\n%4d: %s %s",
323f9f99 480 line_start, buffer, ascii_buffer);
7daf5226 481
552cc11b
MW
482 buffer_pos = buffer;
483 line_start += BYTES_PER_LINE;
484 i = 0;
485 }
486 else
487 {
488 *buffer_pos++ = ' ';
489 }
490 }
491 return written;
492}