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