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