]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils/utils.c
windows: Link libstrongswan against ws2_32.dll
[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:
366 case TTY_FG_BLACK:
367 case TTY_FG_RED:
368 case TTY_FG_GREEN:
369 case TTY_FG_YELLOW:
370 case TTY_FG_BLUE:
371 case TTY_FG_MAGENTA:
372 case TTY_FG_CYAN:
373 case TTY_FG_WHITE:
374 case TTY_FG_DEF:
375 case TTY_BG_BLACK:
376 case TTY_BG_RED:
377 case TTY_BG_GREEN:
378 case TTY_BG_YELLOW:
379 case TTY_BG_BLUE:
380 case TTY_BG_MAGENTA:
381 case TTY_BG_CYAN:
382 case TTY_BG_WHITE:
383 case TTY_BG_DEF:
384 return enum_to_name(tty_color_names, escape);
385 /* warn if a excape code is missing */
386 }
387 return "";
388}
2a595276 389
9a8fdc15
TB
390#ifndef HAVE_CLOSEFROM
391/**
392 * Described in header.
393 */
394void closefrom(int lowfd)
395{
5051bd23
TB
396 char fd_dir[PATH_MAX];
397 int maxfd, fd, len;
398
399 /* try to close only open file descriptors on Linux... */
400 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
4a4cf41b 401 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
5051bd23
TB
402 {
403 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
404 if (enumerator)
405 {
68fcf917 406 char *rel;
5051bd23
TB
407 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
408 {
409 fd = atoi(rel);
410 if (fd >= lowfd)
411 {
412 close(fd);
413 }
414 }
415 enumerator->destroy(enumerator);
416 return;
417 }
418 }
419
420 /* ...fall back to closing all fds otherwise */
d3c30b35
MW
421#ifdef WIN32
422 maxfd = _getmaxstdio();
423#else
9a8fdc15 424 maxfd = (int)sysconf(_SC_OPEN_MAX);
d3c30b35 425#endif
9a8fdc15
TB
426 if (maxfd < 0)
427 {
428 maxfd = 256;
429 }
430 for (fd = lowfd; fd < maxfd; fd++)
431 {
432 close(fd);
433 }
434}
435#endif /* HAVE_CLOSEFROM */
436
3f310c0d
MW
437/**
438 * Return monotonic time
439 */
440time_t time_monotonic(timeval_t *tv)
441{
b2944d71
TB
442#if defined(HAVE_CLOCK_GETTIME) && \
443 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
444 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
445 /* as we use time_monotonic() for condvar operations, we use the
446 * monotonic time source only if it is also supported by pthread. */
3f310c0d 447 timespec_t ts;
7daf5226 448
3f310c0d
MW
449 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
450 {
451 if (tv)
452 {
453 tv->tv_sec = ts.tv_sec;
454 tv->tv_usec = ts.tv_nsec / 1000;
455 }
456 return ts.tv_sec;
457 }
b2944d71 458#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
459 /* Fallback to non-monotonic timestamps:
460 * On MAC OS X, creating monotonic timestamps is rather difficult. We
461 * could use mach_absolute_time() and catch sleep/wakeup notifications.
3d5818ec
MW
462 * We stick to the simpler (non-monotonic) gettimeofday() for now.
463 * But keep in mind: we need the same time source here as in condvar! */
3f310c0d
MW
464 if (!tv)
465 {
466 return time(NULL);
467 }
468 if (gettimeofday(tv, NULL) != 0)
469 { /* should actually never fail if passed pointers are valid */
470 return -1;
471 }
472 return tv->tv_sec;
473}
474
081ae2eb
MW
475/**
476 * return null
477 */
478void *return_null()
479{
480 return NULL;
481}
482
da17b016
MW
483/**
484 * returns TRUE
485 */
486bool return_true()
487{
488 return TRUE;
489}
490
491/**
492 * returns FALSE
493 */
494bool return_false()
495{
496 return FALSE;
497}
498
502edf42
MW
499/**
500 * returns FAILED
501 */
502status_t return_failed()
503{
504 return FAILED;
505}
506
4755ab50
MW
507/**
508 * returns SUCCESS
509 */
510status_t return_success()
511{
512 return SUCCESS;
513}
514
233b853d
MW
515/**
516 * nop operation
517 */
518void nop()
519{
520}
521
0f603d42 522#if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
efd0fe21 523
552cc11b 524/**
7daf5226 525 * We use a single mutex for all refcount variables.
552cc11b
MW
526 */
527static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
528
529/**
efd0fe21 530 * Increase refcount
552cc11b 531 */
3160b92a 532refcount_t ref_get(refcount_t *ref)
552cc11b 533{
3160b92a
MW
534 refcount_t current;
535
552cc11b 536 pthread_mutex_lock(&ref_mutex);
3160b92a 537 current = ++(*ref);
552cc11b 538 pthread_mutex_unlock(&ref_mutex);
3160b92a 539 return current;
552cc11b
MW
540}
541
542/**
efd0fe21 543 * Decrease refcount
552cc11b
MW
544 */
545bool ref_put(refcount_t *ref)
546{
547 bool more_refs;
7daf5226 548
552cc11b 549 pthread_mutex_lock(&ref_mutex);
21f411b8 550 more_refs = --(*ref) > 0;
552cc11b
MW
551 pthread_mutex_unlock(&ref_mutex);
552 return !more_refs;
553}
5317dd68 554
efedd0d2
TB
555/**
556 * Current refcount
557 */
558refcount_t ref_cur(refcount_t *ref)
559{
560 refcount_t current;
561
562 pthread_mutex_lock(&ref_mutex);
563 current = *ref;
564 pthread_mutex_unlock(&ref_mutex);
565 return current;
566}
567
5317dd68
TB
568/**
569 * Single mutex for all compare and swap operations.
570 */
571static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
572
573/**
574 * Compare and swap if equal to old value
575 */
576#define _cas_impl(name, type) \
577bool cas_##name(type *ptr, type oldval, type newval) \
578{ \
579 bool swapped; \
580 pthread_mutex_lock(&cas_mutex); \
581 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
582 pthread_mutex_unlock(&cas_mutex); \
583 return swapped; \
584}
585
586_cas_impl(bool, bool)
587_cas_impl(ptr, void*)
588
0f603d42 589#endif /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
552cc11b 590
2077d996 591
9df621d2 592#ifdef HAVE_FMEMOPEN_FALLBACK
2077d996
MW
593
594static int fmemread(chunk_t *cookie, char *buf, int size)
595{
596 int len;
597
598 len = min(size, cookie->len);
599 memcpy(buf, cookie->ptr, len);
600 *cookie = chunk_skip(*cookie, len);
601
602 return len;
603}
604
605static int fmemwrite(chunk_t *cookie, const char *buf, int size)
606{
607 int len;
608
609 len = min(size, cookie->len);
610 memcpy(cookie->ptr, buf, len);
611 *cookie = chunk_skip(*cookie, len);
612
613 return len;
614}
615
616static int fmemclose(void *cookie)
617{
618 free(cookie);
619 return 0;
620}
621
622FILE *fmemopen(void *buf, size_t size, const char *mode)
623{
624 chunk_t *cookie;
625
626 INIT(cookie,
627 .ptr = buf,
628 .len = size,
629 );
630
631 return funopen(cookie, (void*)fmemread, (void*)fmemwrite, NULL, fmemclose);
632}
633
634#endif /* FMEMOPEN fallback*/
635
552cc11b 636/**
d25ce370 637 * Described in header.
552cc11b 638 */
1b40b74d 639int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 640 const void *const *args)
552cc11b
MW
641{
642 static const char* months[] = {
643 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
644 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
645 };
646 time_t *time = *((time_t**)(args[0]));
13f2d3a2 647 bool utc = *((int*)(args[1]));
552cc11b 648 struct tm t;
7daf5226 649
cf29fc07 650 if (*time == UNDEFINED_TIME)
552cc11b 651 {
1b40b74d 652 return print_in_hook(data, "--- -- --:--:--%s----",
d25ce370 653 utc ? " UTC " : " ");
552cc11b
MW
654 }
655 if (utc)
656 {
657 gmtime_r(time, &t);
658 }
659 else
660 {
661 localtime_r(time, &t);
662 }
1b40b74d 663 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
d25ce370
TB
664 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
665 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
552cc11b
MW
666}
667
668/**
d25ce370 669 * Described in header.
552cc11b 670 */
1b40b74d 671int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 672 const void *const *args)
552cc11b
MW
673{
674 char* unit = "second";
d25ce370
TB
675 time_t *arg1 = *((time_t**)(args[0]));
676 time_t *arg2 = *((time_t**)(args[1]));
876961cf 677 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 678
552cc11b
MW
679 if (delta > 2 * 60 * 60 * 24)
680 {
681 delta /= 60 * 60 * 24;
682 unit = "day";
683 }
684 else if (delta > 2 * 60 * 60)
685 {
686 delta /= 60 * 60;
687 unit = "hour";
688 }
689 else if (delta > 2 * 60)
690 {
691 delta /= 60;
692 unit = "minute";
693 }
1b40b74d 694 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
876961cf 695 (delta == 1) ? "" : "s");
552cc11b
MW
696}
697
698/**
699 * Number of bytes per line to dump raw data
700 */
701#define BYTES_PER_LINE 16
702
703static char hexdig_upper[] = "0123456789ABCDEF";
704
705/**
d25ce370 706 * Described in header.
552cc11b 707 */
1b40b74d 708int mem_printf_hook(printf_hook_data_t *data,
d25ce370 709 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
710{
711 char *bytes = *((void**)(args[0]));
817ab8a8 712 u_int len = *((int*)(args[1]));
7daf5226 713
552cc11b
MW
714 char buffer[BYTES_PER_LINE * 3];
715 char ascii_buffer[BYTES_PER_LINE + 1];
716 char *buffer_pos = buffer;
717 char *bytes_pos = bytes;
718 char *bytes_roof = bytes + len;
719 int line_start = 0;
720 int i = 0;
721 int written = 0;
7daf5226 722
1b40b74d 723 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
7daf5226 724
552cc11b
MW
725 while (bytes_pos < bytes_roof)
726 {
727 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
728 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
729
730 ascii_buffer[i++] =
731 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
732
7daf5226 733 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
734 {
735 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 736
552cc11b
MW
737 while (padding--)
738 {
739 *buffer_pos++ = ' ';
740 }
741 *buffer_pos++ = '\0';
742 ascii_buffer[i] = '\0';
7daf5226 743
1b40b74d 744 written += print_in_hook(data, "\n%4d: %s %s",
323f9f99 745 line_start, buffer, ascii_buffer);
7daf5226 746
552cc11b
MW
747 buffer_pos = buffer;
748 line_start += BYTES_PER_LINE;
749 i = 0;
750 }
751 else
752 {
753 *buffer_pos++ = ' ';
754 }
755 }
756 return written;
757}