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