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