Unused variable removed.
[strongswan.git] / src / libstrongswan / utils.c
1 /*
2 * Copyright (C) 2008-2011 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
29 #include "enum.h"
30 #include "debug.h"
31 #include "utils/enumerator.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 *clalloc(void * pointer, size_t size)
52 {
53 void *data;
54 data = malloc(size);
55
56 memcpy(data, pointer, size);
57
58 return (data);
59 }
60
61 /**
62 * Described in header.
63 */
64 void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
65 {
66 int m, i;
67
68 /* byte wise XOR until dst aligned */
69 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
70 {
71 dst[i] ^= src[i];
72 }
73 /* try to use words if src shares an aligment with dst */
74 switch (((uintptr_t)&src[i] % sizeof(long)))
75 {
76 case 0:
77 for (m = n - sizeof(long); i <= m; i += sizeof(long))
78 {
79 *(long*)&dst[i] ^= *(long*)&src[i];
80 }
81 break;
82 case sizeof(int):
83 for (m = n - sizeof(int); i <= m; i += sizeof(int))
84 {
85 *(int*)&dst[i] ^= *(int*)&src[i];
86 }
87 break;
88 case sizeof(short):
89 for (m = n - sizeof(short); i <= m; i += sizeof(short))
90 {
91 *(short*)&dst[i] ^= *(short*)&src[i];
92 }
93 break;
94 default:
95 break;
96 }
97 /* byte wise XOR of the rest */
98 for (; i < n; i++)
99 {
100 dst[i] ^= src[i];
101 }
102 }
103
104 /**
105 * Described in header.
106 */
107 void memwipe_noinline(void *ptr, size_t n)
108 {
109 memwipe_inline(ptr, n);
110 }
111
112 /**
113 * Described in header.
114 */
115 void *memstr(const void *haystack, const char *needle, size_t n)
116 {
117 unsigned const char *pos = haystack;
118 size_t l = strlen(needle);
119 for (; n >= l; ++pos, --n)
120 {
121 if (memeq(pos, needle, l))
122 {
123 return (void*)pos;
124 }
125 }
126 return NULL;
127 }
128
129 /**
130 * Described in header.
131 */
132 char* translate(char *str, const char *from, const char *to)
133 {
134 char *pos = str;
135 if (strlen(from) != strlen(to))
136 {
137 return str;
138 }
139 while (pos && *pos)
140 {
141 char *match;
142 if ((match = strchr(from, *pos)) != NULL)
143 {
144 *pos = to[match - from];
145 }
146 pos++;
147 }
148 return str;
149 }
150
151 /**
152 * Described in header.
153 */
154 bool mkdir_p(const char *path, mode_t mode)
155 {
156 int len;
157 char *pos, full[PATH_MAX];
158 pos = full;
159 if (!path || *path == '\0')
160 {
161 return TRUE;
162 }
163 len = snprintf(full, sizeof(full)-1, "%s", path);
164 if (len < 0 || len >= sizeof(full)-1)
165 {
166 DBG1(DBG_LIB, "path string %s too long", path);
167 return FALSE;
168 }
169 /* ensure that the path ends with a '/' */
170 if (full[len-1] != '/')
171 {
172 full[len++] = '/';
173 full[len] = '\0';
174 }
175 /* skip '/' at the beginning */
176 while (*pos == '/')
177 {
178 pos++;
179 }
180 while ((pos = strchr(pos, '/')))
181 {
182 *pos = '\0';
183 if (access(full, F_OK) < 0)
184 {
185 if (mkdir(full, mode) < 0)
186 {
187 DBG1(DBG_LIB, "failed to create directory %s", full);
188 return FALSE;
189 }
190 }
191 *pos = '/';
192 pos++;
193 }
194 return TRUE;
195 }
196
197 #ifndef HAVE_CLOSEFROM
198 /**
199 * Described in header.
200 */
201 void closefrom(int lowfd)
202 {
203 char fd_dir[PATH_MAX];
204 int maxfd, fd, len;
205
206 /* try to close only open file descriptors on Linux... */
207 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
208 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
209 {
210 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
211 if (enumerator)
212 {
213 char *rel;
214 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
215 {
216 fd = atoi(rel);
217 if (fd >= lowfd)
218 {
219 close(fd);
220 }
221 }
222 enumerator->destroy(enumerator);
223 return;
224 }
225 }
226
227 /* ...fall back to closing all fds otherwise */
228 maxfd = (int)sysconf(_SC_OPEN_MAX);
229 if (maxfd < 0)
230 {
231 maxfd = 256;
232 }
233 for (fd = lowfd; fd < maxfd; fd++)
234 {
235 close(fd);
236 }
237 }
238 #endif /* HAVE_CLOSEFROM */
239
240 /**
241 * Return monotonic time
242 */
243 time_t time_monotonic(timeval_t *tv)
244 {
245 #if defined(HAVE_CLOCK_GETTIME) && \
246 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
247 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
248 /* as we use time_monotonic() for condvar operations, we use the
249 * monotonic time source only if it is also supported by pthread. */
250 timespec_t ts;
251
252 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
253 {
254 if (tv)
255 {
256 tv->tv_sec = ts.tv_sec;
257 tv->tv_usec = ts.tv_nsec / 1000;
258 }
259 return ts.tv_sec;
260 }
261 #endif /* HAVE_CLOCK_GETTIME && (...) */
262 /* Fallback to non-monotonic timestamps:
263 * On MAC OS X, creating monotonic timestamps is rather difficult. We
264 * could use mach_absolute_time() and catch sleep/wakeup notifications.
265 * We stick to the simpler (non-monotonic) gettimeofday() for now.
266 * But keep in mind: we need the same time source here as in condvar! */
267 if (!tv)
268 {
269 return time(NULL);
270 }
271 if (gettimeofday(tv, NULL) != 0)
272 { /* should actually never fail if passed pointers are valid */
273 return -1;
274 }
275 return tv->tv_sec;
276 }
277
278 /**
279 * return null
280 */
281 void *return_null()
282 {
283 return NULL;
284 }
285
286 /**
287 * returns TRUE
288 */
289 bool return_true()
290 {
291 return TRUE;
292 }
293
294 /**
295 * returns FALSE
296 */
297 bool return_false()
298 {
299 return FALSE;
300 }
301
302 /**
303 * returns FAILED
304 */
305 status_t return_failed()
306 {
307 return FAILED;
308 }
309
310 /**
311 * nop operation
312 */
313 void nop()
314 {
315 }
316
317 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
318 #include <pthread.h>
319
320 /**
321 * We use a single mutex for all refcount variables.
322 */
323 static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
324
325 /**
326 * Increase refcount
327 */
328 void ref_get(refcount_t *ref)
329 {
330 pthread_mutex_lock(&ref_mutex);
331 (*ref)++;
332 pthread_mutex_unlock(&ref_mutex);
333 }
334
335 /**
336 * Decrease refcount
337 */
338 bool ref_put(refcount_t *ref)
339 {
340 bool more_refs;
341
342 pthread_mutex_lock(&ref_mutex);
343 more_refs = --(*ref) > 0;
344 pthread_mutex_unlock(&ref_mutex);
345 return !more_refs;
346 }
347 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
348
349 /**
350 * Described in header.
351 */
352 int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
353 const void *const *args)
354 {
355 static const char* months[] = {
356 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
357 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
358 };
359 time_t *time = *((time_t**)(args[0]));
360 bool utc = *((bool*)(args[1]));;
361 struct tm t;
362
363 if (time == UNDEFINED_TIME)
364 {
365 return print_in_hook(dst, len, "--- -- --:--:--%s----",
366 utc ? " UTC " : " ");
367 }
368 if (utc)
369 {
370 gmtime_r(time, &t);
371 }
372 else
373 {
374 localtime_r(time, &t);
375 }
376 return print_in_hook(dst, len, "%s %02d %02d:%02d:%02d%s%04d",
377 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
378 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
379 }
380
381 /**
382 * Described in header.
383 */
384 int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
385 const void *const *args)
386 {
387 char* unit = "second";
388 time_t *arg1 = *((time_t**)(args[0]));
389 time_t *arg2 = *((time_t**)(args[1]));
390 u_int64_t delta = llabs(*arg1 - *arg2);
391
392 if (delta > 2 * 60 * 60 * 24)
393 {
394 delta /= 60 * 60 * 24;
395 unit = "day";
396 }
397 else if (delta > 2 * 60 * 60)
398 {
399 delta /= 60 * 60;
400 unit = "hour";
401 }
402 else if (delta > 2 * 60)
403 {
404 delta /= 60;
405 unit = "minute";
406 }
407 return print_in_hook(dst, len, "%" PRIu64 " %s%s", delta, unit,
408 (delta == 1) ? "" : "s");
409 }
410
411 /**
412 * Number of bytes per line to dump raw data
413 */
414 #define BYTES_PER_LINE 16
415
416 static char hexdig_upper[] = "0123456789ABCDEF";
417
418 /**
419 * Described in header.
420 */
421 int mem_printf_hook(char *dst, size_t dstlen,
422 printf_hook_spec_t *spec, const void *const *args)
423 {
424 char *bytes = *((void**)(args[0]));
425 int len = *((size_t*)(args[1]));
426
427 char buffer[BYTES_PER_LINE * 3];
428 char ascii_buffer[BYTES_PER_LINE + 1];
429 char *buffer_pos = buffer;
430 char *bytes_pos = bytes;
431 char *bytes_roof = bytes + len;
432 int line_start = 0;
433 int i = 0;
434 int written = 0;
435
436 written += print_in_hook(dst, dstlen, "=> %d bytes @ %p", len, bytes);
437
438 while (bytes_pos < bytes_roof)
439 {
440 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
441 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
442
443 ascii_buffer[i++] =
444 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
445
446 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
447 {
448 int padding = 3 * (BYTES_PER_LINE - i);
449
450 while (padding--)
451 {
452 *buffer_pos++ = ' ';
453 }
454 *buffer_pos++ = '\0';
455 ascii_buffer[i] = '\0';
456
457 written += print_in_hook(dst, dstlen, "\n%4d: %s %s",
458 line_start, buffer, ascii_buffer);
459
460 buffer_pos = buffer;
461 line_start += BYTES_PER_LINE;
462 i = 0;
463 }
464 else
465 {
466 *buffer_pos++ = ' ';
467 }
468 }
469 return written;
470 }