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