]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils.c
Only close open file descriptors on Linux.
[people/ms/strongswan.git] / src / libstrongswan / utils.c
CommitLineData
552cc11b 1/*
9a8fdc15 2 * Copyright (C) 2008-2011 Tobias Brunner
552cc11b
MW
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.
552cc11b
MW
15 */
16
17#include "utils.h"
18
6c20579a 19#include <sys/stat.h>
552cc11b 20#include <string.h>
552cc11b 21#include <stdio.h>
6c20579a 22#include <unistd.h>
876961cf 23#include <inttypes.h>
74b14b40 24#include <stdint.h>
d24a74c5 25#include <limits.h>
6c20579a 26#include <dirent.h>
f464d750 27#include <time.h>
552cc11b 28
fac3bfa5
TB
29#include "enum.h"
30#include "debug.h"
5051bd23 31#include "utils/enumerator.h"
552cc11b 32
a8809bb0 33ENUM(status_names, SUCCESS, NEED_MORE,
552cc11b
MW
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 */
51void *clalloc(void * pointer, size_t size)
52{
53 void *data;
54 data = malloc(size);
7daf5226 55
552cc11b 56 memcpy(data, pointer, size);
7daf5226 57
552cc11b
MW
58 return (data);
59}
60
61/**
62 * Described in header.
63 */
01e43e31 64void memxor(u_int8_t dst[], u_int8_t src[], size_t n)
552cc11b 65{
01e43e31 66 int m, i;
7daf5226 67
01e43e31 68 /* byte wise XOR until dst aligned */
09846603 69 for (i = 0; (uintptr_t)&dst[i] % sizeof(long) && i < n; i++)
4fd233a7 70 {
01e43e31 71 dst[i] ^= src[i];
4fd233a7 72 }
01e43e31 73 /* try to use words if src shares an aligment with dst */
74b14b40 74 switch (((uintptr_t)&src[i] % sizeof(long)))
552cc11b 75 {
01e43e31
MW
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];
552cc11b
MW
101 }
102}
103
ed678b52
MW
104/**
105 * Described in header.
106 */
107void memwipe_noinline(void *ptr, size_t n)
108{
109 memwipe_inline(ptr, n);
110}
111
81736d7d
TB
112/**
113 * Described in header.
114 */
115void *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
d543d9ca
TB
129/**
130 * Described in header.
131 */
132char* 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
6c20579a
TB
151/**
152 * Described in header.
153 */
154bool mkdir_p(const char *path, mode_t mode)
155{
fc1afcc8 156 int len;
6c20579a
TB
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 {
8b0e0910 166 DBG1(DBG_LIB, "path string %s too long", path);
6c20579a
TB
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 {
8b0e0910 187 DBG1(DBG_LIB, "failed to create directory %s", full);
6c20579a
TB
188 return FALSE;
189 }
190 }
191 *pos = '/';
192 pos++;
193 }
194 return TRUE;
195}
196
9a8fdc15
TB
197#ifndef HAVE_CLOSEFROM
198/**
199 * Described in header.
200 */
201void closefrom(int lowfd)
202{
5051bd23
TB
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))
209 {
210 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
211 if (enumerator)
212 {
213 char *rel, *end;
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 */
9a8fdc15
TB
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
3f310c0d
MW
240/**
241 * Return monotonic time
242 */
243time_t time_monotonic(timeval_t *tv)
244{
b2944d71
TB
245#if defined(HAVE_CLOCK_GETTIME) && \
246 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
247 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
248 /* as we use time_monotonic() for condvar operations, we use the
249 * monotonic time source only if it is also supported by pthread. */
3f310c0d 250 timespec_t ts;
7daf5226 251
3f310c0d
MW
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 }
b2944d71 261#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
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.
3d5818ec
MW
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! */
3f310c0d
MW
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
081ae2eb
MW
278/**
279 * return null
280 */
281void *return_null()
282{
283 return NULL;
284}
285
da17b016
MW
286/**
287 * returns TRUE
288 */
289bool return_true()
290{
291 return TRUE;
292}
293
294/**
295 * returns FALSE
296 */
297bool return_false()
298{
299 return FALSE;
300}
301
502edf42
MW
302/**
303 * returns FAILED
304 */
305status_t return_failed()
306{
307 return FAILED;
308}
309
233b853d
MW
310/**
311 * nop operation
312 */
313void nop()
314{
315}
316
efd0fe21
MW
317#ifndef HAVE_GCC_ATOMIC_OPERATIONS
318#include <pthread.h>
319
552cc11b 320/**
7daf5226 321 * We use a single mutex for all refcount variables.
552cc11b
MW
322 */
323static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
324
325/**
efd0fe21 326 * Increase refcount
552cc11b
MW
327 */
328void ref_get(refcount_t *ref)
329{
330 pthread_mutex_lock(&ref_mutex);
331 (*ref)++;
332 pthread_mutex_unlock(&ref_mutex);
333}
334
335/**
efd0fe21 336 * Decrease refcount
552cc11b
MW
337 */
338bool ref_put(refcount_t *ref)
339{
340 bool more_refs;
7daf5226 341
552cc11b 342 pthread_mutex_lock(&ref_mutex);
21f411b8 343 more_refs = --(*ref) > 0;
552cc11b
MW
344 pthread_mutex_unlock(&ref_mutex);
345 return !more_refs;
346}
efd0fe21 347#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
552cc11b
MW
348
349/**
d25ce370 350 * Described in header.
552cc11b 351 */
d25ce370
TB
352int time_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
353 const void *const *args)
552cc11b
MW
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]));
d25ce370 360 bool utc = *((bool*)(args[1]));;
552cc11b 361 struct tm t;
7daf5226 362
552cc11b
MW
363 if (time == UNDEFINED_TIME)
364 {
d25ce370
TB
365 return print_in_hook(dst, len, "--- -- --:--:--%s----",
366 utc ? " UTC " : " ");
552cc11b
MW
367 }
368 if (utc)
369 {
370 gmtime_r(time, &t);
371 }
372 else
373 {
374 localtime_r(time, &t);
375 }
d25ce370
TB
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);
552cc11b
MW
379}
380
381/**
d25ce370 382 * Described in header.
552cc11b 383 */
d25ce370
TB
384int time_delta_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
385 const void *const *args)
552cc11b
MW
386{
387 char* unit = "second";
d25ce370
TB
388 time_t *arg1 = *((time_t**)(args[0]));
389 time_t *arg2 = *((time_t**)(args[1]));
876961cf 390 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 391
552cc11b
MW
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 }
876961cf
TB
407 return print_in_hook(dst, len, "%" PRIu64 " %s%s", delta, unit,
408 (delta == 1) ? "" : "s");
552cc11b
MW
409}
410
411/**
412 * Number of bytes per line to dump raw data
413 */
414#define BYTES_PER_LINE 16
415
416static char hexdig_upper[] = "0123456789ABCDEF";
417
418/**
d25ce370 419 * Described in header.
552cc11b 420 */
d25ce370
TB
421int mem_printf_hook(char *dst, size_t dstlen,
422 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
423{
424 char *bytes = *((void**)(args[0]));
425 int len = *((size_t*)(args[1]));
7daf5226 426
552cc11b
MW
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;
7daf5226 435
d25ce370 436 written += print_in_hook(dst, dstlen, "=> %d bytes @ %p", len, bytes);
7daf5226 437
552cc11b
MW
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
7daf5226 446 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
447 {
448 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 449
552cc11b
MW
450 while (padding--)
451 {
452 *buffer_pos++ = ' ';
453 }
454 *buffer_pos++ = '\0';
455 ascii_buffer[i] = '\0';
7daf5226 456
d25ce370 457 written += print_in_hook(dst, dstlen, "\n%4d: %s %s",
323f9f99 458 line_start, buffer, ascii_buffer);
7daf5226 459
552cc11b
MW
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}