Add a utility function to resolve TTY color escape codes dynamically
[strongswan.git] / src / libstrongswan / utils / utils.c
1 /*
2 * Copyright (C) 2008-2012 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 #include "utils.h"
18
19 #include <sys/stat.h>
20 #include <string.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <inttypes.h>
24 #include <stdint.h>
25 #include <limits.h>
26 #include <dirent.h>
27 #include <time.h>
28 #include <pthread.h>
29
30 #include "collections/enumerator.h"
31 #include "utils/debug.h"
32
33 ENUM(status_names, SUCCESS, NEED_MORE,
34 "SUCCESS",
35 "FAILED",
36 "OUT_OF_RES",
37 "ALREADY_DONE",
38 "NOT_SUPPORTED",
39 "INVALID_ARG",
40 "NOT_FOUND",
41 "PARSE_ERROR",
42 "VERIFY_ERROR",
43 "INVALID_STATE",
44 "DESTROY_ME",
45 "NEED_MORE",
46 );
47
48 /**
49 * Described in header.
50 */
51 void *clalloc(void * pointer, size_t size)
52 {
53 void *data;
54 data = malloc(size);
55
56 memcpy(data, pointer, size);
57
58 return (data);
59 }
60
61 /**
62 * Described in header.
63 */
64 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
65 {
66 int m, i;
67
68 /* byte wise XOR until dst aligned */
69 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
70 {
71 dst[i] ^= src[i];
72 }
73 /* try to use words if src shares an aligment with dst */
74 switch (((uintptr_t)&src[i] % sizeof(long)))
75 {
76 case 0:
77 for (m = n - sizeof(long); i <= m; i += sizeof(long))
78 {
79 *(long*)&dst[i] ^= *(long*)&src[i];
80 }
81 break;
82 case sizeof(int):
83 for (m = n - sizeof(int); i <= m; i += sizeof(int))
84 {
85 *(int*)&dst[i] ^= *(int*)&src[i];
86 }
87 break;
88 case sizeof(short):
89 for (m = n - sizeof(short); i <= m; i += sizeof(short))
90 {
91 *(short*)&dst[i] ^= *(short*)&src[i];
92 }
93 break;
94 default:
95 break;
96 }
97 /* byte wise XOR of the rest */
98 for (; i < n; i++)
99 {
100 dst[i] ^= src[i];
101 }
102 }
103
104 /**
105 * Described in header.
106 */
107 void memwipe_noinline(void *ptr, size_t n)
108 {
109 memwipe_inline(ptr, n);
110 }
111
112 /**
113 * Described in header.
114 */
115 void *memstr(const void *haystack, const char *needle, size_t n)
116 {
117 unsigned const char *pos = haystack;
118 size_t l = strlen(needle);
119 for (; n >= l; ++pos, --n)
120 {
121 if (memeq(pos, needle, l))
122 {
123 return (void*)pos;
124 }
125 }
126 return NULL;
127 }
128
129 /**
130 * Described in header.
131 */
132 char* translate(char *str, const char *from, const char *to)
133 {
134 char *pos = str;
135 if (strlen(from) != strlen(to))
136 {
137 return str;
138 }
139 while (pos && *pos)
140 {
141 char *match;
142 if ((match = strchr(from, *pos)) != NULL)
143 {
144 *pos = to[match - from];
145 }
146 pos++;
147 }
148 return str;
149 }
150
151 /**
152 * Described in header.
153 */
154 bool mkdir_p(const char *path, mode_t mode)
155 {
156 int len;
157 char *pos, full[PATH_MAX];
158 pos = full;
159 if (!path || *path == '\0')
160 {
161 return TRUE;
162 }
163 len = snprintf(full, sizeof(full)-1, "%s", path);
164 if (len < 0 || len >= sizeof(full)-1)
165 {
166 DBG1(DBG_LIB, "path string %s too long", path);
167 return FALSE;
168 }
169 /* ensure that the path ends with a '/' */
170 if (full[len-1] != '/')
171 {
172 full[len++] = '/';
173 full[len] = '\0';
174 }
175 /* skip '/' at the beginning */
176 while (*pos == '/')
177 {
178 pos++;
179 }
180 while ((pos = strchr(pos, '/')))
181 {
182 *pos = '\0';
183 if (access(full, F_OK) < 0)
184 {
185 if (mkdir(full, mode) < 0)
186 {
187 DBG1(DBG_LIB, "failed to create directory %s", full);
188 return FALSE;
189 }
190 }
191 *pos = '/';
192 pos++;
193 }
194 return TRUE;
195 }
196
197 ENUM(tty_color_names, TTY_RESET, TTY_BG_DEF,
198 "\e[0m",
199 "\e[1m",
200 "\e[4m",
201 "\e[5m",
202 "\e[30m",
203 "\e[31m",
204 "\e[32m",
205 "\e[33m",
206 "\e[34m",
207 "\e[35m",
208 "\e[36m",
209 "\e[37m",
210 "\e[39m",
211 "\e[40m",
212 "\e[41m",
213 "\e[42m",
214 "\e[43m",
215 "\e[44m",
216 "\e[45m",
217 "\e[46m",
218 "\e[47m",
219 "\e[49m",
220 );
221
222 /**
223 * Get the escape string for a given TTY color, empty string on non-tty FILE
224 */
225 char* tty_escape_get(int fd, tty_escape_t escape)
226 {
227 if (!isatty(fd))
228 {
229 return "";
230 }
231 switch (escape)
232 {
233 case TTY_RESET:
234 case TTY_BOLD:
235 case TTY_UNDERLINE:
236 case TTY_BLINKING:
237 case TTY_FG_BLACK:
238 case TTY_FG_RED:
239 case TTY_FG_GREEN:
240 case TTY_FG_YELLOW:
241 case TTY_FG_BLUE:
242 case TTY_FG_MAGENTA:
243 case TTY_FG_CYAN:
244 case TTY_FG_WHITE:
245 case TTY_FG_DEF:
246 case TTY_BG_BLACK:
247 case TTY_BG_RED:
248 case TTY_BG_GREEN:
249 case TTY_BG_YELLOW:
250 case TTY_BG_BLUE:
251 case TTY_BG_MAGENTA:
252 case TTY_BG_CYAN:
253 case TTY_BG_WHITE:
254 case TTY_BG_DEF:
255 return enum_to_name(tty_color_names, escape);
256 /* warn if a excape code is missing */
257 }
258 return "";
259 }
260
261 /**
262 * The size of the thread-specific error buffer
263 */
264 #define STRERROR_BUF_LEN 256
265
266 /**
267 * Key to store thread-specific error buffer
268 */
269 static pthread_key_t strerror_buf_key;
270
271 /**
272 * Only initialize the key above once
273 */
274 static pthread_once_t strerror_buf_key_once = PTHREAD_ONCE_INIT;
275
276 /**
277 * Create the key used for the thread-specific error buffer
278 */
279 static void create_strerror_buf_key()
280 {
281 pthread_key_create(&strerror_buf_key, free);
282 }
283
284 /**
285 * Retrieve the error buffer assigned to the current thread (or create it)
286 */
287 static inline char *get_strerror_buf()
288 {
289 char *buf;
290
291 pthread_once(&strerror_buf_key_once, create_strerror_buf_key);
292 buf = pthread_getspecific(strerror_buf_key);
293 if (!buf)
294 {
295 buf = malloc(STRERROR_BUF_LEN);
296 pthread_setspecific(strerror_buf_key, buf);
297 }
298 return buf;
299 }
300
301 #ifdef HAVE_STRERROR_R
302 /*
303 * Described in header.
304 */
305 const char *safe_strerror(int errnum)
306 {
307 char *buf = get_strerror_buf(), *msg;
308
309 #ifdef STRERROR_R_CHAR_P
310 /* char* version which may or may not return the original buffer */
311 msg = strerror_r(errnum, buf, STRERROR_BUF_LEN);
312 #else
313 /* int version returns 0 on success */
314 msg = strerror_r(errnum, buf, STRERROR_BUF_LEN) ? "Unknown error" : buf;
315 #endif
316 return msg;
317 }
318 #else /* HAVE_STRERROR_R */
319 /* we actually wan't to call strerror(3) below */
320 #undef strerror
321 /*
322 * Described in header.
323 */
324 const char *safe_strerror(int errnum)
325 {
326 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
327 char *buf = get_strerror_buf();
328
329 /* use a mutex to ensure calling strerror(3) is thread-safe */
330 pthread_mutex_lock(&mutex);
331 strncpy(buf, strerror(errnum), STRERROR_BUF_LEN);
332 pthread_mutex_unlock(&mutex);
333 buf[STRERROR_BUF_LEN - 1] = '\0';
334 return buf;
335 }
336 #endif /* HAVE_STRERROR_R */
337
338
339 #ifndef HAVE_CLOSEFROM
340 /**
341 * Described in header.
342 */
343 void closefrom(int lowfd)
344 {
345 char fd_dir[PATH_MAX];
346 int maxfd, fd, len;
347
348 /* try to close only open file descriptors on Linux... */
349 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
350 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
351 {
352 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
353 if (enumerator)
354 {
355 char *rel;
356 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
357 {
358 fd = atoi(rel);
359 if (fd >= lowfd)
360 {
361 close(fd);
362 }
363 }
364 enumerator->destroy(enumerator);
365 return;
366 }
367 }
368
369 /* ...fall back to closing all fds otherwise */
370 maxfd = (int)sysconf(_SC_OPEN_MAX);
371 if (maxfd < 0)
372 {
373 maxfd = 256;
374 }
375 for (fd = lowfd; fd < maxfd; fd++)
376 {
377 close(fd);
378 }
379 }
380 #endif /* HAVE_CLOSEFROM */
381
382 /**
383 * Return monotonic time
384 */
385 time_t time_monotonic(timeval_t *tv)
386 {
387 #if defined(HAVE_CLOCK_GETTIME) && \
388 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
389 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
390 /* as we use time_monotonic() for condvar operations, we use the
391 * monotonic time source only if it is also supported by pthread. */
392 timespec_t ts;
393
394 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
395 {
396 if (tv)
397 {
398 tv->tv_sec = ts.tv_sec;
399 tv->tv_usec = ts.tv_nsec / 1000;
400 }
401 return ts.tv_sec;
402 }
403 #endif /* HAVE_CLOCK_GETTIME && (...) */
404 /* Fallback to non-monotonic timestamps:
405 * On MAC OS X, creating monotonic timestamps is rather difficult. We
406 * could use mach_absolute_time() and catch sleep/wakeup notifications.
407 * We stick to the simpler (non-monotonic) gettimeofday() for now.
408 * But keep in mind: we need the same time source here as in condvar! */
409 if (!tv)
410 {
411 return time(NULL);
412 }
413 if (gettimeofday(tv, NULL) != 0)
414 { /* should actually never fail if passed pointers are valid */
415 return -1;
416 }
417 return tv->tv_sec;
418 }
419
420 /**
421 * return null
422 */
423 void *return_null()
424 {
425 return NULL;
426 }
427
428 /**
429 * returns TRUE
430 */
431 bool return_true()
432 {
433 return TRUE;
434 }
435
436 /**
437 * returns FALSE
438 */
439 bool return_false()
440 {
441 return FALSE;
442 }
443
444 /**
445 * returns FAILED
446 */
447 status_t return_failed()
448 {
449 return FAILED;
450 }
451
452 /**
453 * returns SUCCESS
454 */
455 status_t return_success()
456 {
457 return SUCCESS;
458 }
459
460 /**
461 * nop operation
462 */
463 void nop()
464 {
465 }
466
467 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
468
469 /**
470 * We use a single mutex for all refcount variables.
471 */
472 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
473
474 /**
475 * Increase refcount
476 */
477 void ref_get(refcount_t *ref)
478 {
479 pthread_mutex_lock(&ref_mutex);
480 (*ref)++;
481 pthread_mutex_unlock(&ref_mutex);
482 }
483
484 /**
485 * Decrease refcount
486 */
487 bool ref_put(refcount_t *ref)
488 {
489 bool more_refs;
490
491 pthread_mutex_lock(&ref_mutex);
492 more_refs = --(*ref) > 0;
493 pthread_mutex_unlock(&ref_mutex);
494 return !more_refs;
495 }
496
497 /**
498 * Single mutex for all compare and swap operations.
499 */
500 static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
501
502 /**
503 * Compare and swap if equal to old value
504 */
505 #define _cas_impl(name, type) \
506 bool cas_##name(type *ptr, type oldval, type newval) \
507 { \
508 bool swapped; \
509 pthread_mutex_lock(&cas_mutex); \
510 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
511 pthread_mutex_unlock(&cas_mutex); \
512 return swapped; \
513 }
514
515 _cas_impl(bool, bool)
516 _cas_impl(ptr, void*)
517
518 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
519
520 /**
521 * Described in header.
522 */
523 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
524 const void *const *args)
525 {
526 static const char* months[] = {
527 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
528 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
529 };
530 time_t *time = *((time_t**)(args[0]));
531 bool utc = *((bool*)(args[1]));;
532 struct tm t;
533
534 if (*time == UNDEFINED_TIME)
535 {
536 return print_in_hook(data, "--- -- --:--:--%s----",
537 utc ? " UTC " : " ");
538 }
539 if (utc)
540 {
541 gmtime_r(time, &t);
542 }
543 else
544 {
545 localtime_r(time, &t);
546 }
547 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
548 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
549 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
550 }
551
552 /**
553 * Described in header.
554 */
555 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
556 const void *const *args)
557 {
558 char* unit = "second";
559 time_t *arg1 = *((time_t**)(args[0]));
560 time_t *arg2 = *((time_t**)(args[1]));
561 u_int64_t delta = llabs(*arg1 - *arg2);
562
563 if (delta > 2 * 60 * 60 * 24)
564 {
565 delta /= 60 * 60 * 24;
566 unit = "day";
567 }
568 else if (delta > 2 * 60 * 60)
569 {
570 delta /= 60 * 60;
571 unit = "hour";
572 }
573 else if (delta > 2 * 60)
574 {
575 delta /= 60;
576 unit = "minute";
577 }
578 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
579 (delta == 1) ? "" : "s");
580 }
581
582 /**
583 * Number of bytes per line to dump raw data
584 */
585 #define BYTES_PER_LINE 16
586
587 static char hexdig_upper[] = "0123456789ABCDEF";
588
589 /**
590 * Described in header.
591 */
592 int mem_printf_hook(printf_hook_data_t *data,
593 printf_hook_spec_t *spec, const void *const *args)
594 {
595 char *bytes = *((void**)(args[0]));
596 u_int len = *((int*)(args[1]));
597
598 char buffer[BYTES_PER_LINE * 3];
599 char ascii_buffer[BYTES_PER_LINE + 1];
600 char *buffer_pos = buffer;
601 char *bytes_pos = bytes;
602 char *bytes_roof = bytes + len;
603 int line_start = 0;
604 int i = 0;
605 int written = 0;
606
607 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
608
609 while (bytes_pos < bytes_roof)
610 {
611 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
612 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
613
614 ascii_buffer[i++] =
615 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
616
617 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
618 {
619 int padding = 3 * (BYTES_PER_LINE - i);
620
621 while (padding--)
622 {
623 *buffer_pos++ = ' ';
624 }
625 *buffer_pos++ = '\0';
626 ascii_buffer[i] = '\0';
627
628 written += print_in_hook(data, "\n%4d: %s %s",
629 line_start, buffer, ascii_buffer);
630
631 buffer_pos = buffer;
632 line_start += BYTES_PER_LINE;
633 i = 0;
634 }
635 else
636 {
637 *buffer_pos++ = ' ';
638 }
639 }
640 return written;
641 }