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