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