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