printf-hook-builtin: Support Windows console colors using TTY escape codes
[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 #ifdef WIN32
311 if (_mkdir(full) < 0)
312 #else
313 if (mkdir(full, mode) < 0)
314 #endif
315 {
316 DBG1(DBG_LIB, "failed to create directory %s", full);
317 return FALSE;
318 }
319 }
320 *pos = '/';
321 pos++;
322 }
323 return TRUE;
324 }
325
326 ENUM(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 */
354 char* 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 #ifdef WIN32
367 return "";
368 #endif
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);
388 /* warn if a escape code is missing */
389 }
390 return "";
391 }
392
393 #ifndef HAVE_CLOSEFROM
394 /**
395 * Described in header.
396 */
397 void closefrom(int lowfd)
398 {
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());
404 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
405 {
406 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
407 if (enumerator)
408 {
409 char *rel;
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 */
424 #ifdef WIN32
425 maxfd = _getmaxstdio();
426 #else
427 maxfd = (int)sysconf(_SC_OPEN_MAX);
428 #endif
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
440 /**
441 * Return monotonic time
442 */
443 time_t time_monotonic(timeval_t *tv)
444 {
445 #if defined(HAVE_CLOCK_GETTIME) && \
446 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
447 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
448 /* as we use time_monotonic() for condvar operations, we use the
449 * monotonic time source only if it is also supported by pthread. */
450 timespec_t ts;
451
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 }
461 #endif /* HAVE_CLOCK_GETTIME && (...) */
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.
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! */
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
478 /**
479 * return null
480 */
481 void *return_null()
482 {
483 return NULL;
484 }
485
486 /**
487 * returns TRUE
488 */
489 bool return_true()
490 {
491 return TRUE;
492 }
493
494 /**
495 * returns FALSE
496 */
497 bool return_false()
498 {
499 return FALSE;
500 }
501
502 /**
503 * returns FAILED
504 */
505 status_t return_failed()
506 {
507 return FAILED;
508 }
509
510 /**
511 * returns SUCCESS
512 */
513 status_t return_success()
514 {
515 return SUCCESS;
516 }
517
518 /**
519 * nop operation
520 */
521 void nop()
522 {
523 }
524
525 #if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
526
527 /**
528 * We use a single mutex for all refcount variables.
529 */
530 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
531
532 /**
533 * Increase refcount
534 */
535 refcount_t ref_get(refcount_t *ref)
536 {
537 refcount_t current;
538
539 pthread_mutex_lock(&ref_mutex);
540 current = ++(*ref);
541 pthread_mutex_unlock(&ref_mutex);
542 return current;
543 }
544
545 /**
546 * Decrease refcount
547 */
548 bool ref_put(refcount_t *ref)
549 {
550 bool more_refs;
551
552 pthread_mutex_lock(&ref_mutex);
553 more_refs = --(*ref) > 0;
554 pthread_mutex_unlock(&ref_mutex);
555 return !more_refs;
556 }
557
558 /**
559 * Current refcount
560 */
561 refcount_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
571 /**
572 * Single mutex for all compare and swap operations.
573 */
574 static 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) \
580 bool 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
592 #endif /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
593
594
595 #ifdef HAVE_FMEMOPEN_FALLBACK
596
597 static 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
608 static 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
619 static int fmemclose(void *cookie)
620 {
621 free(cookie);
622 return 0;
623 }
624
625 FILE *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
639 /**
640 * Described in header.
641 */
642 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
643 const void *const *args)
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]));
650 bool utc = *((int*)(args[1]));
651 struct tm t;
652
653 if (*time == UNDEFINED_TIME)
654 {
655 return print_in_hook(data, "--- -- --:--:--%s----",
656 utc ? " UTC " : " ");
657 }
658 if (utc)
659 {
660 gmtime_r(time, &t);
661 }
662 else
663 {
664 localtime_r(time, &t);
665 }
666 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
667 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
668 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
669 }
670
671 /**
672 * Described in header.
673 */
674 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
675 const void *const *args)
676 {
677 char* unit = "second";
678 time_t *arg1 = *((time_t**)(args[0]));
679 time_t *arg2 = *((time_t**)(args[1]));
680 u_int64_t delta = llabs(*arg1 - *arg2);
681
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 }
697 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
698 (delta == 1) ? "" : "s");
699 }
700
701 /**
702 * Number of bytes per line to dump raw data
703 */
704 #define BYTES_PER_LINE 16
705
706 static char hexdig_upper[] = "0123456789ABCDEF";
707
708 /**
709 * Described in header.
710 */
711 int mem_printf_hook(printf_hook_data_t *data,
712 printf_hook_spec_t *spec, const void *const *args)
713 {
714 char *bytes = *((void**)(args[0]));
715 u_int len = *((int*)(args[1]));
716
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;
725
726 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
727
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
736 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
737 {
738 int padding = 3 * (BYTES_PER_LINE - i);
739
740 while (padding--)
741 {
742 *buffer_pos++ = ' ';
743 }
744 *buffer_pos++ = '\0';
745 ascii_buffer[i] = '\0';
746
747 written += print_in_hook(data, "\n%4d: %s %s",
748 line_start, buffer, ascii_buffer);
749
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 }