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