atomics: Move atomics/recounting support to separate files
[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 #ifdef WIN32
19 /* for GetTickCount64, Windows 7 */
20 # define _WIN32_WINNT 0x0601
21 #endif
22
23 #include "utils.h"
24
25 #include <sys/stat.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <inttypes.h>
30 #include <stdint.h>
31 #include <limits.h>
32 #include <dirent.h>
33 #include <time.h>
34 #ifndef WIN32
35 # include <signal.h>
36 #endif
37
38 #include <library.h>
39 #include <utils/debug.h>
40 #include <utils/chunk.h>
41 #include <collections/enumerator.h>
42 #include <threading/mutex.h>
43 #include <threading/condvar.h>
44
45 ENUM(status_names, SUCCESS, NEED_MORE,
46 "SUCCESS",
47 "FAILED",
48 "OUT_OF_RES",
49 "ALREADY_DONE",
50 "NOT_SUPPORTED",
51 "INVALID_ARG",
52 "NOT_FOUND",
53 "PARSE_ERROR",
54 "VERIFY_ERROR",
55 "INVALID_STATE",
56 "DESTROY_ME",
57 "NEED_MORE",
58 );
59
60 /**
61 * Described in header.
62 */
63 void* malloc_align(size_t size, u_int8_t align)
64 {
65 u_int8_t pad;
66 void *ptr;
67
68 if (align == 0)
69 {
70 align = 1;
71 }
72 ptr = malloc(align + sizeof(pad) + size);
73 if (!ptr)
74 {
75 return NULL;
76 }
77 /* store padding length just before data, down to the allocation boundary
78 * to do some verification during free_align() */
79 pad = align - ((uintptr_t)ptr % align);
80 memset(ptr, pad, pad);
81 return ptr + pad;
82 }
83
84 /**
85 * Described in header.
86 */
87 void free_align(void *ptr)
88 {
89 u_int8_t pad, *pos;
90
91 pos = ptr - 1;
92 /* verify padding to check any corruption */
93 for (pad = *pos; (void*)pos >= ptr - pad; pos--)
94 {
95 if (*pos != pad)
96 {
97 DBG1(DBG_LIB, "!!!! invalid free_align() !!!!");
98 return;
99 }
100 }
101 free(ptr - pad);
102 }
103
104 /**
105 * Described in header.
106 */
107 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
108 {
109 int m, i;
110
111 /* byte wise XOR until dst aligned */
112 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
113 {
114 dst[i] ^= src[i];
115 }
116 /* try to use words if src shares an aligment with dst */
117 switch (((uintptr_t)&src[i] % sizeof(long)))
118 {
119 case 0:
120 for (m = n - sizeof(long); i <= m; i += sizeof(long))
121 {
122 *(long*)&dst[i] ^= *(long*)&src[i];
123 }
124 break;
125 case sizeof(int):
126 for (m = n - sizeof(int); i <= m; i += sizeof(int))
127 {
128 *(int*)&dst[i] ^= *(int*)&src[i];
129 }
130 break;
131 case sizeof(short):
132 for (m = n - sizeof(short); i <= m; i += sizeof(short))
133 {
134 *(short*)&dst[i] ^= *(short*)&src[i];
135 }
136 break;
137 default:
138 break;
139 }
140 /* byte wise XOR of the rest */
141 for (; i < n; i++)
142 {
143 dst[i] ^= src[i];
144 }
145 }
146
147 /**
148 * Described in header.
149 */
150 void memwipe_noinline(void *ptr, size_t n)
151 {
152 memwipe_inline(ptr, n);
153 }
154
155 /**
156 * Described in header.
157 */
158 bool memeq_const(const void *x, const void *y, size_t len)
159 {
160 const u_char *a, *b;
161 u_int bad = 0;
162 size_t i;
163
164 a = (const u_char*)x;
165 b = (const u_char*)y;
166
167 for (i = 0; i < len; i++)
168 {
169 bad |= a[i] != b[i];
170 }
171 return !bad;
172 }
173
174 /**
175 * Described in header.
176 */
177 void *memstr(const void *haystack, const char *needle, size_t n)
178 {
179 const u_char *pos = haystack;
180 size_t l;
181
182 if (!haystack || !needle || (l = strlen(needle)) == 0)
183 {
184 return NULL;
185 }
186 for (; n >= l; ++pos, --n)
187 {
188 if (memeq(pos, needle, l))
189 {
190 return (void*)pos;
191 }
192 }
193 return NULL;
194 }
195
196 /**
197 * Described in header.
198 */
199 void *utils_memrchr(const void *s, int c, size_t n)
200 {
201 const u_char *pos;
202
203 if (!s || !n)
204 {
205 return NULL;
206 }
207
208 for (pos = s + n - 1; pos >= (u_char*)s; pos--)
209 {
210 if (*pos == (u_char)c)
211 {
212 return (void*)pos;
213 }
214 }
215 return NULL;
216 }
217
218 /**
219 * Described in header.
220 */
221 char* translate(char *str, const char *from, const char *to)
222 {
223 char *pos = str;
224 if (strlen(from) != strlen(to))
225 {
226 return str;
227 }
228 while (pos && *pos)
229 {
230 char *match;
231 if ((match = strchr(from, *pos)) != NULL)
232 {
233 *pos = to[match - from];
234 }
235 pos++;
236 }
237 return str;
238 }
239
240 /**
241 * Described in header.
242 */
243 char* strreplace(const char *str, const char *search, const char *replace)
244 {
245 size_t len, slen, rlen, count = 0;
246 char *res, *pos, *found, *dst;
247
248 if (!str || !*str || !search || !*search || !replace)
249 {
250 return (char*)str;
251 }
252 slen = strlen(search);
253 rlen = strlen(replace);
254 if (slen != rlen)
255 {
256 for (pos = (char*)str; (pos = strstr(pos, search)); pos += slen)
257 {
258 found = pos;
259 count++;
260 }
261 if (!count)
262 {
263 return (char*)str;
264 }
265 len = (found - str) + strlen(found) + count * (rlen - slen);
266 }
267 else
268 {
269 len = strlen(str);
270 }
271 found = strstr(str, search);
272 if (!found)
273 {
274 return (char*)str;
275 }
276 dst = res = malloc(len + 1);
277 pos = (char*)str;
278 do
279 {
280 len = found - pos;
281 memcpy(dst, pos, len);
282 dst += len;
283 memcpy(dst, replace, rlen);
284 dst += rlen;
285 pos = found + slen;
286 }
287 while ((found = strstr(pos, search)));
288 strcpy(dst, pos);
289 return res;
290 }
291
292 #ifdef WIN32
293
294 /**
295 * Flag to indicate signaled wait_sigint()
296 */
297 static bool sigint_signaled = FALSE;
298
299 /**
300 * Condvar to wait in wait_sigint()
301 */
302 static condvar_t *sigint_cond;
303
304 /**
305 * Mutex to check signaling()
306 */
307 static mutex_t *sigint_mutex;
308
309 /**
310 * Control handler to catch ^C
311 */
312 static BOOL WINAPI handler(DWORD dwCtrlType)
313 {
314 switch (dwCtrlType)
315 {
316 case CTRL_C_EVENT:
317 case CTRL_BREAK_EVENT:
318 case CTRL_CLOSE_EVENT:
319 sigint_mutex->lock(sigint_mutex);
320 sigint_signaled = TRUE;
321 sigint_cond->signal(sigint_cond);
322 sigint_mutex->unlock(sigint_mutex);
323 return TRUE;
324 default:
325 return FALSE;
326 }
327 }
328
329 /**
330 * Windows variant
331 */
332 void wait_sigint()
333 {
334 SetConsoleCtrlHandler(handler, TRUE);
335
336 sigint_mutex = mutex_create(MUTEX_TYPE_DEFAULT);
337 sigint_cond = condvar_create(CONDVAR_TYPE_DEFAULT);
338
339 sigint_mutex->lock(sigint_mutex);
340 while (!sigint_signaled)
341 {
342 sigint_cond->wait(sigint_cond, sigint_mutex);
343 }
344 sigint_mutex->unlock(sigint_mutex);
345
346 sigint_mutex->destroy(sigint_mutex);
347 sigint_cond->destroy(sigint_cond);
348 }
349
350 #else /* !WIN32 */
351
352 /**
353 * Unix variant
354 */
355 void wait_sigint()
356 {
357 sigset_t set;
358 int sig;
359
360 sigemptyset(&set);
361 sigaddset(&set, SIGINT);
362 sigaddset(&set, SIGTERM);
363
364 sigprocmask(SIG_BLOCK, &set, NULL);
365 sigwait(&set, &sig);
366 }
367
368 #endif
369
370 /**
371 * Described in header.
372 */
373 char* path_dirname(const char *path)
374 {
375 char *pos;
376
377 pos = path ? strrchr(path, DIRECTORY_SEPARATOR[0]) : NULL;
378
379 if (pos && !pos[1])
380 { /* if path ends with slashes we have to look beyond them */
381 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
382 { /* skip trailing slashes */
383 pos--;
384 }
385 pos = memrchr(path, DIRECTORY_SEPARATOR[0], pos - path + 1);
386 }
387 if (!pos)
388 {
389 #ifdef WIN32
390 if (path && strlen(path))
391 {
392 if ((isalpha(path[0]) && path[1] == ':'))
393 { /* if just a drive letter given, return that as dirname */
394 return chunk_clone(chunk_from_chars(path[0], ':', 0)).ptr;
395 }
396 }
397 #endif
398 return strdup(".");
399 }
400 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
401 { /* skip superfluous slashes */
402 pos--;
403 }
404 return strndup(path, pos - path + 1);
405 }
406
407 /**
408 * Described in header.
409 */
410 char* path_basename(const char *path)
411 {
412 char *pos, *trail = NULL;
413
414 if (!path || !*path)
415 {
416 return strdup(".");
417 }
418 pos = strrchr(path, DIRECTORY_SEPARATOR[0]);
419 if (pos && !pos[1])
420 { /* if path ends with slashes we have to look beyond them */
421 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
422 { /* skip trailing slashes */
423 pos--;
424 }
425 if (pos == path && *pos == DIRECTORY_SEPARATOR[0])
426 { /* contains only slashes */
427 return strdup(DIRECTORY_SEPARATOR);
428 }
429 trail = pos + 1;
430 pos = memrchr(path, DIRECTORY_SEPARATOR[0], trail - path);
431 }
432 pos = pos ? pos + 1 : (char*)path;
433 return trail ? strndup(pos, trail - pos) : strdup(pos);
434 }
435
436 /**
437 * Described in header.
438 */
439 bool path_absolute(const char *path)
440 {
441 if (!path)
442 {
443 return FALSE;
444 }
445 #ifdef WIN32
446 if (strpfx(path, "\\\\"))
447 { /* UNC */
448 return TRUE;
449 }
450 if (strlen(path) && isalpha(path[0]) && path[1] == ':')
451 { /* drive letter */
452 return TRUE;
453 }
454 #else /* !WIN32 */
455 if (path[0] == DIRECTORY_SEPARATOR[0])
456 {
457 return TRUE;
458 }
459 #endif
460 return FALSE;
461 }
462
463 /**
464 * Described in header.
465 */
466 bool mkdir_p(const char *path, mode_t mode)
467 {
468 int len;
469 char *pos, full[PATH_MAX];
470 pos = full;
471 if (!path || *path == '\0')
472 {
473 return TRUE;
474 }
475 len = snprintf(full, sizeof(full)-1, "%s", path);
476 if (len < 0 || len >= sizeof(full)-1)
477 {
478 DBG1(DBG_LIB, "path string %s too long", path);
479 return FALSE;
480 }
481 /* ensure that the path ends with a '/' */
482 if (full[len-1] != '/')
483 {
484 full[len++] = '/';
485 full[len] = '\0';
486 }
487 /* skip '/' at the beginning */
488 while (*pos == '/')
489 {
490 pos++;
491 }
492 while ((pos = strchr(pos, '/')))
493 {
494 *pos = '\0';
495 if (access(full, F_OK) < 0)
496 {
497 #ifdef WIN32
498 if (_mkdir(full) < 0)
499 #else
500 if (mkdir(full, mode) < 0)
501 #endif
502 {
503 DBG1(DBG_LIB, "failed to create directory %s", full);
504 return FALSE;
505 }
506 }
507 *pos = '/';
508 pos++;
509 }
510 return TRUE;
511 }
512
513 ENUM(tty_color_names, TTY_RESET, TTY_BG_DEF,
514 "\e[0m",
515 "\e[1m",
516 "\e[4m",
517 "\e[5m",
518 "\e[30m",
519 "\e[31m",
520 "\e[32m",
521 "\e[33m",
522 "\e[34m",
523 "\e[35m",
524 "\e[36m",
525 "\e[37m",
526 "\e[39m",
527 "\e[40m",
528 "\e[41m",
529 "\e[42m",
530 "\e[43m",
531 "\e[44m",
532 "\e[45m",
533 "\e[46m",
534 "\e[47m",
535 "\e[49m",
536 );
537
538 /**
539 * Get the escape string for a given TTY color, empty string on non-tty FILE
540 */
541 char* tty_escape_get(int fd, tty_escape_t escape)
542 {
543 if (!isatty(fd))
544 {
545 return "";
546 }
547 switch (escape)
548 {
549 case TTY_RESET:
550 case TTY_BOLD:
551 case TTY_UNDERLINE:
552 case TTY_BLINKING:
553 #ifdef WIN32
554 return "";
555 #endif
556 case TTY_FG_BLACK:
557 case TTY_FG_RED:
558 case TTY_FG_GREEN:
559 case TTY_FG_YELLOW:
560 case TTY_FG_BLUE:
561 case TTY_FG_MAGENTA:
562 case TTY_FG_CYAN:
563 case TTY_FG_WHITE:
564 case TTY_FG_DEF:
565 case TTY_BG_BLACK:
566 case TTY_BG_RED:
567 case TTY_BG_GREEN:
568 case TTY_BG_YELLOW:
569 case TTY_BG_BLUE:
570 case TTY_BG_MAGENTA:
571 case TTY_BG_CYAN:
572 case TTY_BG_WHITE:
573 case TTY_BG_DEF:
574 return enum_to_name(tty_color_names, escape);
575 /* warn if a escape code is missing */
576 }
577 return "";
578 }
579
580 #ifndef HAVE_CLOSEFROM
581 /**
582 * Described in header.
583 */
584 void closefrom(int lowfd)
585 {
586 char fd_dir[PATH_MAX];
587 int maxfd, fd, len;
588
589 /* try to close only open file descriptors on Linux... */
590 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
591 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
592 {
593 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
594 if (enumerator)
595 {
596 char *rel;
597 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
598 {
599 fd = atoi(rel);
600 if (fd >= lowfd)
601 {
602 close(fd);
603 }
604 }
605 enumerator->destroy(enumerator);
606 return;
607 }
608 }
609
610 /* ...fall back to closing all fds otherwise */
611 #ifdef WIN32
612 maxfd = _getmaxstdio();
613 #else
614 maxfd = (int)sysconf(_SC_OPEN_MAX);
615 #endif
616 if (maxfd < 0)
617 {
618 maxfd = 256;
619 }
620 for (fd = lowfd; fd < maxfd; fd++)
621 {
622 close(fd);
623 }
624 }
625 #endif /* HAVE_CLOSEFROM */
626
627 /**
628 * Return monotonic time
629 */
630 time_t time_monotonic(timeval_t *tv)
631 {
632 #ifdef WIN32
633 ULONGLONG ms;
634 time_t s;
635
636 ms = GetTickCount64();
637 s = ms / 1000;
638 if (tv)
639 {
640 tv->tv_sec = s;
641 tv->tv_usec = (ms - (s * 1000)) * 1000;
642 }
643 return s;
644 #else /* !WIN32 */
645 #if defined(HAVE_CLOCK_GETTIME) && \
646 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
647 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
648 /* as we use time_monotonic() for condvar operations, we use the
649 * monotonic time source only if it is also supported by pthread. */
650 timespec_t ts;
651
652 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
653 {
654 if (tv)
655 {
656 tv->tv_sec = ts.tv_sec;
657 tv->tv_usec = ts.tv_nsec / 1000;
658 }
659 return ts.tv_sec;
660 }
661 #endif /* HAVE_CLOCK_GETTIME && (...) */
662 /* Fallback to non-monotonic timestamps:
663 * On MAC OS X, creating monotonic timestamps is rather difficult. We
664 * could use mach_absolute_time() and catch sleep/wakeup notifications.
665 * We stick to the simpler (non-monotonic) gettimeofday() for now.
666 * But keep in mind: we need the same time source here as in condvar! */
667 if (!tv)
668 {
669 return time(NULL);
670 }
671 if (gettimeofday(tv, NULL) != 0)
672 { /* should actually never fail if passed pointers are valid */
673 return -1;
674 }
675 return tv->tv_sec;
676 #endif /* !WIN32 */
677 }
678
679 /**
680 * return null
681 */
682 void *return_null()
683 {
684 return NULL;
685 }
686
687 /**
688 * returns TRUE
689 */
690 bool return_true()
691 {
692 return TRUE;
693 }
694
695 /**
696 * returns FALSE
697 */
698 bool return_false()
699 {
700 return FALSE;
701 }
702
703 /**
704 * returns FAILED
705 */
706 status_t return_failed()
707 {
708 return FAILED;
709 }
710
711 /**
712 * returns SUCCESS
713 */
714 status_t return_success()
715 {
716 return SUCCESS;
717 }
718
719 /**
720 * nop operation
721 */
722 void nop()
723 {
724 }
725
726 #ifdef HAVE_FMEMOPEN_FALLBACK
727
728 static int fmemread(chunk_t *cookie, char *buf, int size)
729 {
730 int len;
731
732 len = min(size, cookie->len);
733 memcpy(buf, cookie->ptr, len);
734 *cookie = chunk_skip(*cookie, len);
735
736 return len;
737 }
738
739 static int fmemwrite(chunk_t *cookie, const char *buf, int size)
740 {
741 int len;
742
743 len = min(size, cookie->len);
744 memcpy(cookie->ptr, buf, len);
745 *cookie = chunk_skip(*cookie, len);
746
747 return len;
748 }
749
750 static int fmemclose(void *cookie)
751 {
752 free(cookie);
753 return 0;
754 }
755
756 FILE *fmemopen(void *buf, size_t size, const char *mode)
757 {
758 chunk_t *cookie;
759
760 INIT(cookie,
761 .ptr = buf,
762 .len = size,
763 );
764
765 return funopen(cookie, (void*)fmemread, (void*)fmemwrite, NULL, fmemclose);
766 }
767
768 #endif /* FMEMOPEN fallback*/
769
770 /**
771 * See header
772 */
773 void utils_init()
774 {
775 #ifdef WIN32
776 windows_init();
777 #endif
778 atomics_init();
779 strerror_init();
780 }
781
782 /**
783 * See header
784 */
785 void utils_deinit()
786 {
787 #ifdef WIN32
788 windows_deinit();
789 #endif
790 atomics_deinit();
791 strerror_deinit();
792 }
793
794 /**
795 * Described in header.
796 */
797 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
798 const void *const *args)
799 {
800 static const char* months[] = {
801 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
802 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
803 };
804 time_t *time = *((time_t**)(args[0]));
805 bool utc = *((int*)(args[1]));
806 struct tm t, *ret = NULL;
807
808 if (*time != UNDEFINED_TIME)
809 {
810 if (utc)
811 {
812 ret = gmtime_r(time, &t);
813 }
814 else
815 {
816 ret = localtime_r(time, &t);
817 }
818 }
819 if (ret == NULL)
820 {
821 return print_in_hook(data, "--- -- --:--:--%s----",
822 utc ? " UTC " : " ");
823 }
824 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
825 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
826 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
827 }
828
829 /**
830 * Described in header.
831 */
832 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
833 const void *const *args)
834 {
835 char* unit = "second";
836 time_t *arg1 = *((time_t**)(args[0]));
837 time_t *arg2 = *((time_t**)(args[1]));
838 u_int64_t delta = llabs(*arg1 - *arg2);
839
840 if (delta > 2 * 60 * 60 * 24)
841 {
842 delta /= 60 * 60 * 24;
843 unit = "day";
844 }
845 else if (delta > 2 * 60 * 60)
846 {
847 delta /= 60 * 60;
848 unit = "hour";
849 }
850 else if (delta > 2 * 60)
851 {
852 delta /= 60;
853 unit = "minute";
854 }
855 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
856 (delta == 1) ? "" : "s");
857 }
858
859 /**
860 * Number of bytes per line to dump raw data
861 */
862 #define BYTES_PER_LINE 16
863
864 static char hexdig_upper[] = "0123456789ABCDEF";
865
866 /**
867 * Described in header.
868 */
869 int mem_printf_hook(printf_hook_data_t *data,
870 printf_hook_spec_t *spec, const void *const *args)
871 {
872 char *bytes = *((void**)(args[0]));
873 u_int len = *((int*)(args[1]));
874
875 char buffer[BYTES_PER_LINE * 3];
876 char ascii_buffer[BYTES_PER_LINE + 1];
877 char *buffer_pos = buffer;
878 char *bytes_pos = bytes;
879 char *bytes_roof = bytes + len;
880 int line_start = 0;
881 int i = 0;
882 int written = 0;
883
884 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
885
886 while (bytes_pos < bytes_roof)
887 {
888 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
889 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
890
891 ascii_buffer[i++] =
892 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
893
894 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
895 {
896 int padding = 3 * (BYTES_PER_LINE - i);
897
898 while (padding--)
899 {
900 *buffer_pos++ = ' ';
901 }
902 *buffer_pos++ = '\0';
903 ascii_buffer[i] = '\0';
904
905 written += print_in_hook(data, "\n%4d: %s %s",
906 line_start, buffer, ascii_buffer);
907
908 buffer_pos = buffer;
909 line_start += BYTES_PER_LINE;
910 i = 0;
911 }
912 else
913 {
914 *buffer_pos++ = ' ';
915 }
916 }
917 return written;
918 }