]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils/utils.c
windows: Do not check if having clock_gettime()
[people/ms/strongswan.git] / src / libstrongswan / utils / utils.c
CommitLineData
552cc11b 1/*
766141bc 2 * Copyright (C) 2008-2014 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
766141bc 17#define _GNU_SOURCE /* for memrchr */
4de7401a
MW
18#ifdef WIN32
19/* for GetTickCount64, Windows 7 */
20# define _WIN32_WINNT 0x0601
21#endif
22
23#include "utils.h"
24
6c20579a 25#include <sys/stat.h>
552cc11b 26#include <string.h>
552cc11b 27#include <stdio.h>
6c20579a 28#include <unistd.h>
876961cf 29#include <inttypes.h>
74b14b40 30#include <stdint.h>
d24a74c5 31#include <limits.h>
6c20579a 32#include <dirent.h>
f464d750 33#include <time.h>
66c0801d
MW
34#ifndef WIN32
35# include <signal.h>
36#endif
552cc11b 37
f1c9653e
MW
38#include <library.h>
39#include <utils/debug.h>
40#include <utils/chunk.h>
41#include <collections/enumerator.h>
42#include <threading/spinlock.h>
66c0801d
MW
43#include <threading/mutex.h>
44#include <threading/condvar.h>
552cc11b 45
a8809bb0 46ENUM(status_names, SUCCESS, NEED_MORE,
552cc11b
MW
47 "SUCCESS",
48 "FAILED",
49 "OUT_OF_RES",
50 "ALREADY_DONE",
51 "NOT_SUPPORTED",
52 "INVALID_ARG",
53 "NOT_FOUND",
54 "PARSE_ERROR",
55 "VERIFY_ERROR",
56 "INVALID_STATE",
57 "DESTROY_ME",
58 "NEED_MORE",
59);
60
552cc11b
MW
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{
2ed241ae 117 const u_char *pos = haystack;
7b91011d
TB
118 size_t l;
119
120 if (!haystack || !needle || (l = strlen(needle)) == 0)
121 {
122 return NULL;
123 }
81736d7d
TB
124 for (; n >= l; ++pos, --n)
125 {
126 if (memeq(pos, needle, l))
127 {
128 return (void*)pos;
129 }
130 }
131 return NULL;
132}
133
2ed241ae
TB
134/**
135 * Described in header.
136 */
137void *utils_memrchr(const void *s, int c, size_t n)
138{
139 const u_char *pos;
140
141 if (!s || !n)
142 {
143 return NULL;
144 }
145
146 for (pos = s + n - 1; pos >= (u_char*)s; pos--)
147 {
148 if (*pos == (u_char)c)
149 {
150 return (void*)pos;
151 }
152 }
153 return NULL;
154}
155
d543d9ca
TB
156/**
157 * Described in header.
158 */
159char* translate(char *str, const char *from, const char *to)
160{
161 char *pos = str;
162 if (strlen(from) != strlen(to))
163 {
164 return str;
165 }
166 while (pos && *pos)
167 {
168 char *match;
169 if ((match = strchr(from, *pos)) != NULL)
170 {
171 *pos = to[match - from];
172 }
173 pos++;
174 }
175 return str;
ccb6758e
TB
176}
177
178/**
179 * Described in header.
180 */
181char* strreplace(const char *str, const char *search, const char *replace)
182{
183 size_t len, slen, rlen, count = 0;
184 char *res, *pos, *found, *dst;
185
186 if (!str || !*str || !search || !*search || !replace)
187 {
188 return (char*)str;
189 }
190 slen = strlen(search);
191 rlen = strlen(replace);
192 if (slen != rlen)
193 {
194 for (pos = (char*)str; (pos = strstr(pos, search)); pos += slen)
195 {
196 found = pos;
197 count++;
198 }
199 if (!count)
200 {
201 return (char*)str;
202 }
203 len = (found - str) + strlen(found) + count * (rlen - slen);
204 }
205 else
206 {
207 len = strlen(str);
208 }
209 found = strstr(str, search);
210 if (!found)
211 {
212 return (char*)str;
213 }
214 dst = res = malloc(len + 1);
215 pos = (char*)str;
216 do
217 {
218 len = found - pos;
219 memcpy(dst, pos, len);
220 dst += len;
221 memcpy(dst, replace, rlen);
222 dst += rlen;
223 pos = found + slen;
224 }
225 while ((found = strstr(pos, search)));
226 strcpy(dst, pos);
227 return res;
d543d9ca
TB
228}
229
66c0801d
MW
230#ifdef WIN32
231
232/**
233 * Flag to indicate signaled wait_sigint()
234 */
235static bool sigint_signaled = FALSE;
236
237/**
238 * Condvar to wait in wait_sigint()
239 */
240static condvar_t *sigint_cond;
241
242/**
243 * Mutex to check signaling()
244 */
245static mutex_t *sigint_mutex;
246
247/**
248 * Control handler to catch ^C
249 */
250static BOOL handler(DWORD dwCtrlType)
251{
252 switch (dwCtrlType)
253 {
254 case CTRL_C_EVENT:
255 case CTRL_BREAK_EVENT:
256 case CTRL_CLOSE_EVENT:
257 sigint_mutex->lock(sigint_mutex);
258 sigint_signaled = TRUE;
259 sigint_cond->signal(sigint_cond);
260 sigint_mutex->unlock(sigint_mutex);
261 return TRUE;
262 default:
263 return FALSE;
264 }
265}
266
267/**
268 * Windows variant
269 */
270void wait_sigint()
271{
272 SetConsoleCtrlHandler(handler, TRUE);
273
274 sigint_mutex = mutex_create(MUTEX_TYPE_DEFAULT);
275 sigint_cond = condvar_create(CONDVAR_TYPE_DEFAULT);
276
277 sigint_mutex->lock(sigint_mutex);
278 while (!sigint_signaled)
279 {
280 sigint_cond->wait(sigint_cond, sigint_mutex);
281 }
282 sigint_mutex->unlock(sigint_mutex);
283
284 sigint_mutex->destroy(sigint_mutex);
285 sigint_cond->destroy(sigint_cond);
286}
287
288#else /* !WIN32 */
289
290/**
291 * Unix variant
292 */
293void wait_sigint()
294{
295 sigset_t set;
296 int sig;
297
298 sigemptyset(&set);
299 sigaddset(&set, SIGINT);
300 sigaddset(&set, SIGTERM);
301
302 sigprocmask(SIG_BLOCK, &set, NULL);
303 sigwait(&set, &sig);
304}
305
306#endif
307
766141bc
TB
308/**
309 * Described in header.
310 */
311char* path_dirname(const char *path)
312{
313 char *pos;
314
8182631b 315 pos = path ? strrchr(path, DIRECTORY_SEPARATOR[0]) : NULL;
766141bc
TB
316
317 if (pos && !pos[1])
318 { /* if path ends with slashes we have to look beyond them */
8182631b 319 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
766141bc
TB
320 { /* skip trailing slashes */
321 pos--;
322 }
8182631b 323 pos = memrchr(path, DIRECTORY_SEPARATOR[0], pos - path + 1);
766141bc
TB
324 }
325 if (!pos)
326 {
2496eaff
MW
327#ifdef WIN32
328 if (path && strlen(path))
329 {
330 if ((isalpha(path[0]) && path[1] == ':'))
331 { /* if just a drive letter given, return that as dirname */
332 return chunk_clone(chunk_from_chars(path[0], ':', 0)).ptr;
333 }
334 }
335#endif
766141bc
TB
336 return strdup(".");
337 }
8182631b 338 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
766141bc
TB
339 { /* skip superfluous slashes */
340 pos--;
341 }
342 return strndup(path, pos - path + 1);
343}
344
345/**
346 * Described in header.
347 */
348char* path_basename(const char *path)
349{
350 char *pos, *trail = NULL;
351
352 if (!path || !*path)
353 {
354 return strdup(".");
355 }
8182631b 356 pos = strrchr(path, DIRECTORY_SEPARATOR[0]);
766141bc
TB
357 if (pos && !pos[1])
358 { /* if path ends with slashes we have to look beyond them */
8182631b 359 while (pos > path && *pos == DIRECTORY_SEPARATOR[0])
766141bc
TB
360 { /* skip trailing slashes */
361 pos--;
362 }
8182631b 363 if (pos == path && *pos == DIRECTORY_SEPARATOR[0])
766141bc 364 { /* contains only slashes */
8182631b 365 return strdup(DIRECTORY_SEPARATOR);
766141bc
TB
366 }
367 trail = pos + 1;
8182631b 368 pos = memrchr(path, DIRECTORY_SEPARATOR[0], trail - path);
766141bc
TB
369 }
370 pos = pos ? pos + 1 : (char*)path;
371 return trail ? strndup(pos, trail - pos) : strdup(pos);
372}
373
67b3bcd1
MW
374/**
375 * Described in header.
376 */
377bool path_absolute(const char *path)
378{
379 if (!path)
380 {
381 return FALSE;
382 }
383#ifdef WIN32
384 if (strpfx(path, "\\\\"))
385 { /* UNC */
386 return TRUE;
387 }
388 if (strlen(path) && isalpha(path[0]) && path[1] == ':')
389 { /* drive letter */
390 return TRUE;
391 }
392#else /* !WIN32 */
393 if (path[0] == DIRECTORY_SEPARATOR[0])
394 {
395 return TRUE;
396 }
397#endif
398 return FALSE;
399}
400
6c20579a
TB
401/**
402 * Described in header.
403 */
404bool mkdir_p(const char *path, mode_t mode)
405{
fc1afcc8 406 int len;
6c20579a
TB
407 char *pos, full[PATH_MAX];
408 pos = full;
409 if (!path || *path == '\0')
410 {
411 return TRUE;
412 }
413 len = snprintf(full, sizeof(full)-1, "%s", path);
414 if (len < 0 || len >= sizeof(full)-1)
415 {
8b0e0910 416 DBG1(DBG_LIB, "path string %s too long", path);
6c20579a
TB
417 return FALSE;
418 }
419 /* ensure that the path ends with a '/' */
420 if (full[len-1] != '/')
421 {
422 full[len++] = '/';
423 full[len] = '\0';
424 }
425 /* skip '/' at the beginning */
426 while (*pos == '/')
427 {
428 pos++;
429 }
430 while ((pos = strchr(pos, '/')))
431 {
432 *pos = '\0';
433 if (access(full, F_OK) < 0)
434 {
a3f7dfc1
MW
435#ifdef WIN32
436 if (_mkdir(full) < 0)
437#else
6c20579a 438 if (mkdir(full, mode) < 0)
a3f7dfc1 439#endif
6c20579a 440 {
8b0e0910 441 DBG1(DBG_LIB, "failed to create directory %s", full);
6c20579a
TB
442 return FALSE;
443 }
444 }
445 *pos = '/';
446 pos++;
447 }
448 return TRUE;
449}
450
4d174272
MW
451ENUM(tty_color_names, TTY_RESET, TTY_BG_DEF,
452 "\e[0m",
453 "\e[1m",
454 "\e[4m",
455 "\e[5m",
456 "\e[30m",
457 "\e[31m",
458 "\e[32m",
459 "\e[33m",
460 "\e[34m",
461 "\e[35m",
462 "\e[36m",
463 "\e[37m",
464 "\e[39m",
465 "\e[40m",
466 "\e[41m",
467 "\e[42m",
468 "\e[43m",
469 "\e[44m",
470 "\e[45m",
471 "\e[46m",
472 "\e[47m",
473 "\e[49m",
474);
475
476/**
477 * Get the escape string for a given TTY color, empty string on non-tty FILE
478 */
479char* tty_escape_get(int fd, tty_escape_t escape)
480{
481 if (!isatty(fd))
482 {
483 return "";
484 }
485 switch (escape)
486 {
487 case TTY_RESET:
488 case TTY_BOLD:
489 case TTY_UNDERLINE:
490 case TTY_BLINKING:
1f2b8c8c
MW
491#ifdef WIN32
492 return "";
493#endif
4d174272
MW
494 case TTY_FG_BLACK:
495 case TTY_FG_RED:
496 case TTY_FG_GREEN:
497 case TTY_FG_YELLOW:
498 case TTY_FG_BLUE:
499 case TTY_FG_MAGENTA:
500 case TTY_FG_CYAN:
501 case TTY_FG_WHITE:
502 case TTY_FG_DEF:
503 case TTY_BG_BLACK:
504 case TTY_BG_RED:
505 case TTY_BG_GREEN:
506 case TTY_BG_YELLOW:
507 case TTY_BG_BLUE:
508 case TTY_BG_MAGENTA:
509 case TTY_BG_CYAN:
510 case TTY_BG_WHITE:
511 case TTY_BG_DEF:
512 return enum_to_name(tty_color_names, escape);
1f2b8c8c 513 /* warn if a escape code is missing */
4d174272
MW
514 }
515 return "";
516}
2a595276 517
9a8fdc15
TB
518#ifndef HAVE_CLOSEFROM
519/**
520 * Described in header.
521 */
522void closefrom(int lowfd)
523{
5051bd23
TB
524 char fd_dir[PATH_MAX];
525 int maxfd, fd, len;
526
527 /* try to close only open file descriptors on Linux... */
528 len = snprintf(fd_dir, sizeof(fd_dir), "/proc/%u/fd", getpid());
4a4cf41b 529 if (len > 0 && len < sizeof(fd_dir) && access(fd_dir, F_OK) == 0)
5051bd23
TB
530 {
531 enumerator_t *enumerator = enumerator_create_directory(fd_dir);
532 if (enumerator)
533 {
68fcf917 534 char *rel;
5051bd23
TB
535 while (enumerator->enumerate(enumerator, &rel, NULL, NULL))
536 {
537 fd = atoi(rel);
538 if (fd >= lowfd)
539 {
540 close(fd);
541 }
542 }
543 enumerator->destroy(enumerator);
544 return;
545 }
546 }
547
548 /* ...fall back to closing all fds otherwise */
d3c30b35
MW
549#ifdef WIN32
550 maxfd = _getmaxstdio();
551#else
9a8fdc15 552 maxfd = (int)sysconf(_SC_OPEN_MAX);
d3c30b35 553#endif
9a8fdc15
TB
554 if (maxfd < 0)
555 {
556 maxfd = 256;
557 }
558 for (fd = lowfd; fd < maxfd; fd++)
559 {
560 close(fd);
561 }
562}
563#endif /* HAVE_CLOSEFROM */
564
3f310c0d
MW
565/**
566 * Return monotonic time
567 */
568time_t time_monotonic(timeval_t *tv)
569{
4de7401a
MW
570#ifdef WIN32
571 ULONGLONG ms;
572 time_t s;
573
574 ms = GetTickCount64();
575 s = ms / 1000;
576 if (tv)
577 {
578 tv->tv_sec = s;
579 tv->tv_usec = (ms - (s * 1000)) * 1000;
580 }
581 return s;
582#else /* !WIN32 */
b2944d71
TB
583#if defined(HAVE_CLOCK_GETTIME) && \
584 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
585 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
3d5818ec
MW
586 /* as we use time_monotonic() for condvar operations, we use the
587 * monotonic time source only if it is also supported by pthread. */
3f310c0d 588 timespec_t ts;
7daf5226 589
3f310c0d
MW
590 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
591 {
592 if (tv)
593 {
594 tv->tv_sec = ts.tv_sec;
595 tv->tv_usec = ts.tv_nsec / 1000;
596 }
597 return ts.tv_sec;
598 }
b2944d71 599#endif /* HAVE_CLOCK_GETTIME && (...) */
3f310c0d
MW
600 /* Fallback to non-monotonic timestamps:
601 * On MAC OS X, creating monotonic timestamps is rather difficult. We
602 * could use mach_absolute_time() and catch sleep/wakeup notifications.
3d5818ec
MW
603 * We stick to the simpler (non-monotonic) gettimeofday() for now.
604 * But keep in mind: we need the same time source here as in condvar! */
3f310c0d
MW
605 if (!tv)
606 {
607 return time(NULL);
608 }
609 if (gettimeofday(tv, NULL) != 0)
610 { /* should actually never fail if passed pointers are valid */
611 return -1;
612 }
613 return tv->tv_sec;
4de7401a 614#endif /* !WIN32 */
3f310c0d
MW
615}
616
081ae2eb
MW
617/**
618 * return null
619 */
620void *return_null()
621{
622 return NULL;
623}
624
da17b016
MW
625/**
626 * returns TRUE
627 */
628bool return_true()
629{
630 return TRUE;
631}
632
633/**
634 * returns FALSE
635 */
636bool return_false()
637{
638 return FALSE;
639}
640
502edf42
MW
641/**
642 * returns FAILED
643 */
644status_t return_failed()
645{
646 return FAILED;
647}
648
4755ab50
MW
649/**
650 * returns SUCCESS
651 */
652status_t return_success()
653{
654 return SUCCESS;
655}
656
233b853d
MW
657/**
658 * nop operation
659 */
660void nop()
661{
662}
663
0f603d42 664#if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
efd0fe21 665
552cc11b 666/**
f1c9653e 667 * Spinlock for ref_get/put
552cc11b 668 */
f1c9653e 669static spinlock_t *ref_lock;
552cc11b
MW
670
671/**
efd0fe21 672 * Increase refcount
552cc11b 673 */
3160b92a 674refcount_t ref_get(refcount_t *ref)
552cc11b 675{
3160b92a
MW
676 refcount_t current;
677
f1c9653e 678 ref_lock->lock(ref_lock);
3160b92a 679 current = ++(*ref);
f1c9653e
MW
680 ref_lock->unlock(ref_lock);
681
3160b92a 682 return current;
552cc11b
MW
683}
684
685/**
efd0fe21 686 * Decrease refcount
552cc11b
MW
687 */
688bool ref_put(refcount_t *ref)
689{
690 bool more_refs;
7daf5226 691
f1c9653e 692 ref_lock->lock(ref_lock);
21f411b8 693 more_refs = --(*ref) > 0;
f1c9653e 694 ref_lock->unlock(ref_lock);
552cc11b
MW
695 return !more_refs;
696}
5317dd68 697
efedd0d2
TB
698/**
699 * Current refcount
700 */
701refcount_t ref_cur(refcount_t *ref)
702{
703 refcount_t current;
704
f1c9653e 705 ref_lock->lock(ref_lock);
efedd0d2 706 current = *ref;
f1c9653e
MW
707 ref_lock->unlock(ref_lock);
708
efedd0d2
TB
709 return current;
710}
711
5317dd68 712/**
f1c9653e 713 * Spinlock for all compare and swap operations.
5317dd68 714 */
f1c9653e 715static spinlock_t *cas_lock;
5317dd68
TB
716
717/**
718 * Compare and swap if equal to old value
719 */
720#define _cas_impl(name, type) \
721bool cas_##name(type *ptr, type oldval, type newval) \
722{ \
723 bool swapped; \
f1c9653e 724 cas_lock->lock(cas_lock); \
5317dd68 725 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
f1c9653e 726 cas_lock->unlock(cas_lock); \
5317dd68
TB
727 return swapped; \
728}
729
730_cas_impl(bool, bool)
731_cas_impl(ptr, void*)
732
0f603d42 733#endif /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
552cc11b 734
2077d996 735
9df621d2 736#ifdef HAVE_FMEMOPEN_FALLBACK
2077d996
MW
737
738static int fmemread(chunk_t *cookie, char *buf, int size)
739{
740 int len;
741
742 len = min(size, cookie->len);
743 memcpy(buf, cookie->ptr, len);
744 *cookie = chunk_skip(*cookie, len);
745
746 return len;
747}
748
749static int fmemwrite(chunk_t *cookie, const char *buf, int size)
750{
751 int len;
752
753 len = min(size, cookie->len);
754 memcpy(cookie->ptr, buf, len);
755 *cookie = chunk_skip(*cookie, len);
756
757 return len;
758}
759
760static int fmemclose(void *cookie)
761{
762 free(cookie);
763 return 0;
764}
765
766FILE *fmemopen(void *buf, size_t size, const char *mode)
767{
768 chunk_t *cookie;
769
770 INIT(cookie,
771 .ptr = buf,
772 .len = size,
773 );
774
775 return funopen(cookie, (void*)fmemread, (void*)fmemwrite, NULL, fmemclose);
776}
777
778#endif /* FMEMOPEN fallback*/
779
f1c9653e
MW
780/**
781 * See header
782 */
783void utils_init()
784{
785#ifdef WIN32
786 windows_init();
787#endif
788
789#if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
790 ref_lock = spinlock_create();
791 cas_lock = spinlock_create();
792#endif
793
794 strerror_init();
795}
796
797/**
798 * See header
799 */
800void utils_deinit()
801{
802#ifdef WIN32
803 windows_deinit();
804#endif
805
806#if !defined(HAVE_GCC_ATOMIC_OPERATIONS) && !defined(HAVE_GCC_SYNC_OPERATIONS)
807 ref_lock->destroy(ref_lock);
808 cas_lock->destroy(cas_lock);
809#endif
810
811 strerror_deinit();
812}
813
552cc11b 814/**
d25ce370 815 * Described in header.
552cc11b 816 */
1b40b74d 817int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 818 const void *const *args)
552cc11b
MW
819{
820 static const char* months[] = {
821 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
822 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
823 };
824 time_t *time = *((time_t**)(args[0]));
13f2d3a2 825 bool utc = *((int*)(args[1]));
8f129319 826 struct tm t, *ret = NULL;
7daf5226 827
8f129319 828 if (*time != UNDEFINED_TIME)
552cc11b 829 {
8f129319
MW
830 if (utc)
831 {
832 ret = gmtime_r(time, &t);
833 }
834 else
835 {
836 ret = localtime_r(time, &t);
837 }
552cc11b 838 }
8f129319 839 if (ret == NULL)
552cc11b 840 {
8f129319
MW
841 return print_in_hook(data, "--- -- --:--:--%s----",
842 utc ? " UTC " : " ");
552cc11b 843 }
1b40b74d 844 return print_in_hook(data, "%s %02d %02d:%02d:%02d%s%04d",
d25ce370
TB
845 months[t.tm_mon], t.tm_mday, t.tm_hour, t.tm_min,
846 t.tm_sec, utc ? " UTC " : " ", t.tm_year + 1900);
552cc11b
MW
847}
848
849/**
d25ce370 850 * Described in header.
552cc11b 851 */
1b40b74d 852int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 853 const void *const *args)
552cc11b
MW
854{
855 char* unit = "second";
d25ce370
TB
856 time_t *arg1 = *((time_t**)(args[0]));
857 time_t *arg2 = *((time_t**)(args[1]));
876961cf 858 u_int64_t delta = llabs(*arg1 - *arg2);
7daf5226 859
552cc11b
MW
860 if (delta > 2 * 60 * 60 * 24)
861 {
862 delta /= 60 * 60 * 24;
863 unit = "day";
864 }
865 else if (delta > 2 * 60 * 60)
866 {
867 delta /= 60 * 60;
868 unit = "hour";
869 }
870 else if (delta > 2 * 60)
871 {
872 delta /= 60;
873 unit = "minute";
874 }
1b40b74d 875 return print_in_hook(data, "%" PRIu64 " %s%s", delta, unit,
876961cf 876 (delta == 1) ? "" : "s");
552cc11b
MW
877}
878
879/**
880 * Number of bytes per line to dump raw data
881 */
882#define BYTES_PER_LINE 16
883
884static char hexdig_upper[] = "0123456789ABCDEF";
885
886/**
d25ce370 887 * Described in header.
552cc11b 888 */
1b40b74d 889int mem_printf_hook(printf_hook_data_t *data,
d25ce370 890 printf_hook_spec_t *spec, const void *const *args)
552cc11b
MW
891{
892 char *bytes = *((void**)(args[0]));
817ab8a8 893 u_int len = *((int*)(args[1]));
7daf5226 894
552cc11b
MW
895 char buffer[BYTES_PER_LINE * 3];
896 char ascii_buffer[BYTES_PER_LINE + 1];
897 char *buffer_pos = buffer;
898 char *bytes_pos = bytes;
899 char *bytes_roof = bytes + len;
900 int line_start = 0;
901 int i = 0;
902 int written = 0;
7daf5226 903
1b40b74d 904 written += print_in_hook(data, "=> %u bytes @ %p", len, bytes);
7daf5226 905
552cc11b
MW
906 while (bytes_pos < bytes_roof)
907 {
908 *buffer_pos++ = hexdig_upper[(*bytes_pos >> 4) & 0xF];
909 *buffer_pos++ = hexdig_upper[ *bytes_pos & 0xF];
910
911 ascii_buffer[i++] =
912 (*bytes_pos > 31 && *bytes_pos < 127) ? *bytes_pos : '.';
913
7daf5226 914 if (++bytes_pos == bytes_roof || i == BYTES_PER_LINE)
552cc11b
MW
915 {
916 int padding = 3 * (BYTES_PER_LINE - i);
7daf5226 917
552cc11b
MW
918 while (padding--)
919 {
920 *buffer_pos++ = ' ';
921 }
922 *buffer_pos++ = '\0';
923 ascii_buffer[i] = '\0';
7daf5226 924
1b40b74d 925 written += print_in_hook(data, "\n%4d: %s %s",
323f9f99 926 line_start, buffer, ascii_buffer);
7daf5226 927
552cc11b
MW
928 buffer_pos = buffer;
929 line_start += BYTES_PER_LINE;
930 i = 0;
931 }
932 else
933 {
934 *buffer_pos++ = ' ';
935 }
936 }
937 return written;
938}