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