Merge branch 'atomic-ref'
[strongswan.git] / src / libstrongswan / utils / utils.c
1 /*
2 * Copyright (C) 2008-2014 Tobias Brunner
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.
15 */
16
17 #define _GNU_SOURCE /* for memrchr */
18 #include <sys/stat.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <unistd.h>
22 #include <inttypes.h>
23 #include <stdint.h>
24 #include <limits.h>
25 #include <dirent.h>
26 #include <time.h>
27 #include <pthread.h>
28
29 #include "utils.h"
30
31 #include "collections/enumerator.h"
32 #include "utils/debug.h"
33 #include "utils/chunk.h"
34
35 ENUM(status_names, SUCCESS, NEED_MORE,
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
50 /**
51 * Described in header.
52 */
53 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
54 {
55 int m, i;
56
57 /* byte wise XOR until dst aligned */
58 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
59 {
60 dst[i] ^= src[i];
61 }
62 /* try to use words if src shares an aligment with dst */
63 switch (((uintptr_t)&src[i] % sizeof(long)))
64 {
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];
90 }
91 }
92
93 /**
94 * Described in header.
95 */
96 void memwipe_noinline(void *ptr, size_t n)
97 {
98 memwipe_inline(ptr, n);
99 }
100
101 /**
102 * Described in header.
103 */
104 void *memstr(const void *haystack, const char *needle, size_t n)
105 {
106 const u_char *pos = haystack;
107 size_t l;
108
109 if (!haystack || !needle || (l = strlen(needle)) == 0)
110 {
111 return NULL;
112 }
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
123 /**
124 * Described in header.
125 */
126 void *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
145 /**
146 * Described in header.
147 */
148 char* 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;
165 }
166
167 /**
168 * Described in header.
169 */
170 char* 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;
217 }
218
219 /**
220 * Described in header.
221 */
222 char* 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 */
250 char* 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
276 /**
277 * Described in header.
278 */
279 bool mkdir_p(const char *path, mode_t mode)
280 {
281 int len;
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 {
291 DBG1(DBG_LIB, "path string %s too long", path);
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 {
310 if (mkdir(full, mode) < 0)
311 {
312 DBG1(DBG_LIB, "failed to create directory %s", full);
313 return FALSE;
314 }
315 }
316 *pos = '/';
317 pos++;
318 }
319 return TRUE;
320 }
321
322 ENUM(tty_color_names, TTY_RESET, TTY_BG_DEF,
323 "\e[0m",
324 "\e[1m",
325 "\e[4m",
326 "\e[5m",
327 "\e[30m",
328 "\e[31m",
329 "\e[32m",
330 "\e[33m",
331 "\e[34m",
332 "\e[35m",
333 "\e[36m",
334 "\e[37m",
335 "\e[39m",
336 "\e[40m",
337 "\e[41m",
338 "\e[42m",
339 "\e[43m",
340 "\e[44m",
341 "\e[45m",
342 "\e[46m",
343 "\e[47m",
344 "\e[49m",
345 );
346
347 /**
348 * Get the escape string for a given TTY color, empty string on non-tty FILE
349 */
350 char* tty_escape_get(int fd, tty_escape_t escape)
351 {
352 if (!isatty(fd))
353 {
354 return "";
355 }
356 switch (escape)
357 {
358 case TTY_RESET:
359 case TTY_BOLD:
360 case TTY_UNDERLINE:
361 case TTY_BLINKING:
362 case TTY_FG_BLACK:
363 case TTY_FG_RED:
364 case TTY_FG_GREEN:
365 case TTY_FG_YELLOW:
366 case TTY_FG_BLUE:
367 case TTY_FG_MAGENTA:
368 case TTY_FG_CYAN:
369 case TTY_FG_WHITE:
370 case TTY_FG_DEF:
371 case TTY_BG_BLACK:
372 case TTY_BG_RED:
373 case TTY_BG_GREEN:
374 case TTY_BG_YELLOW:
375 case TTY_BG_BLUE:
376 case TTY_BG_MAGENTA:
377 case TTY_BG_CYAN:
378 case TTY_BG_WHITE:
379 case TTY_BG_DEF:
380 return enum_to_name(tty_color_names, escape);
381 /* warn if a excape code is missing */
382 }
383 return "";
384 }
385
386 #ifndef HAVE_CLOSEFROM
387 /**
388 * Described in header.
389 */
390 void closefrom(int lowfd)
391 {
392 char fd_dir[PATH_MAX];
393 int maxfd, fd, len;
394
395 /* try to close only open file descriptors on Linux... */
396 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
397 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
398 {
399 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
400 if (enumerator)
401 {
402 char *rel;
403 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
404 {
405 fd = atoi(rel);
406 if (fd >= lowfd)
407 {
408 close(fd);
409 }
410 }
411 enumerator->destroy(enumerator);
412 return;
413 }
414 }
415
416 /* ...fall back to closing all fds otherwise */
417 maxfd = (int)sysconf(_SC_OPEN_MAX);
418 if (maxfd < 0)
419 {
420 maxfd = 256;
421 }
422 for (fd = lowfd; fd < maxfd; fd++)
423 {
424 close(fd);
425 }
426 }
427 #endif /* HAVE_CLOSEFROM */
428
429 /**
430 * Return monotonic time
431 */
432 time_t time_monotonic(timeval_t *tv)
433 {
434 #if defined(HAVE_CLOCK_GETTIME) && \
435 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
436 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
437 /* as we use time_monotonic() for condvar operations, we use the
438 * monotonic time source only if it is also supported by pthread. */
439 timespec_t ts;
440
441 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
442 {
443 if (tv)
444 {
445 tv->tv_sec = ts.tv_sec;
446 tv->tv_usec = ts.tv_nsec / 1000;
447 }
448 return ts.tv_sec;
449 }
450 #endif /* HAVE_CLOCK_GETTIME && (...) */
451 /* Fallback to non-monotonic timestamps:
452 * On MAC OS X, creating monotonic timestamps is rather difficult. We
453 * could use mach_absolute_time() and catch sleep/wakeup notifications.
454 * We stick to the simpler (non-monotonic) gettimeofday() for now.
455 * But keep in mind: we need the same time source here as in condvar! */
456 if (!tv)
457 {
458 return time(NULL);
459 }
460 if (gettimeofday(tv, NULL) != 0)
461 { /* should actually never fail if passed pointers are valid */
462 return -1;
463 }
464 return tv->tv_sec;
465 }
466
467 /**
468 * return null
469 */
470 void *return_null()
471 {
472 return NULL;
473 }
474
475 /**
476 * returns TRUE
477 */
478 bool return_true()
479 {
480 return TRUE;
481 }
482
483 /**
484 * returns FALSE
485 */
486 bool return_false()
487 {
488 return FALSE;
489 }
490
491 /**
492 * returns FAILED
493 */
494 status_t return_failed()
495 {
496 return FAILED;
497 }
498
499 /**
500 * returns SUCCESS
501 */
502 status_t return_success()
503 {
504 return SUCCESS;
505 }
506
507 /**
508 * nop operation
509 */
510 void nop()
511 {
512 }
513
514 #if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
515
516 /**
517 * We use a single mutex for all refcount variables.
518 */
519 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
520
521 /**
522 * Increase refcount
523 */
524 refcount_t ref_get(refcount_t *ref)
525 {
526 refcount_t current;
527
528 pthread_mutex_lock(&ref_mutex);
529 current = ++(*ref);
530 pthread_mutex_unlock(&ref_mutex);
531 return current;
532 }
533
534 /**
535 * Decrease refcount
536 */
537 bool ref_put(refcount_t *ref)
538 {
539 bool more_refs;
540
541 pthread_mutex_lock(&ref_mutex);
542 more_refs = --(*ref) > 0;
543 pthread_mutex_unlock(&ref_mutex);
544 return !more_refs;
545 }
546
547 /**
548 * Current refcount
549 */
550 refcount_t ref_cur(refcount_t *ref)
551 {
552 refcount_t current;
553
554 pthread_mutex_lock(&ref_mutex);
555 current = *ref;
556 pthread_mutex_unlock(&ref_mutex);
557 return current;
558 }
559
560 /**
561 * Single mutex for all compare and swap operations.
562 */
563 static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
564
565 /**
566 * Compare and swap if equal to old value
567 */
568 #define _cas_impl(name, type) \
569 bool cas_##name(type *ptr, type oldval, type newval) \
570 { \
571 bool swapped; \
572 pthread_mutex_lock(&cas_mutex); \
573 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
574 pthread_mutex_unlock(&cas_mutex); \
575 return swapped; \
576 }
577
578 _cas_impl(bool, bool)
579 _cas_impl(ptr, void*)
580
581 #endif /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
582
583
584 #ifdef HAVE_FMEMOPEN_FALLBACK
585
586 static int fmemread(chunk_t *cookie, char *buf, int size)
587 {
588 int len;
589
590 len = min(size, cookie->len);
591 memcpy(buf, cookie->ptr, len);
592 *cookie = chunk_skip(*cookie, len);
593
594 return len;
595 }
596
597 static int fmemwrite(chunk_t *cookie, const char *buf, int size)
598 {
599 int len;
600
601 len = min(size, cookie->len);
602 memcpy(cookie->ptr, buf, len);
603 *cookie = chunk_skip(*cookie, len);
604
605 return len;
606 }
607
608 static int fmemclose(void *cookie)
609 {
610 free(cookie);
611 return 0;
612 }
613
614 FILE *fmemopen(void *buf, size_t size, const char *mode)
615 {
616 chunk_t *cookie;
617
618 INIT(cookie,
619 .ptr = buf,
620 .len = size,
621 );
622
623 return funopen(cookie, (void*)fmemread, (void*)fmemwrite, NULL, fmemclose);
624 }
625
626 #endif /* FMEMOPEN fallback*/
627
628 /**
629 * Described in header.
630 */
631 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
632 const void *const *args)
633 {
634 static const char* months[] = {
635 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
636 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
637 };
638 time_t *time = *((time_t**)(args[0]));
639 bool utc = *((int*)(args[1]));
640 struct tm t;
641
642 if (*time == UNDEFINED_TIME)
643 {
644 return print_in_hook(data, "--- -- --:--:--%s----",
645 utc ? " UTC " : " ");
646 }
647 if (utc)
648 {
649 gmtime_r(time, &t);
650 }
651 else
652 {
653 localtime_r(time, &t);
654 }
655 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
656 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
657 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
658 }
659
660 /**
661 * Described in header.
662 */
663 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
664 const void *const *args)
665 {
666 char* unit = "second";
667 time_t *arg1 = *((time_t**)(args[0]));
668 time_t *arg2 = *((time_t**)(args[1]));
669 u_int64_t delta = llabs(*arg1 - *arg2);
670
671 if (delta > 2 * 60 * 60 * 24)
672 {
673 delta /= 60 * 60 * 24;
674 unit = "day";
675 }
676 else if (delta > 2 * 60 * 60)
677 {
678 delta /= 60 * 60;
679 unit = "hour";
680 }
681 else if (delta > 2 * 60)
682 {
683 delta /= 60;
684 unit = "minute";
685 }
686 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
687 (delta == 1) ? "" : "s");
688 }
689
690 /**
691 * Number of bytes per line to dump raw data
692 */
693 #define BYTES_PER_LINE 16
694
695 static char hexdig_upper[] = "0123456789ABCDEF";
696
697 /**
698 * Described in header.
699 */
700 int mem_printf_hook(printf_hook_data_t *data,
701 printf_hook_spec_t *spec, const void *const *args)
702 {
703 char *bytes = *((void**)(args[0]));
704 u_int len = *((int*)(args[1]));
705
706 char buffer[BYTES_PER_LINE * 3];
707 char ascii_buffer[BYTES_PER_LINE + 1];
708 char *buffer_pos = buffer;
709 char *bytes_pos = bytes;
710 char *bytes_roof = bytes + len;
711 int line_start = 0;
712 int i = 0;
713 int written = 0;
714
715 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
716
717 while (bytes_pos < bytes_roof)
718 {
719 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
720 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
721
722 ascii_buffer[i++] =
723 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
724
725 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
726 {
727 int padding = 3 * (BYTES_PER_LINE - i);
728
729 while (padding--)
730 {
731 *buffer_pos++ = ' ';
732 }
733 *buffer_pos++ = '\0';
734 ascii_buffer[i] = '\0';
735
736 written += print_in_hook(data, "\n%4d: %s %s",
737 line_start, buffer, ascii_buffer);
738
739 buffer_pos = buffer;
740 line_start += BYTES_PER_LINE;
741 i = 0;
742 }
743 else
744 {
745 *buffer_pos++ = ' ';
746 }
747 }
748 return written;
749 }