2 * Copyright (C) 2008-2014 Tobias Brunner
3 * Copyright (C) 2005-2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
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>.
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
17 #define _GNU_SOURCE /* for memrchr */
31 #include "collections/enumerator.h"
32 #include "utils/debug.h"
33 #include "utils/chunk.h"
35 ENUM(status_names
, SUCCESS
, NEED_MORE
,
51 * Described in header.
53 void memxor(u_int8_t dst
[], u_int8_t src
[], size_t n
)
57 /* byte wise XOR until dst aligned */
58 for (i
= 0; (uintptr_t)&dst
[i
] % sizeof(long) && i
< n
; i
++)
62 /* try to use words if src shares an aligment with dst */
63 switch (((uintptr_t)&src
[i
] % sizeof(long)))
66 for (m
= n
- sizeof(long); i
<= m
; i
+= sizeof(long))
68 *(long*)&dst
[i
] ^= *(long*)&src
[i
];
72 for (m
= n
- sizeof(int); i
<= m
; i
+= sizeof(int))
74 *(int*)&dst
[i
] ^= *(int*)&src
[i
];
78 for (m
= n
- sizeof(short); i
<= m
; i
+= sizeof(short))
80 *(short*)&dst
[i
] ^= *(short*)&src
[i
];
86 /* byte wise XOR of the rest */
94 * Described in header.
96 void memwipe_noinline(void *ptr
, size_t n
)
98 memwipe_inline(ptr
, n
);
102 * Described in header.
104 void *memstr(const void *haystack
, const char *needle
, size_t n
)
106 const u_char
*pos
= haystack
;
109 if (!haystack
|| !needle
|| (l
= strlen(needle
)) == 0)
113 for (; n
>= l
; ++pos
, --n
)
115 if (memeq(pos
, needle
, l
))
124 * Described in header.
126 void *utils_memrchr(const void *s
, int c
, size_t n
)
135 for (pos
= s
+ n
- 1; pos
>= (u_char
*)s
; pos
--)
137 if (*pos
== (u_char
)c
)
146 * Described in header.
148 char* translate(char *str
, const char *from
, const char *to
)
151 if (strlen(from
) != strlen(to
))
158 if ((match
= strchr(from
, *pos
)) != NULL
)
160 *pos
= to
[match
- from
];
168 * Described in header.
170 char* strreplace(const char *str
, const char *search
, const char *replace
)
172 size_t len
, slen
, rlen
, count
= 0;
173 char *res
, *pos
, *found
, *dst
;
175 if (!str
|| !*str
|| !search
|| !*search
|| !replace
)
179 slen
= strlen(search
);
180 rlen
= strlen(replace
);
183 for (pos
= (char*)str
; (pos
= strstr(pos
, search
)); pos
+= slen
)
192 len
= (found
- str
) + strlen(found
) + count
* (rlen
- slen
);
198 found
= strstr(str
, search
);
203 dst
= res
= malloc(len
+ 1);
208 memcpy(dst
, pos
, len
);
210 memcpy(dst
, replace
, rlen
);
214 while ((found
= strstr(pos
, search
)));
220 * Described in header.
222 char* path_dirname(const char *path
)
226 pos
= path
? strrchr(path
, '/') : NULL
;
229 { /* if path ends with slashes we have to look beyond them */
230 while (pos
> path
&& *pos
== '/')
231 { /* skip trailing slashes */
234 pos
= memrchr(path
, '/', pos
- path
+ 1);
240 while (pos
> path
&& *pos
== '/')
241 { /* skip superfluous slashes */
244 return strndup(path
, pos
- path
+ 1);
248 * Described in header.
250 char* path_basename(const char *path
)
252 char *pos
, *trail
= NULL
;
258 pos
= strrchr(path
, '/');
260 { /* if path ends with slashes we have to look beyond them */
261 while (pos
> path
&& *pos
== '/')
262 { /* skip trailing slashes */
265 if (pos
== path
&& *pos
== '/')
266 { /* contains only slashes */
270 pos
= memrchr(path
, '/', trail
- path
);
272 pos
= pos
? pos
+ 1 : (char*)path
;
273 return trail
? strndup(pos
, trail
- pos
) : strdup(pos
);
277 * Described in header.
279 bool mkdir_p(const char *path
, mode_t mode
)
282 char *pos
, full
[PATH_MAX
];
284 if (!path
|| *path
== '\0')
288 len
= snprintf(full
, sizeof(full
)-1, "%s", path
);
289 if (len
< 0 || len
>= sizeof(full
)-1)
291 DBG1(DBG_LIB
, "path string %s too long", path
);
294 /* ensure that the path ends with a '/' */
295 if (full
[len
-1] != '/')
300 /* skip '/' at the beginning */
305 while ((pos
= strchr(pos
, '/')))
308 if (access(full
, F_OK
) < 0)
311 if (_mkdir(full
) < 0)
313 if (mkdir(full
, mode
) < 0)
316 DBG1(DBG_LIB
, "failed to create directory %s", full
);
326 ENUM(tty_color_names
, TTY_RESET
, TTY_BG_DEF
,
352 * Get the escape string for a given TTY color, empty string on non-tty FILE
354 char* tty_escape_get(int fd
, tty_escape_t escape
)
384 return enum_to_name(tty_color_names
, escape
);
385 /* warn if a excape code is missing */
390 #ifndef HAVE_CLOSEFROM
392 * Described in header.
394 void closefrom(int lowfd
)
396 char fd_dir
[PATH_MAX
];
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)
403 enumerator_t
*enumerator
= enumerator_create_directory(fd_dir
);
407 while (enumerator
->enumerate(enumerator
, &rel
, NULL
, NULL
))
415 enumerator
->destroy(enumerator
);
420 /* ...fall back to closing all fds otherwise */
422 maxfd
= _getmaxstdio();
424 maxfd
= (int)sysconf(_SC_OPEN_MAX
);
430 for (fd
= lowfd
; fd
< maxfd
; fd
++)
435 #endif /* HAVE_CLOSEFROM */
438 * Return monotonic time
440 time_t time_monotonic(timeval_t
*tv
)
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. */
449 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0)
453 tv
->tv_sec
= ts
.tv_sec
;
454 tv
->tv_usec
= ts
.tv_nsec
/ 1000;
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! */
468 if (gettimeofday(tv
, NULL
) != 0)
469 { /* should actually never fail if passed pointers are valid */
502 status_t
return_failed()
510 status_t
return_success()
522 #if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
525 * We use a single mutex for all refcount variables.
527 static pthread_mutex_t ref_mutex
= PTHREAD_MUTEX_INITIALIZER
;
532 refcount_t
ref_get(refcount_t
*ref
)
536 pthread_mutex_lock(&ref_mutex
);
538 pthread_mutex_unlock(&ref_mutex
);
545 bool ref_put(refcount_t
*ref
)
549 pthread_mutex_lock(&ref_mutex
);
550 more_refs
= --(*ref
) > 0;
551 pthread_mutex_unlock(&ref_mutex
);
558 refcount_t
ref_cur(refcount_t
*ref
)
562 pthread_mutex_lock(&ref_mutex
);
564 pthread_mutex_unlock(&ref_mutex
);
569 * Single mutex for all compare and swap operations.
571 static pthread_mutex_t cas_mutex
= PTHREAD_MUTEX_INITIALIZER
;
574 * Compare and swap if equal to old value
576 #define _cas_impl(name, type) \
577 bool cas_##name(type *ptr, type oldval, type newval) \
580 pthread_mutex_lock(&cas_mutex); \
581 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
582 pthread_mutex_unlock(&cas_mutex); \
586 _cas_impl(bool, bool)
587 _cas_impl(ptr
, void*)
589 #endif /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
592 #ifdef HAVE_FMEMOPEN_FALLBACK
594 static int fmemread(chunk_t
*cookie
, char *buf
, int size
)
598 len
= min(size
, cookie
->len
);
599 memcpy(buf
, cookie
->ptr
, len
);
600 *cookie
= chunk_skip(*cookie
, len
);
605 static int fmemwrite(chunk_t
*cookie
, const char *buf
, int size
)
609 len
= min(size
, cookie
->len
);
610 memcpy(cookie
->ptr
, buf
, len
);
611 *cookie
= chunk_skip(*cookie
, len
);
616 static int fmemclose(void *cookie
)
622 FILE *fmemopen(void *buf
, size_t size
, const char *mode
)
631 return funopen(cookie
, (void*)fmemread
, (void*)fmemwrite
, NULL
, fmemclose
);
634 #endif /* FMEMOPEN fallback*/
637 * Described in header.
639 int time_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
640 const void *const *args
)
642 static const char* months
[] = {
643 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
644 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
646 time_t *time
= *((time_t**)(args
[0]));
647 bool utc
= *((int*)(args
[1]));
650 if (*time
== UNDEFINED_TIME
)
652 return print_in_hook(data
, "--- -- --:--:--%s----",
653 utc
? " UTC " : " ");
661 localtime_r(time
, &t
);
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);
669 * Described in header.
671 int time_delta_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
672 const void *const *args
)
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
);
679 if (delta
> 2 * 60 * 60 * 24)
681 delta
/= 60 * 60 * 24;
684 else if (delta
> 2 * 60 * 60)
689 else if (delta
> 2 * 60)
694 return print_in_hook(data
, "%" PRIu64
" %s%s", delta
, unit
,
695 (delta
== 1) ? "" : "s");
699 * Number of bytes per line to dump raw data
701 #define BYTES_PER_LINE 16
703 static char hexdig_upper
[] = "0123456789ABCDEF";
706 * Described in header.
708 int mem_printf_hook(printf_hook_data_t
*data
,
709 printf_hook_spec_t
*spec
, const void *const *args
)
711 char *bytes
= *((void**)(args
[0]));
712 u_int len
= *((int*)(args
[1]));
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
;
723 written
+= print_in_hook(data
, "=> %u bytes @ %p", len
, bytes
);
725 while (bytes_pos
< bytes_roof
)
727 *buffer_pos
++ = hexdig_upper
[(*bytes_pos
>> 4) & 0xF];
728 *buffer_pos
++ = hexdig_upper
[ *bytes_pos
& 0xF];
731 (*bytes_pos
> 31 && *bytes_pos
< 127) ? *bytes_pos
: '.';
733 if (++bytes_pos
== bytes_roof
|| i
== BYTES_PER_LINE
)
735 int padding
= 3 * (BYTES_PER_LINE
- i
);
741 *buffer_pos
++ = '\0';
742 ascii_buffer
[i
] = '\0';
744 written
+= print_in_hook(data
, "\n%4d: %s %s",
745 line_start
, buffer
, ascii_buffer
);
748 line_start
+= BYTES_PER_LINE
;