utils: Move thread-safe strerror replacement to a separate file
[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 #ifndef HAVE_CLOSEFROM
307 /**
308 * Described in header.
309 */
310 void closefrom(int lowfd)
311 {
312 char fd_dir[PATH_MAX];
313 int maxfd, fd, len;
314
315 /* try to close only open file descriptors on Linux... */
316 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
317 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
318 {
319 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
320 if (enumerator)
321 {
322 char *rel;
323 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
324 {
325 fd = atoi(rel);
326 if (fd >= lowfd)
327 {
328 close(fd);
329 }
330 }
331 enumerator->destroy(enumerator);
332 return;
333 }
334 }
335
336 /* ...fall back to closing all fds otherwise */
337 maxfd = (int)sysconf(_SC_OPEN_MAX);
338 if (maxfd < 0)
339 {
340 maxfd = 256;
341 }
342 for (fd = lowfd; fd < maxfd; fd++)
343 {
344 close(fd);
345 }
346 }
347 #endif /* HAVE_CLOSEFROM */
348
349 /**
350 * Return monotonic time
351 */
352 time_t time_monotonic(timeval_t *tv)
353 {
354 #if defined(HAVE_CLOCK_GETTIME) && \
355 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
356 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
357 /* as we use time_monotonic() for condvar operations, we use the
358 * monotonic time source only if it is also supported by pthread. */
359 timespec_t ts;
360
361 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
362 {
363 if (tv)
364 {
365 tv->tv_sec = ts.tv_sec;
366 tv->tv_usec = ts.tv_nsec / 1000;
367 }
368 return ts.tv_sec;
369 }
370 #endif /* HAVE_CLOCK_GETTIME && (...) */
371 /* Fallback to non-monotonic timestamps:
372 * On MAC OS X, creating monotonic timestamps is rather difficult. We
373 * could use mach_absolute_time() and catch sleep/wakeup notifications.
374 * We stick to the simpler (non-monotonic) gettimeofday() for now.
375 * But keep in mind: we need the same time source here as in condvar! */
376 if (!tv)
377 {
378 return time(NULL);
379 }
380 if (gettimeofday(tv, NULL) != 0)
381 { /* should actually never fail if passed pointers are valid */
382 return -1;
383 }
384 return tv->tv_sec;
385 }
386
387 /**
388 * return null
389 */
390 void *return_null()
391 {
392 return NULL;
393 }
394
395 /**
396 * returns TRUE
397 */
398 bool return_true()
399 {
400 return TRUE;
401 }
402
403 /**
404 * returns FALSE
405 */
406 bool return_false()
407 {
408 return FALSE;
409 }
410
411 /**
412 * returns FAILED
413 */
414 status_t return_failed()
415 {
416 return FAILED;
417 }
418
419 /**
420 * returns SUCCESS
421 */
422 status_t return_success()
423 {
424 return SUCCESS;
425 }
426
427 /**
428 * nop operation
429 */
430 void nop()
431 {
432 }
433
434 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
435
436 /**
437 * We use a single mutex for all refcount variables.
438 */
439 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
440
441 /**
442 * Increase refcount
443 */
444 refcount_t ref_get(refcount_t *ref)
445 {
446 refcount_t current;
447
448 pthread_mutex_lock(&ref_mutex);
449 current = ++(*ref);
450 pthread_mutex_unlock(&ref_mutex);
451
452 return current;
453 }
454
455 /**
456 * Decrease refcount
457 */
458 bool ref_put(refcount_t *ref)
459 {
460 bool more_refs;
461
462 pthread_mutex_lock(&ref_mutex);
463 more_refs = --(*ref) > 0;
464 pthread_mutex_unlock(&ref_mutex);
465 return !more_refs;
466 }
467
468 /**
469 * Single mutex for all compare and swap operations.
470 */
471 static pthread_mutex_t cas_mutex = PTHREAD_MUTEX_INITIALIZER;
472
473 /**
474 * Compare and swap if equal to old value
475 */
476 #define _cas_impl(name, type) \
477 bool cas_##name(type *ptr, type oldval, type newval) \
478 { \
479 bool swapped; \
480 pthread_mutex_lock(&cas_mutex); \
481 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
482 pthread_mutex_unlock(&cas_mutex); \
483 return swapped; \
484 }
485
486 _cas_impl(bool, bool)
487 _cas_impl(ptr, void*)
488
489 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
490
491
492 #ifdef HAVE_FMEMOPEN_FALLBACK
493
494 static int fmemread(chunk_t *cookie, char *buf, int size)
495 {
496 int len;
497
498 len = min(size, cookie->len);
499 memcpy(buf, cookie->ptr, len);
500 *cookie = chunk_skip(*cookie, len);
501
502 return len;
503 }
504
505 static int fmemwrite(chunk_t *cookie, const char *buf, int size)
506 {
507 int len;
508
509 len = min(size, cookie->len);
510 memcpy(cookie->ptr, buf, len);
511 *cookie = chunk_skip(*cookie, len);
512
513 return len;
514 }
515
516 static int fmemclose(void *cookie)
517 {
518 free(cookie);
519 return 0;
520 }
521
522 FILE *fmemopen(void *buf, size_t size, const char *mode)
523 {
524 chunk_t *cookie;
525
526 INIT(cookie,
527 .ptr = buf,
528 .len = size,
529 );
530
531 return funopen(cookie, (void*)fmemread, (void*)fmemwrite, NULL, fmemclose);
532 }
533
534 #endif /* FMEMOPEN fallback*/
535
536 /**
537 * Described in header.
538 */
539 int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
540 const void *const *args)
541 {
542 static const char* months[] = {
543 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
544 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
545 };
546 time_t *time = *((time_t**)(args[0]));
547 bool utc = *((int*)(args[1]));
548 struct tm t;
549
550 if (*time == UNDEFINED_TIME)
551 {
552 return print_in_hook(data, "--- -- --:--:--%s----",
553 utc ? " UTC " : " ");
554 }
555 if (utc)
556 {
557 gmtime_r(time, &t);
558 }
559 else
560 {
561 localtime_r(time, &t);
562 }
563 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
564 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
565 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
566 }
567
568 /**
569 * Described in header.
570 */
571 int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
572 const void *const *args)
573 {
574 char* unit = "second";
575 time_t *arg1 = *((time_t**)(args[0]));
576 time_t *arg2 = *((time_t**)(args[1]));
577 u_int64_t delta = llabs(*arg1 - *arg2);
578
579 if (delta > 2 * 60 * 60 * 24)
580 {
581 delta /= 60 * 60 * 24;
582 unit = "day";
583 }
584 else if (delta > 2 * 60 * 60)
585 {
586 delta /= 60 * 60;
587 unit = "hour";
588 }
589 else if (delta > 2 * 60)
590 {
591 delta /= 60;
592 unit = "minute";
593 }
594 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
595 (delta == 1) ? "" : "s");
596 }
597
598 /**
599 * Number of bytes per line to dump raw data
600 */
601 #define BYTES_PER_LINE 16
602
603 static char hexdig_upper[] = "0123456789ABCDEF";
604
605 /**
606 * Described in header.
607 */
608 int mem_printf_hook(printf_hook_data_t *data,
609 printf_hook_spec_t *spec, const void *const *args)
610 {
611 char *bytes = *((void**)(args[0]));
612 u_int len = *((int*)(args[1]));
613
614 char buffer[BYTES_PER_LINE * 3];
615 char ascii_buffer[BYTES_PER_LINE + 1];
616 char *buffer_pos = buffer;
617 char *bytes_pos = bytes;
618 char *bytes_roof = bytes + len;
619 int line_start = 0;
620 int i = 0;
621 int written = 0;
622
623 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
624
625 while (bytes_pos < bytes_roof)
626 {
627 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
628 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
629
630 ascii_buffer[i++] =
631 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
632
633 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
634 {
635 int padding = 3 * (BYTES_PER_LINE - i);
636
637 while (padding--)
638 {
639 *buffer_pos++ = ' ';
640 }
641 *buffer_pos++ = '\0';
642 ascii_buffer[i] = '\0';
643
644 written += print_in_hook(data, "\n%4d: %s %s",
645 line_start, buffer, ascii_buffer);
646
647 buffer_pos = buffer;
648 line_start += BYTES_PER_LINE;
649 i = 0;
650 }
651 else
652 {
653 *buffer_pos++ = ' ';
654 }
655 }
656 return written;
657 }