]> git.proxmox.com Git - mirror_frr.git/blob - lib/log.c
Merge pull request #4582 from donaldsharp/do_not_warn
[mirror_frr.git] / lib / log.c
1 /*
2 * Logging of zebra
3 * Copyright (C) 1997, 1998, 1999 Kunihiro Ishiguro
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; see the file COPYING; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #define FRR_DEFINE_DESC_TABLE
23
24 #include <zebra.h>
25
26 #include "zclient.h"
27 #include "log.h"
28 #include "log_int.h"
29 #include "memory.h"
30 #include "command.h"
31 #include "lib_errors.h"
32 #include "lib/hook.h"
33 #include "printfrr.h"
34
35 #ifndef SUNOS_5
36 #include <sys/un.h>
37 #endif
38 /* for printstack on solaris */
39 #ifdef HAVE_UCONTEXT_H
40 #include <ucontext.h>
41 #endif
42
43 #ifdef HAVE_LIBUNWIND
44 #define UNW_LOCAL_ONLY
45 #include <libunwind.h>
46 #include <dlfcn.h>
47 #endif
48
49 DEFINE_MTYPE_STATIC(LIB, ZLOG, "Logging")
50
51 /* hook for external logging */
52 DEFINE_HOOK(zebra_ext_log, (int priority, const char *format, va_list args),
53 (priority, format, args));
54
55 static int logfile_fd = -1; /* Used in signal handler. */
56
57 struct zlog *zlog_default = NULL;
58 bool zlog_startup_stderr = true;
59
60 /* lock protecting zlog_default for mt-safe zlog */
61 static pthread_mutex_t loglock = PTHREAD_MUTEX_INITIALIZER;
62
63 const char *zlog_priority[] = {
64 "emergencies", "alerts", "critical", "errors", "warnings",
65 "notifications", "informational", "debugging", NULL,
66 };
67
68 static char zlog_filters[ZLOG_FILTERS_MAX][ZLOG_FILTER_LENGTH_MAX + 1];
69 static uint8_t zlog_filter_count;
70
71 /*
72 * look for a match on the filter in the current filters, loglock must be held
73 */
74 static int zlog_filter_lookup(const char *lookup)
75 {
76 for (int i = 0; i < zlog_filter_count; i++) {
77 if (strncmp(lookup, zlog_filters[i], sizeof(zlog_filters[0]))
78 == 0)
79 return i;
80 }
81 return -1;
82 }
83
84 void zlog_filter_clear(void)
85 {
86 pthread_mutex_lock(&loglock);
87 zlog_filter_count = 0;
88 pthread_mutex_unlock(&loglock);
89 }
90
91 int zlog_filter_add(const char *filter)
92 {
93 pthread_mutex_lock(&loglock);
94
95 int ret = 0;
96
97 if (zlog_filter_count >= ZLOG_FILTERS_MAX) {
98 ret = 1;
99 goto done;
100 }
101
102 if (zlog_filter_lookup(filter) != -1) {
103 /* Filter already present */
104 ret = -1;
105 goto done;
106 }
107
108 strlcpy(zlog_filters[zlog_filter_count], filter,
109 sizeof(zlog_filters[0]));
110
111 if (zlog_filters[zlog_filter_count][0] == '\0') {
112 /* Filter was either empty or didn't get copied correctly */
113 ret = -1;
114 goto done;
115 }
116
117 zlog_filter_count++;
118
119 done:
120 pthread_mutex_unlock(&loglock);
121 return ret;
122 }
123
124 int zlog_filter_del(const char *filter)
125 {
126 pthread_mutex_lock(&loglock);
127
128 int found_idx = zlog_filter_lookup(filter);
129 int last_idx = zlog_filter_count - 1;
130 int ret = 0;
131
132 if (found_idx == -1) {
133 /* Didn't find the filter to delete */
134 ret = -1;
135 goto done;
136 }
137
138 /* Adjust the filter array */
139 memmove(zlog_filters[found_idx], zlog_filters[found_idx + 1],
140 (last_idx - found_idx) * sizeof(zlog_filters[0]));
141
142 zlog_filter_count--;
143
144 done:
145 pthread_mutex_unlock(&loglock);
146 return ret;
147 }
148
149 /* Dump all filters to buffer, delimited by new line */
150 int zlog_filter_dump(char *buf, size_t max_size)
151 {
152 pthread_mutex_lock(&loglock);
153
154 int ret = 0;
155 int len = 0;
156
157 for (int i = 0; i < zlog_filter_count; i++) {
158 ret = snprintf(buf + len, max_size - len, " %s\n",
159 zlog_filters[i]);
160 len += ret;
161 if ((ret < 0) || ((size_t)len >= max_size)) {
162 len = -1;
163 goto done;
164 }
165 }
166
167 done:
168 pthread_mutex_unlock(&loglock);
169 return len;
170 }
171
172 /*
173 * write_wrapper
174 *
175 * glibc has declared that the return value from write *must* not be
176 * ignored.
177 * gcc see's this problem and issues a warning for the line.
178 *
179 * Why is this a big deal you say? Because both of them are right
180 * and if you have -Werror enabled then all calls to write
181 * generate a build error and the build stops.
182 *
183 * clang has helpfully allowed this construct:
184 * (void)write(...)
185 * to tell the compiler yeah I know it has a return value
186 * I don't care about it at this time.
187 * gcc doesn't have this ability.
188 *
189 * This code was written such that it didn't care about the
190 * return value from write. At this time do I want
191 * to go through and fix and test this code for correctness.
192 * So just wrapper the bad behavior and move on.
193 */
194 static void write_wrapper(int fd, const void *buf, size_t count)
195 {
196 if (write(fd, buf, count) <= 0)
197 return;
198
199 return;
200 }
201
202 /**
203 * Looks up a message in a message list by key.
204 *
205 * If the message is not found, returns the provided error message.
206 *
207 * Terminates when it hits a struct message that's all zeros.
208 *
209 * @param mz the message list
210 * @param kz the message key
211 * @param nf the message to return if not found
212 * @return the message
213 */
214 const char *lookup_msg(const struct message *mz, int kz, const char *nf)
215 {
216 static struct message nt = {0};
217 const char *rz = nf ? nf : "(no message found)";
218 const struct message *pnt;
219 for (pnt = mz; memcmp(pnt, &nt, sizeof(struct message)); pnt++)
220 if (pnt->key == kz) {
221 rz = pnt->str ? pnt->str : rz;
222 break;
223 }
224 return rz;
225 }
226
227 /* For time string format. */
228 size_t quagga_timestamp(int timestamp_precision, char *buf, size_t buflen)
229 {
230 static struct {
231 time_t last;
232 size_t len;
233 char buf[28];
234 } cache;
235 struct timeval clock;
236
237 gettimeofday(&clock, NULL);
238
239 /* first, we update the cache if the time has changed */
240 if (cache.last != clock.tv_sec) {
241 struct tm *tm;
242 cache.last = clock.tv_sec;
243 tm = localtime(&cache.last);
244 cache.len = strftime(cache.buf, sizeof(cache.buf),
245 "%Y/%m/%d %H:%M:%S", tm);
246 }
247 /* note: it's not worth caching the subsecond part, because
248 chances are that back-to-back calls are not sufficiently close
249 together
250 for the clock not to have ticked forward */
251
252 if (buflen > cache.len) {
253 memcpy(buf, cache.buf, cache.len);
254 if ((timestamp_precision > 0)
255 && (buflen > cache.len + 1 + timestamp_precision)) {
256 /* should we worry about locale issues? */
257 static const int divisor[] = {0, 100000, 10000, 1000,
258 100, 10, 1};
259 int prec;
260 char *p = buf + cache.len + 1
261 + (prec = timestamp_precision);
262 *p-- = '\0';
263 while (prec > 6)
264 /* this is unlikely to happen, but protect anyway */
265 {
266 *p-- = '0';
267 prec--;
268 }
269 clock.tv_usec /= divisor[prec];
270 do {
271 *p-- = '0' + (clock.tv_usec % 10);
272 clock.tv_usec /= 10;
273 } while (--prec > 0);
274 *p = '.';
275 return cache.len + 1 + timestamp_precision;
276 }
277 buf[cache.len] = '\0';
278 return cache.len;
279 }
280 if (buflen > 0)
281 buf[0] = '\0';
282 return 0;
283 }
284
285 static inline void timestamp_control_render(struct timestamp_control *ctl)
286 {
287 if (!ctl->already_rendered) {
288 ctl->len = quagga_timestamp(ctl->precision, ctl->buf,
289 sizeof(ctl->buf));
290 ctl->already_rendered = 1;
291 }
292 }
293
294 /* Utility routine for current time printing. */
295 static void time_print(FILE *fp, struct timestamp_control *ctl)
296 {
297 timestamp_control_render(ctl);
298 fprintf(fp, "%s ", ctl->buf);
299 }
300
301 static int time_print_buf(char *buf, int len, int max_size,
302 struct timestamp_control *ctl)
303 {
304 timestamp_control_render(ctl);
305
306 if (ctl->len + 1 >= (unsigned long)max_size)
307 return -1;
308
309 return snprintf(buf + len, max_size - len, "%s ", ctl->buf);
310 }
311
312 static void vzlog_file(struct zlog *zl, struct timestamp_control *tsctl,
313 const char *proto_str, int record_priority, int priority,
314 FILE *fp, const char *msg)
315 {
316 time_print(fp, tsctl);
317 if (record_priority)
318 fprintf(fp, "%s: ", zlog_priority[priority]);
319
320 fprintf(fp, "%s%s\n", proto_str, msg);
321 fflush(fp);
322 }
323
324 /* Search a buf for the filter strings, loglock must be held */
325 static int search_buf(const char *buf)
326 {
327 char *found = NULL;
328
329 for (int i = 0; i < zlog_filter_count; i++) {
330 found = strstr(buf, zlog_filters[i]);
331 if (found != NULL)
332 return 0;
333 }
334
335 return -1;
336 }
337
338 /* Filter out a log */
339 static int vzlog_filter(struct zlog *zl, struct timestamp_control *tsctl,
340 const char *proto_str, int priority, const char *msg)
341 {
342 int len = 0;
343 int ret = 0;
344 char buf[1024] = "";
345
346 ret = time_print_buf(buf, len, sizeof(buf), tsctl);
347
348 len += ret;
349 if ((ret < 0) || ((size_t)len >= sizeof(buf)))
350 goto search;
351
352 if (zl && zl->record_priority)
353 snprintf(buf + len, sizeof(buf) - len, "%s: %s: %s",
354 zlog_priority[priority], proto_str, msg);
355 else
356 snprintf(buf + len, sizeof(buf) - len, "%s: %s", proto_str,
357 msg);
358
359 search:
360 return search_buf(buf);
361 }
362
363 /* va_list version of zlog. */
364 void vzlog(int priority, const char *format, va_list args)
365 {
366 pthread_mutex_lock(&loglock);
367
368 char proto_str[32] = "";
369 int original_errno = errno;
370 struct timestamp_control tsctl = {};
371 tsctl.already_rendered = 0;
372 struct zlog *zl = zlog_default;
373 char buf[256], *msg;
374
375 if (zl == NULL) {
376 tsctl.precision = 0;
377 } else {
378 tsctl.precision = zl->timestamp_precision;
379 if (zl->instance)
380 sprintf(proto_str, "%s[%d]: ", zl->protoname,
381 zl->instance);
382 else
383 sprintf(proto_str, "%s: ", zl->protoname);
384 }
385
386 msg = vasnprintfrr(MTYPE_TMP, buf, sizeof(buf), format, args);
387
388 /* If it doesn't match on a filter, do nothing with the debug log */
389 if ((priority == LOG_DEBUG) && zlog_filter_count
390 && vzlog_filter(zl, &tsctl, proto_str, priority, msg)) {
391 pthread_mutex_unlock(&loglock);
392 goto out;
393 }
394
395 /* call external hook */
396 hook_call(zebra_ext_log, priority, format, args);
397
398 /* When zlog_default is also NULL, use stderr for logging. */
399 if (zl == NULL) {
400 time_print(stderr, &tsctl);
401 fprintf(stderr, "%s: %s\n", "unknown", msg);
402 fflush(stderr);
403 goto out;
404 }
405
406 /* Syslog output */
407 if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG])
408 syslog(priority | zlog_default->facility, "%s", msg);
409
410 /* File output. */
411 if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
412 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
413 zl->fp, msg);
414
415 /* fixed-config logging to stderr while we're stating up & haven't
416 * daemonized / reached mainloop yet
417 *
418 * note the "else" on stdout output -- we don't want to print the same
419 * message to both stderr and stdout. */
420 if (zlog_startup_stderr && priority <= LOG_WARNING)
421 vzlog_file(zl, &tsctl, proto_str, 1, priority, stderr, msg);
422 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
423 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
424 stdout, msg);
425
426 /* Terminal monitor. */
427 if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
428 vty_log((zl->record_priority ? zlog_priority[priority] : NULL),
429 proto_str, msg, &tsctl);
430
431 out:
432 if (msg != buf)
433 XFREE(MTYPE_TMP, msg);
434 errno = original_errno;
435 pthread_mutex_unlock(&loglock);
436 }
437
438 int vzlog_test(int priority)
439 {
440 pthread_mutex_lock(&loglock);
441
442 int ret = 0;
443
444 struct zlog *zl = zlog_default;
445
446 /* When zlog_default is also NULL, use stderr for logging. */
447 if (zl == NULL)
448 ret = 1;
449 /* Syslog output */
450 else if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG])
451 ret = 1;
452 /* File output. */
453 else if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
454 ret = 1;
455 /* stdout output. */
456 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
457 ret = 1;
458 /* Terminal monitor. */
459 else if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
460 ret = 1;
461
462 pthread_mutex_unlock(&loglock);
463
464 return ret;
465 }
466
467 /*
468 * crash handling
469 *
470 * NB: only AS-Safe (async-signal) functions can be used here!
471 */
472
473 /* Needs to be enhanced to support Solaris. */
474 static int syslog_connect(void)
475 {
476 #ifdef SUNOS_5
477 return -1;
478 #else
479 int fd;
480 struct sockaddr_un addr;
481
482 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
483 return -1;
484 addr.sun_family = AF_UNIX;
485 #ifdef _PATH_LOG
486 #define SYSLOG_SOCKET_PATH _PATH_LOG
487 #else
488 #define SYSLOG_SOCKET_PATH "/dev/log"
489 #endif
490 strlcpy(addr.sun_path, SYSLOG_SOCKET_PATH, sizeof(addr.sun_path));
491 #undef SYSLOG_SOCKET_PATH
492 if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
493 close(fd);
494 return -1;
495 }
496 return fd;
497 #endif
498 }
499
500 static void syslog_sigsafe(int priority, const char *msg, size_t msglen)
501 {
502 static int syslog_fd = -1;
503 char buf[sizeof("<1234567890>ripngd[1234567890]: ") + msglen + 50];
504 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
505
506 if ((syslog_fd < 0) && ((syslog_fd = syslog_connect()) < 0))
507 return;
508
509 /* forget about the timestamp, too difficult in a signal handler */
510 bprintfrr(&fb, "<%d>%s", priority, zlog_default->ident);
511 if (zlog_default->syslog_options & LOG_PID)
512 bprintfrr(&fb, "[%ld]", (long)getpid());
513 bprintfrr(&fb, ": %s", msg);
514 write_wrapper(syslog_fd, fb.buf, fb.pos - fb.buf);
515 }
516
517 static int open_crashlog(void)
518 {
519 char crashlog_buf[PATH_MAX];
520 const char *crashlog_default = "/var/tmp/frr.crashlog", *crashlog;
521
522 if (!zlog_default || !zlog_default->ident)
523 crashlog = crashlog_default;
524 else {
525 snprintfrr(crashlog_buf, sizeof(crashlog_buf),
526 "/var/tmp/frr.%s.crashlog", zlog_default->ident);
527 crashlog = crashlog_buf;
528 }
529 return open(crashlog, O_WRONLY | O_CREAT | O_EXCL, LOGFILE_MASK);
530 }
531
532 /* N.B. implicit priority is most severe */
533 #define PRI LOG_CRIT
534
535 static void crash_write(struct fbuf *fb, char *msgstart)
536 {
537 if (fb->pos == fb->buf)
538 return;
539 if (!msgstart)
540 msgstart = fb->buf;
541
542 /* If no file logging configured, try to write to fallback log file. */
543 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
544 write(logfile_fd, fb->buf, fb->pos - fb->buf);
545 if (!zlog_default)
546 write(STDERR_FILENO, fb->buf, fb->pos - fb->buf);
547 else {
548 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
549 write(STDOUT_FILENO, fb->buf, fb->pos - fb->buf);
550 /* Remove trailing '\n' for monitor and syslog */
551 fb->pos--;
552 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
553 vty_log_fixed(fb->buf, fb->pos - fb->buf);
554 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
555 syslog_sigsafe(PRI | zlog_default->facility, msgstart,
556 fb->pos - msgstart);
557 }
558 }
559
560 /* Note: the goal here is to use only async-signal-safe functions. */
561 void zlog_signal(int signo, const char *action, void *siginfo_v,
562 void *program_counter)
563 {
564 #ifdef SA_SIGINFO
565 siginfo_t *siginfo = siginfo_v;
566 #endif
567 time_t now;
568 char buf[sizeof("DEFAULT: Received signal S at T (si_addr 0xP, PC 0xP); aborting...")
569 + 100];
570 char *msgstart;
571 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
572
573 time(&now);
574 if (zlog_default)
575 bprintfrr(&fb, "%s: ", zlog_default->protoname);
576
577 msgstart = fb.pos;
578
579 bprintfrr(&fb, "Received signal %d at %lld", signo, (long long)now);
580 #ifdef SA_SIGINFO
581 if (program_counter)
582 bprintfrr(&fb, " (si_addr 0x%tx, PC 0x%tx)",
583 (ptrdiff_t)siginfo->si_addr,
584 (ptrdiff_t)program_counter);
585 else
586 bprintfrr(&fb, " (si_addr 0x%tx)",
587 (ptrdiff_t)siginfo->si_addr);
588 #endif /* SA_SIGINFO */
589 bprintfrr(&fb, "; %s\n", action);
590
591 crash_write(&fb, msgstart);
592
593 zlog_backtrace_sigsafe(PRI, program_counter);
594
595 fb.pos = buf;
596
597 struct thread *tc;
598 tc = pthread_getspecific(thread_current);
599
600 if (!tc)
601 bprintfrr(&fb, "no thread information available\n");
602 else
603 bprintfrr(&fb, "in thread %s scheduled from %s:%d\n",
604 tc->funcname, tc->schedfrom, tc->schedfrom_line);
605
606 crash_write(&fb, NULL);
607 }
608
609 /* Log a backtrace using only async-signal-safe functions.
610 Needs to be enhanced to support syslog logging. */
611 void zlog_backtrace_sigsafe(int priority, void *program_counter)
612 {
613 #ifdef HAVE_LIBUNWIND
614 char buf[256];
615 struct fbuf fb = { .buf = buf, .len = sizeof(buf) };
616 unw_cursor_t cursor;
617 unw_context_t uc;
618 unw_word_t ip, off, sp;
619 Dl_info dlinfo;
620
621 unw_getcontext(&uc);
622 unw_init_local(&cursor, &uc);
623 while (unw_step(&cursor) > 0) {
624 char name[128] = "?";
625
626 unw_get_reg(&cursor, UNW_REG_IP, &ip);
627 unw_get_reg(&cursor, UNW_REG_SP, &sp);
628
629 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off))
630 snprintfrr(name, sizeof(name), "%s+%#lx",
631 buf, (long)off);
632
633 fb.pos = buf;
634 if (unw_is_signal_frame(&cursor))
635 bprintfrr(&fb, " ---- signal ----\n");
636 bprintfrr(&fb, "%-30s %16lx %16lx", name, (long)ip, (long)sp);
637 if (dladdr((void *)ip, &dlinfo))
638 bprintfrr(&fb, " %s (mapped at %p)",
639 dlinfo.dli_fname, dlinfo.dli_fbase);
640 bprintfrr(&fb, "\n");
641 crash_write(&fb, NULL);
642 }
643 #elif defined(HAVE_GLIBC_BACKTRACE) || defined(HAVE_PRINTSTACK)
644 static const char pclabel[] = "Program counter: ";
645 void *array[64];
646 int size;
647 char buf[128];
648 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
649 char **bt = NULL;
650
651 #ifdef HAVE_GLIBC_BACKTRACE
652 size = backtrace(array, array_size(array));
653 if (size <= 0 || (size_t)size > array_size(array))
654 return;
655
656 #define DUMP(FD) \
657 { \
658 if (program_counter) { \
659 write_wrapper(FD, pclabel, sizeof(pclabel) - 1); \
660 backtrace_symbols_fd(&program_counter, 1, FD); \
661 } \
662 write_wrapper(FD, fb.buf, fb.pos - fb.buf); \
663 backtrace_symbols_fd(array, size, FD); \
664 }
665 #elif defined(HAVE_PRINTSTACK)
666 size = 0;
667
668 #define DUMP(FD) \
669 { \
670 if (program_counter) \
671 write_wrapper((FD), pclabel, sizeof(pclabel) - 1); \
672 write_wrapper((FD), fb.buf, fb.pos - fb.buf); \
673 printstack((FD)); \
674 }
675 #endif /* HAVE_GLIBC_BACKTRACE, HAVE_PRINTSTACK */
676
677 bprintfrr(&fb, "Backtrace for %d stack frames:\n", size);
678
679 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
680 DUMP(logfile_fd)
681 if (!zlog_default)
682 DUMP(STDERR_FILENO)
683 else {
684 if (priority <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
685 DUMP(STDOUT_FILENO)
686 /* Remove trailing '\n' for monitor and syslog */
687 fb.pos--;
688 if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
689 vty_log_fixed(fb.buf, fb.pos - fb.buf);
690 if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
691 syslog_sigsafe(priority | zlog_default->facility,
692 fb.buf, fb.pos - fb.buf);
693 {
694 int i;
695 #ifdef HAVE_GLIBC_BACKTRACE
696 bt = backtrace_symbols(array, size);
697 #endif
698 /* Just print the function addresses. */
699 for (i = 0; i < size; i++) {
700 fb.pos = buf;
701 if (bt)
702 bprintfrr(&fb, "%s", bt[i]);
703 else
704 bprintfrr(&fb, "[bt %d] 0x%tx", i,
705 (ptrdiff_t)(array[i]));
706 if (priority
707 <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
708 vty_log_fixed(fb.buf, fb.pos - fb.buf);
709 if (priority
710 <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
711 syslog_sigsafe(priority
712 | zlog_default->facility,
713 fb.buf, fb.pos - fb.buf);
714 }
715 if (bt)
716 free(bt);
717 }
718 }
719 #undef DUMP
720 #endif /* HAVE_STRACK_TRACE */
721 }
722
723 void zlog_backtrace(int priority)
724 {
725 #ifdef HAVE_LIBUNWIND
726 char buf[100];
727 unw_cursor_t cursor;
728 unw_context_t uc;
729 unw_word_t ip, off, sp;
730 Dl_info dlinfo;
731
732 unw_getcontext(&uc);
733 unw_init_local(&cursor, &uc);
734 zlog(priority, "Backtrace:");
735 while (unw_step(&cursor) > 0) {
736 char name[128] = "?";
737
738 unw_get_reg(&cursor, UNW_REG_IP, &ip);
739 unw_get_reg(&cursor, UNW_REG_SP, &sp);
740
741 if (unw_is_signal_frame(&cursor))
742 zlog(priority, " ---- signal ----");
743
744 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off))
745 snprintf(name, sizeof(name), "%s+%#lx",
746 buf, (long)off);
747
748 if (dladdr((void *)ip, &dlinfo))
749 zlog(priority, "%-30s %16lx %16lx %s (mapped at %p)",
750 name, (long)ip, (long)sp,
751 dlinfo.dli_fname, dlinfo.dli_fbase);
752 else
753 zlog(priority, "%-30s %16lx %16lx",
754 name, (long)ip, (long)sp);
755 }
756 #elif defined(HAVE_GLIBC_BACKTRACE)
757 void *array[20];
758 int size, i;
759 char **strings;
760
761 size = backtrace(array, array_size(array));
762 if (size <= 0 || (size_t)size > array_size(array)) {
763 flog_err_sys(
764 EC_LIB_SYSTEM_CALL,
765 "Cannot get backtrace, returned invalid # of frames %d "
766 "(valid range is between 1 and %lu)",
767 size, (unsigned long)(array_size(array)));
768 return;
769 }
770 zlog(priority, "Backtrace for %d stack frames:", size);
771 if (!(strings = backtrace_symbols(array, size))) {
772 flog_err_sys(EC_LIB_SYSTEM_CALL,
773 "Cannot get backtrace symbols (out of memory?)");
774 for (i = 0; i < size; i++)
775 zlog(priority, "[bt %d] %p", i, array[i]);
776 } else {
777 for (i = 0; i < size; i++)
778 zlog(priority, "[bt %d] %s", i, strings[i]);
779 free(strings);
780 }
781 #else /* !HAVE_GLIBC_BACKTRACE && !HAVE_LIBUNWIND */
782 zlog(priority, "No backtrace available on this platform.");
783 #endif
784 }
785
786 void zlog(int priority, const char *format, ...)
787 {
788 va_list args;
789
790 va_start(args, format);
791 vzlog(priority, format, args);
792 va_end(args);
793 }
794
795 #define ZLOG_FUNC(FUNCNAME, PRIORITY) \
796 void FUNCNAME(const char *format, ...) \
797 { \
798 va_list args; \
799 va_start(args, format); \
800 vzlog(PRIORITY, format, args); \
801 va_end(args); \
802 }
803
804 ZLOG_FUNC(zlog_err, LOG_ERR)
805
806 ZLOG_FUNC(zlog_warn, LOG_WARNING)
807
808 ZLOG_FUNC(zlog_info, LOG_INFO)
809
810 ZLOG_FUNC(zlog_notice, LOG_NOTICE)
811
812 ZLOG_FUNC(zlog_debug, LOG_DEBUG)
813
814 #undef ZLOG_FUNC
815
816 void zlog_thread_info(int log_level)
817 {
818 struct thread *tc;
819 tc = pthread_getspecific(thread_current);
820
821 if (tc)
822 zlog(log_level,
823 "Current thread function %s, scheduled from "
824 "file %s, line %u",
825 tc->funcname, tc->schedfrom, tc->schedfrom_line);
826 else
827 zlog(log_level, "Current thread not known/applicable");
828 }
829
830 void _zlog_assert_failed(const char *assertion, const char *file,
831 unsigned int line, const char *function)
832 {
833 /* Force fallback file logging? */
834 if (zlog_default && !zlog_default->fp
835 && ((logfile_fd = open_crashlog()) >= 0)
836 && ((zlog_default->fp = fdopen(logfile_fd, "w")) != NULL))
837 zlog_default->maxlvl[ZLOG_DEST_FILE] = LOG_ERR;
838 zlog(LOG_CRIT, "Assertion `%s' failed in file %s, line %u, function %s",
839 assertion, file, line, (function ? function : "?"));
840 zlog_backtrace(LOG_CRIT);
841 zlog_thread_info(LOG_CRIT);
842 log_memstats(stderr, "log");
843 abort();
844 }
845
846 void memory_oom(size_t size, const char *name)
847 {
848 flog_err_sys(EC_LIB_SYSTEM_CALL,
849 "out of memory: failed to allocate %zu bytes for %s"
850 "object",
851 size, name);
852 zlog_backtrace(LOG_ERR);
853 abort();
854 }
855
856 /* Open log stream */
857 void openzlog(const char *progname, const char *protoname,
858 unsigned short instance, int syslog_flags, int syslog_facility)
859 {
860 struct zlog *zl;
861 unsigned int i;
862
863 zl = XCALLOC(MTYPE_ZLOG, sizeof(struct zlog));
864
865 zl->ident = progname;
866 zl->protoname = protoname;
867 zl->instance = instance;
868 zl->facility = syslog_facility;
869 zl->syslog_options = syslog_flags;
870
871 /* Set default logging levels. */
872 for (i = 0; i < array_size(zl->maxlvl); i++)
873 zl->maxlvl[i] = ZLOG_DISABLED;
874 zl->maxlvl[ZLOG_DEST_MONITOR] = LOG_DEBUG;
875 zl->default_lvl = LOG_DEBUG;
876
877 openlog(progname, syslog_flags, zl->facility);
878
879 pthread_mutex_lock(&loglock);
880 zlog_default = zl;
881 pthread_mutex_unlock(&loglock);
882
883 #ifdef HAVE_GLIBC_BACKTRACE
884 /* work around backtrace() using lazily resolved dynamically linked
885 * symbols, which will otherwise cause funny breakage in the SEGV
886 * handler.
887 * (particularly, the dynamic linker can call malloc(), which uses locks
888 * in programs linked with -pthread, thus can deadlock.) */
889 void *bt[4];
890 backtrace(bt, array_size(bt));
891 free(backtrace_symbols(bt, 0));
892 backtrace_symbols_fd(bt, 0, 0);
893 #endif
894 }
895
896 void closezlog(void)
897 {
898 pthread_mutex_lock(&loglock);
899 struct zlog *zl = zlog_default;
900
901 closelog();
902
903 if (zl->fp != NULL)
904 fclose(zl->fp);
905
906 XFREE(MTYPE_ZLOG, zl->filename);
907
908 XFREE(MTYPE_ZLOG, zl);
909 zlog_default = NULL;
910 pthread_mutex_unlock(&loglock);
911 }
912
913 /* Called from command.c. */
914 void zlog_set_level(zlog_dest_t dest, int log_level)
915 {
916 pthread_mutex_lock(&loglock);
917 zlog_default->maxlvl[dest] = log_level;
918 pthread_mutex_unlock(&loglock);
919 }
920
921 int zlog_set_file(const char *filename, int log_level)
922 {
923 struct zlog *zl;
924 FILE *fp;
925 mode_t oldumask;
926 int ret = 1;
927
928 /* There is opend file. */
929 zlog_reset_file();
930
931 /* Open file. */
932 oldumask = umask(0777 & ~LOGFILE_MASK);
933 fp = fopen(filename, "a");
934 umask(oldumask);
935 if (fp == NULL) {
936 ret = 0;
937 } else {
938 pthread_mutex_lock(&loglock);
939 zl = zlog_default;
940
941 /* Set flags. */
942 zl->filename = XSTRDUP(MTYPE_ZLOG, filename);
943 zl->maxlvl[ZLOG_DEST_FILE] = log_level;
944 zl->fp = fp;
945 logfile_fd = fileno(fp);
946 pthread_mutex_unlock(&loglock);
947 }
948
949 return ret;
950 }
951
952 /* Reset opend file. */
953 int zlog_reset_file(void)
954 {
955 pthread_mutex_lock(&loglock);
956
957 struct zlog *zl = zlog_default;
958
959 if (zl->fp)
960 fclose(zl->fp);
961 zl->fp = NULL;
962 logfile_fd = -1;
963 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
964
965 XFREE(MTYPE_ZLOG, zl->filename);
966 zl->filename = NULL;
967
968 pthread_mutex_unlock(&loglock);
969
970 return 1;
971 }
972
973 /* Reopen log file. */
974 int zlog_rotate(void)
975 {
976 pthread_mutex_lock(&loglock);
977
978 struct zlog *zl = zlog_default;
979 int level;
980 int ret = 1;
981
982 if (zl->fp)
983 fclose(zl->fp);
984 zl->fp = NULL;
985 logfile_fd = -1;
986 level = zl->maxlvl[ZLOG_DEST_FILE];
987 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
988
989 if (zl->filename) {
990 mode_t oldumask;
991 int save_errno;
992
993 oldumask = umask(0777 & ~LOGFILE_MASK);
994 zl->fp = fopen(zl->filename, "a");
995 save_errno = errno;
996 umask(oldumask);
997 if (zl->fp == NULL) {
998
999 pthread_mutex_unlock(&loglock);
1000
1001 flog_err_sys(
1002 EC_LIB_SYSTEM_CALL,
1003 "Log rotate failed: cannot open file %s for append: %s",
1004 zl->filename, safe_strerror(save_errno));
1005 ret = -1;
1006
1007 pthread_mutex_lock(&loglock);
1008 } else {
1009 logfile_fd = fileno(zl->fp);
1010 zl->maxlvl[ZLOG_DEST_FILE] = level;
1011 }
1012 }
1013
1014 pthread_mutex_unlock(&loglock);
1015
1016 return ret;
1017 }
1018
1019 /* Wrapper around strerror to handle case where it returns NULL. */
1020 const char *safe_strerror(int errnum)
1021 {
1022 const char *s = strerror(errnum);
1023 return (s != NULL) ? s : "Unknown error";
1024 }
1025
1026 #define DESC_ENTRY(T) [(T)] = { (T), (#T), '\0' }
1027 static const struct zebra_desc_table command_types[] = {
1028 DESC_ENTRY(ZEBRA_INTERFACE_ADD),
1029 DESC_ENTRY(ZEBRA_INTERFACE_DELETE),
1030 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_ADD),
1031 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_DELETE),
1032 DESC_ENTRY(ZEBRA_INTERFACE_UP),
1033 DESC_ENTRY(ZEBRA_INTERFACE_DOWN),
1034 DESC_ENTRY(ZEBRA_INTERFACE_SET_MASTER),
1035 DESC_ENTRY(ZEBRA_ROUTE_ADD),
1036 DESC_ENTRY(ZEBRA_ROUTE_DELETE),
1037 DESC_ENTRY(ZEBRA_ROUTE_NOTIFY_OWNER),
1038 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ADD),
1039 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DELETE),
1040 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_ADD),
1041 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_DELETE),
1042 DESC_ENTRY(ZEBRA_ROUTER_ID_ADD),
1043 DESC_ENTRY(ZEBRA_ROUTER_ID_DELETE),
1044 DESC_ENTRY(ZEBRA_ROUTER_ID_UPDATE),
1045 DESC_ENTRY(ZEBRA_HELLO),
1046 DESC_ENTRY(ZEBRA_CAPABILITIES),
1047 DESC_ENTRY(ZEBRA_NEXTHOP_REGISTER),
1048 DESC_ENTRY(ZEBRA_NEXTHOP_UNREGISTER),
1049 DESC_ENTRY(ZEBRA_NEXTHOP_UPDATE),
1050 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_ADD),
1051 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_DELETE),
1052 DESC_ENTRY(ZEBRA_INTERFACE_BFD_DEST_UPDATE),
1053 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_REGISTER),
1054 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_UNREGISTER),
1055 DESC_ENTRY(ZEBRA_IMPORT_CHECK_UPDATE),
1056 DESC_ENTRY(ZEBRA_BFD_DEST_REGISTER),
1057 DESC_ENTRY(ZEBRA_BFD_DEST_DEREGISTER),
1058 DESC_ENTRY(ZEBRA_BFD_DEST_UPDATE),
1059 DESC_ENTRY(ZEBRA_BFD_DEST_REPLAY),
1060 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_ADD),
1061 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_DEL),
1062 DESC_ENTRY(ZEBRA_VRF_UNREGISTER),
1063 DESC_ENTRY(ZEBRA_VRF_ADD),
1064 DESC_ENTRY(ZEBRA_VRF_DELETE),
1065 DESC_ENTRY(ZEBRA_VRF_LABEL),
1066 DESC_ENTRY(ZEBRA_INTERFACE_VRF_UPDATE),
1067 DESC_ENTRY(ZEBRA_BFD_CLIENT_REGISTER),
1068 DESC_ENTRY(ZEBRA_BFD_CLIENT_DEREGISTER),
1069 DESC_ENTRY(ZEBRA_INTERFACE_ENABLE_RADV),
1070 DESC_ENTRY(ZEBRA_INTERFACE_DISABLE_RADV),
1071 DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB),
1072 DESC_ENTRY(ZEBRA_INTERFACE_LINK_PARAMS),
1073 DESC_ENTRY(ZEBRA_MPLS_LABELS_ADD),
1074 DESC_ENTRY(ZEBRA_MPLS_LABELS_DELETE),
1075 DESC_ENTRY(ZEBRA_IPMR_ROUTE_STATS),
1076 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT),
1077 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT_ASYNC),
1078 DESC_ENTRY(ZEBRA_GET_LABEL_CHUNK),
1079 DESC_ENTRY(ZEBRA_RELEASE_LABEL_CHUNK),
1080 DESC_ENTRY(ZEBRA_FEC_REGISTER),
1081 DESC_ENTRY(ZEBRA_FEC_UNREGISTER),
1082 DESC_ENTRY(ZEBRA_FEC_UPDATE),
1083 DESC_ENTRY(ZEBRA_ADVERTISE_ALL_VNI),
1084 DESC_ENTRY(ZEBRA_ADVERTISE_DEFAULT_GW),
1085 DESC_ENTRY(ZEBRA_ADVERTISE_SVI_MACIP),
1086 DESC_ENTRY(ZEBRA_ADVERTISE_SUBNET),
1087 DESC_ENTRY(ZEBRA_LOCAL_ES_ADD),
1088 DESC_ENTRY(ZEBRA_LOCAL_ES_DEL),
1089 DESC_ENTRY(ZEBRA_VNI_ADD),
1090 DESC_ENTRY(ZEBRA_VNI_DEL),
1091 DESC_ENTRY(ZEBRA_L3VNI_ADD),
1092 DESC_ENTRY(ZEBRA_L3VNI_DEL),
1093 DESC_ENTRY(ZEBRA_REMOTE_VTEP_ADD),
1094 DESC_ENTRY(ZEBRA_REMOTE_VTEP_DEL),
1095 DESC_ENTRY(ZEBRA_MACIP_ADD),
1096 DESC_ENTRY(ZEBRA_MACIP_DEL),
1097 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_ADD),
1098 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_DEL),
1099 DESC_ENTRY(ZEBRA_REMOTE_MACIP_ADD),
1100 DESC_ENTRY(ZEBRA_REMOTE_MACIP_DEL),
1101 DESC_ENTRY(ZEBRA_DUPLICATE_ADDR_DETECTION),
1102 DESC_ENTRY(ZEBRA_PW_ADD),
1103 DESC_ENTRY(ZEBRA_PW_DELETE),
1104 DESC_ENTRY(ZEBRA_PW_SET),
1105 DESC_ENTRY(ZEBRA_PW_UNSET),
1106 DESC_ENTRY(ZEBRA_PW_STATUS_UPDATE),
1107 DESC_ENTRY(ZEBRA_RULE_ADD),
1108 DESC_ENTRY(ZEBRA_RULE_DELETE),
1109 DESC_ENTRY(ZEBRA_RULE_NOTIFY_OWNER),
1110 DESC_ENTRY(ZEBRA_TABLE_MANAGER_CONNECT),
1111 DESC_ENTRY(ZEBRA_GET_TABLE_CHUNK),
1112 DESC_ENTRY(ZEBRA_RELEASE_TABLE_CHUNK),
1113 DESC_ENTRY(ZEBRA_IPSET_CREATE),
1114 DESC_ENTRY(ZEBRA_IPSET_DESTROY),
1115 DESC_ENTRY(ZEBRA_IPSET_ENTRY_ADD),
1116 DESC_ENTRY(ZEBRA_IPSET_ENTRY_DELETE),
1117 DESC_ENTRY(ZEBRA_IPSET_NOTIFY_OWNER),
1118 DESC_ENTRY(ZEBRA_IPSET_ENTRY_NOTIFY_OWNER),
1119 DESC_ENTRY(ZEBRA_IPTABLE_ADD),
1120 DESC_ENTRY(ZEBRA_IPTABLE_DELETE),
1121 DESC_ENTRY(ZEBRA_IPTABLE_NOTIFY_OWNER),
1122 DESC_ENTRY(ZEBRA_VXLAN_FLOOD_CONTROL),
1123 DESC_ENTRY(ZEBRA_VXLAN_SG_ADD),
1124 DESC_ENTRY(ZEBRA_VXLAN_SG_DEL),
1125 DESC_ENTRY(ZEBRA_VXLAN_SG_REPLAY),
1126 };
1127 #undef DESC_ENTRY
1128
1129 static const struct zebra_desc_table unknown = {0, "unknown", '?'};
1130
1131 static const struct zebra_desc_table *zroute_lookup(unsigned int zroute)
1132 {
1133 unsigned int i;
1134
1135 if (zroute >= array_size(route_types)) {
1136 flog_err(EC_LIB_DEVELOPMENT, "unknown zebra route type: %u",
1137 zroute);
1138 return &unknown;
1139 }
1140 if (zroute == route_types[zroute].type)
1141 return &route_types[zroute];
1142 for (i = 0; i < array_size(route_types); i++) {
1143 if (zroute == route_types[i].type) {
1144 zlog_warn(
1145 "internal error: route type table out of order "
1146 "while searching for %u, please notify developers",
1147 zroute);
1148 return &route_types[i];
1149 }
1150 }
1151 flog_err(EC_LIB_DEVELOPMENT,
1152 "internal error: cannot find route type %u in table!", zroute);
1153 return &unknown;
1154 }
1155
1156 const char *zebra_route_string(unsigned int zroute)
1157 {
1158 return zroute_lookup(zroute)->string;
1159 }
1160
1161 char zebra_route_char(unsigned int zroute)
1162 {
1163 return zroute_lookup(zroute)->chr;
1164 }
1165
1166 const char *zserv_command_string(unsigned int command)
1167 {
1168 if (command >= array_size(command_types)) {
1169 flog_err(EC_LIB_DEVELOPMENT, "unknown zserv command type: %u",
1170 command);
1171 return unknown.string;
1172 }
1173 return command_types[command].string;
1174 }
1175
1176 int proto_name2num(const char *s)
1177 {
1178 unsigned i;
1179
1180 for (i = 0; i < array_size(route_types); ++i)
1181 if (strcasecmp(s, route_types[i].string) == 0)
1182 return route_types[i].type;
1183 return -1;
1184 }
1185
1186 int proto_redistnum(int afi, const char *s)
1187 {
1188 if (!s)
1189 return -1;
1190
1191 if (afi == AFI_IP) {
1192 if (strmatch(s, "kernel"))
1193 return ZEBRA_ROUTE_KERNEL;
1194 else if (strmatch(s, "connected"))
1195 return ZEBRA_ROUTE_CONNECT;
1196 else if (strmatch(s, "static"))
1197 return ZEBRA_ROUTE_STATIC;
1198 else if (strmatch(s, "rip"))
1199 return ZEBRA_ROUTE_RIP;
1200 else if (strmatch(s, "eigrp"))
1201 return ZEBRA_ROUTE_EIGRP;
1202 else if (strmatch(s, "ospf"))
1203 return ZEBRA_ROUTE_OSPF;
1204 else if (strmatch(s, "isis"))
1205 return ZEBRA_ROUTE_ISIS;
1206 else if (strmatch(s, "bgp"))
1207 return ZEBRA_ROUTE_BGP;
1208 else if (strmatch(s, "table"))
1209 return ZEBRA_ROUTE_TABLE;
1210 else if (strmatch(s, "vnc"))
1211 return ZEBRA_ROUTE_VNC;
1212 else if (strmatch(s, "vnc-direct"))
1213 return ZEBRA_ROUTE_VNC_DIRECT;
1214 else if (strmatch(s, "nhrp"))
1215 return ZEBRA_ROUTE_NHRP;
1216 else if (strmatch(s, "babel"))
1217 return ZEBRA_ROUTE_BABEL;
1218 else if (strmatch(s, "sharp"))
1219 return ZEBRA_ROUTE_SHARP;
1220 else if (strmatch(s, "openfabric"))
1221 return ZEBRA_ROUTE_OPENFABRIC;
1222 }
1223 if (afi == AFI_IP6) {
1224 if (strmatch(s, "kernel"))
1225 return ZEBRA_ROUTE_KERNEL;
1226 else if (strmatch(s, "connected"))
1227 return ZEBRA_ROUTE_CONNECT;
1228 else if (strmatch(s, "static"))
1229 return ZEBRA_ROUTE_STATIC;
1230 else if (strmatch(s, "ripng"))
1231 return ZEBRA_ROUTE_RIPNG;
1232 else if (strmatch(s, "ospf6"))
1233 return ZEBRA_ROUTE_OSPF6;
1234 else if (strmatch(s, "isis"))
1235 return ZEBRA_ROUTE_ISIS;
1236 else if (strmatch(s, "bgp"))
1237 return ZEBRA_ROUTE_BGP;
1238 else if (strmatch(s, "table"))
1239 return ZEBRA_ROUTE_TABLE;
1240 else if (strmatch(s, "vnc"))
1241 return ZEBRA_ROUTE_VNC;
1242 else if (strmatch(s, "vnc-direct"))
1243 return ZEBRA_ROUTE_VNC_DIRECT;
1244 else if (strmatch(s, "nhrp"))
1245 return ZEBRA_ROUTE_NHRP;
1246 else if (strmatch(s, "babel"))
1247 return ZEBRA_ROUTE_BABEL;
1248 else if (strmatch(s, "sharp"))
1249 return ZEBRA_ROUTE_SHARP;
1250 else if (strmatch(s, "openfabric"))
1251 return ZEBRA_ROUTE_OPENFABRIC;
1252 }
1253 return -1;
1254 }
1255
1256 void zlog_hexdump(const void *mem, unsigned int len)
1257 {
1258 unsigned long i = 0;
1259 unsigned int j = 0;
1260 unsigned int columns = 8;
1261 /*
1262 * 19 bytes for 0xADDRESS:
1263 * 24 bytes for data; 2 chars plus a space per data byte
1264 * 1 byte for space
1265 * 8 bytes for ASCII representation
1266 * 1 byte for a newline
1267 * =====================
1268 * 53 bytes per 8 bytes of data
1269 * 1 byte for null term
1270 */
1271 size_t bs = ((len / 8) + 1) * 53 + 1;
1272 char buf[bs];
1273 char *s = buf;
1274
1275 memset(buf, 0, sizeof(buf));
1276
1277 for (i = 0; i < len + ((len % columns) ? (columns - len % columns) : 0);
1278 i++) {
1279 /* print offset */
1280 if (i % columns == 0)
1281 s += snprintf(s, bs - (s - buf),
1282 "0x%016lx: ", (unsigned long)mem + i);
1283
1284 /* print hex data */
1285 if (i < len)
1286 s += snprintf(s, bs - (s - buf), "%02x ",
1287 0xFF & ((const char *)mem)[i]);
1288
1289 /* end of block, just aligning for ASCII dump */
1290 else
1291 s += snprintf(s, bs - (s - buf), " ");
1292
1293 /* print ASCII dump */
1294 if (i % columns == (columns - 1)) {
1295 for (j = i - (columns - 1); j <= i; j++) {
1296 /* end of block not really printing */
1297 if (j >= len)
1298 s += snprintf(s, bs - (s - buf), " ");
1299 else if (isprint((int)((const char *)mem)[j]))
1300 s += snprintf(
1301 s, bs - (s - buf), "%c",
1302 0xFF & ((const char *)mem)[j]);
1303 else /* other char */
1304 s += snprintf(s, bs - (s - buf), ".");
1305 }
1306 s += snprintf(s, bs - (s - buf), "\n");
1307 }
1308 }
1309 zlog_debug("\n%s", buf);
1310 }
1311
1312 const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, size_t inlen)
1313 {
1314 const char *inbuf = in;
1315 char *pos = buf, *end = buf + bufsz;
1316 const char *iend = inbuf + inlen;
1317
1318 memset(buf, 0, bufsz);
1319 for (; inbuf < iend; inbuf++) {
1320 /* don't write partial escape sequence */
1321 if (end - pos < 5)
1322 break;
1323
1324 if (*inbuf == '\n')
1325 snprintf(pos, end - pos, "\\n");
1326 else if (*inbuf == '\r')
1327 snprintf(pos, end - pos, "\\r");
1328 else if (*inbuf == '\t')
1329 snprintf(pos, end - pos, "\\t");
1330 else if (*inbuf < ' ' || *inbuf == '"' || *inbuf >= 127)
1331 snprintf(pos, end - pos, "\\x%02hhx", *inbuf);
1332 else
1333 *pos = *inbuf;
1334
1335 pos += strlen(pos);
1336 }
1337 return buf;
1338 }