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