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