]> git.proxmox.com Git - mirror_frr.git/blob - lib/log.c
c577239908b1dd3c5121bcf4094d33c820e77636
[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 goto out;
392
393 /* call external hook */
394 hook_call(zebra_ext_log, priority, format, args);
395
396 /* When zlog_default is also NULL, use stderr for logging. */
397 if (zl == NULL) {
398 time_print(stderr, &tsctl);
399 fprintf(stderr, "%s: %s\n", "unknown", msg);
400 fflush(stderr);
401 goto out;
402 }
403
404 /* Syslog output */
405 if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG])
406 syslog(priority | zlog_default->facility, "%s", msg);
407
408 /* File output. */
409 if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
410 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
411 zl->fp, msg);
412
413 /* fixed-config logging to stderr while we're stating up & haven't
414 * daemonized / reached mainloop yet
415 *
416 * note the "else" on stdout output -- we don't want to print the same
417 * message to both stderr and stdout. */
418 if (zlog_startup_stderr && priority <= LOG_WARNING)
419 vzlog_file(zl, &tsctl, proto_str, 1, priority, stderr, msg);
420 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
421 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
422 stdout, msg);
423
424 /* Terminal monitor. */
425 if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
426 vty_log((zl->record_priority ? zlog_priority[priority] : NULL),
427 proto_str, msg, &tsctl);
428
429 out:
430 if (msg != buf)
431 XFREE(MTYPE_TMP, msg);
432 errno = original_errno;
433 pthread_mutex_unlock(&loglock);
434 }
435
436 int vzlog_test(int priority)
437 {
438 pthread_mutex_lock(&loglock);
439
440 int ret = 0;
441
442 struct zlog *zl = zlog_default;
443
444 /* When zlog_default is also NULL, use stderr for logging. */
445 if (zl == NULL)
446 ret = 1;
447 /* Syslog output */
448 else if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG])
449 ret = 1;
450 /* File output. */
451 else if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
452 ret = 1;
453 /* stdout output. */
454 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
455 ret = 1;
456 /* Terminal monitor. */
457 else if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
458 ret = 1;
459
460 pthread_mutex_unlock(&loglock);
461
462 return ret;
463 }
464
465 /*
466 * crash handling
467 *
468 * NB: only AS-Safe (async-signal) functions can be used here!
469 */
470
471 /* Needs to be enhanced to support Solaris. */
472 static int syslog_connect(void)
473 {
474 #ifdef SUNOS_5
475 return -1;
476 #else
477 int fd;
478 struct sockaddr_un addr;
479
480 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
481 return -1;
482 addr.sun_family = AF_UNIX;
483 #ifdef _PATH_LOG
484 #define SYSLOG_SOCKET_PATH _PATH_LOG
485 #else
486 #define SYSLOG_SOCKET_PATH "/dev/log"
487 #endif
488 strlcpy(addr.sun_path, SYSLOG_SOCKET_PATH, sizeof(addr.sun_path));
489 #undef SYSLOG_SOCKET_PATH
490 if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
491 close(fd);
492 return -1;
493 }
494 return fd;
495 #endif
496 }
497
498 static void syslog_sigsafe(int priority, const char *msg, size_t msglen)
499 {
500 static int syslog_fd = -1;
501 char buf[sizeof("<1234567890>ripngd[1234567890]: ") + msglen + 50];
502 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
503
504 if ((syslog_fd < 0) && ((syslog_fd = syslog_connect()) < 0))
505 return;
506
507 /* forget about the timestamp, too difficult in a signal handler */
508 bprintfrr(&fb, "<%d>%s", priority, zlog_default->ident);
509 if (zlog_default->syslog_options & LOG_PID)
510 bprintfrr(&fb, "[%ld]", (long)getpid());
511 bprintfrr(&fb, ": %s", msg);
512 write_wrapper(syslog_fd, fb.buf, fb.pos - fb.buf);
513 }
514
515 static int open_crashlog(void)
516 {
517 char crashlog_buf[PATH_MAX];
518 const char *crashlog_default = "/var/tmp/frr.crashlog", *crashlog;
519
520 if (!zlog_default || !zlog_default->ident)
521 crashlog = crashlog_default;
522 else {
523 snprintfrr(crashlog_buf, sizeof(crashlog_buf),
524 "/var/tmp/frr.%s.crashlog", zlog_default->ident);
525 crashlog = crashlog_buf;
526 }
527 return open(crashlog, O_WRONLY | O_CREAT | O_EXCL, LOGFILE_MASK);
528 }
529
530 /* N.B. implicit priority is most severe */
531 #define PRI LOG_CRIT
532
533 static void crash_write(struct fbuf *fb, char *msgstart)
534 {
535 if (fb->pos == fb->buf)
536 return;
537 if (!msgstart)
538 msgstart = fb->buf;
539
540 /* If no file logging configured, try to write to fallback log file. */
541 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
542 write(logfile_fd, fb->buf, fb->pos - fb->buf);
543 if (!zlog_default)
544 write(STDERR_FILENO, fb->buf, fb->pos - fb->buf);
545 else {
546 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
547 write(STDOUT_FILENO, fb->buf, fb->pos - fb->buf);
548 /* Remove trailing '\n' for monitor and syslog */
549 fb->pos--;
550 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
551 vty_log_fixed(fb->buf, fb->pos - fb->buf);
552 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
553 syslog_sigsafe(PRI | zlog_default->facility, msgstart,
554 fb->pos - msgstart);
555 }
556 }
557
558 /* Note: the goal here is to use only async-signal-safe functions. */
559 void zlog_signal(int signo, const char *action, void *siginfo_v,
560 void *program_counter)
561 {
562 #ifdef SA_SIGINFO
563 siginfo_t *siginfo = siginfo_v;
564 #endif
565 time_t now;
566 char buf[sizeof("DEFAULT: Received signal S at T (si_addr 0xP, PC 0xP); aborting...")
567 + 100];
568 char *msgstart;
569 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
570
571 time(&now);
572 if (zlog_default)
573 bprintfrr(&fb, "%s: ", zlog_default->protoname);
574
575 msgstart = fb.pos;
576
577 bprintfrr(&fb, "Received signal %d at %lld", signo, (long long)now);
578 #ifdef SA_SIGINFO
579 if (program_counter)
580 bprintfrr(&fb, " (si_addr 0x%tx, PC 0x%tx)",
581 (ptrdiff_t)siginfo->si_addr,
582 (ptrdiff_t)program_counter);
583 else
584 bprintfrr(&fb, " (si_addr 0x%tx)",
585 (ptrdiff_t)siginfo->si_addr);
586 #endif /* SA_SIGINFO */
587 bprintfrr(&fb, "; %s\n", action);
588
589 crash_write(&fb, msgstart);
590
591 zlog_backtrace_sigsafe(PRI, program_counter);
592
593 fb.pos = buf;
594
595 struct thread *tc;
596 tc = pthread_getspecific(thread_current);
597
598 if (!tc)
599 bprintfrr(&fb, "no thread information available\n");
600 else
601 bprintfrr(&fb, "in thread %s scheduled from %s:%d\n",
602 tc->funcname, tc->schedfrom, tc->schedfrom_line);
603
604 crash_write(&fb, NULL);
605 }
606
607 /* Log a backtrace using only async-signal-safe functions.
608 Needs to be enhanced to support syslog logging. */
609 void zlog_backtrace_sigsafe(int priority, void *program_counter)
610 {
611 #ifdef HAVE_LIBUNWIND
612 char buf[256];
613 struct fbuf fb = { .buf = buf, .len = sizeof(buf) };
614 unw_cursor_t cursor;
615 unw_context_t uc;
616 unw_word_t ip, off, sp;
617 Dl_info dlinfo;
618
619 unw_getcontext(&uc);
620 unw_init_local(&cursor, &uc);
621 while (unw_step(&cursor) > 0) {
622 char name[128] = "?";
623
624 unw_get_reg(&cursor, UNW_REG_IP, &ip);
625 unw_get_reg(&cursor, UNW_REG_SP, &sp);
626
627 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off))
628 snprintfrr(name, sizeof(name), "%s+%#lx",
629 buf, (long)off);
630
631 fb.pos = buf;
632 if (unw_is_signal_frame(&cursor))
633 bprintfrr(&fb, " ---- signal ----\n");
634 bprintfrr(&fb, "%-30s %16lx %16lx", name, (long)ip, (long)sp);
635 if (dladdr((void *)ip, &dlinfo))
636 bprintfrr(&fb, " %s (mapped at %p)",
637 dlinfo.dli_fname, dlinfo.dli_fbase);
638 bprintfrr(&fb, "\n");
639 crash_write(&fb, NULL);
640 }
641 #elif defined(HAVE_GLIBC_BACKTRACE) || defined(HAVE_PRINTSTACK)
642 static const char pclabel[] = "Program counter: ";
643 void *array[64];
644 int size;
645 char buf[128];
646 struct fbuf fb = { .buf = buf, .pos = buf, .len = sizeof(buf) };
647 char **bt = NULL;
648
649 #ifdef HAVE_GLIBC_BACKTRACE
650 size = backtrace(array, array_size(array));
651 if (size <= 0 || (size_t)size > array_size(array))
652 return;
653
654 #define DUMP(FD) \
655 { \
656 if (program_counter) { \
657 write_wrapper(FD, pclabel, sizeof(pclabel) - 1); \
658 backtrace_symbols_fd(&program_counter, 1, FD); \
659 } \
660 write_wrapper(FD, fb.buf, fb.pos - fb.buf); \
661 backtrace_symbols_fd(array, size, FD); \
662 }
663 #elif defined(HAVE_PRINTSTACK)
664 size = 0;
665
666 #define DUMP(FD) \
667 { \
668 if (program_counter) \
669 write_wrapper((FD), pclabel, sizeof(pclabel) - 1); \
670 write_wrapper((FD), fb.buf, fb.pos - fb.buf); \
671 printstack((FD)); \
672 }
673 #endif /* HAVE_GLIBC_BACKTRACE, HAVE_PRINTSTACK */
674
675 bprintfrr(&fb, "Backtrace for %d stack frames:\n", size);
676
677 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
678 DUMP(logfile_fd)
679 if (!zlog_default)
680 DUMP(STDERR_FILENO)
681 else {
682 if (priority <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
683 DUMP(STDOUT_FILENO)
684 /* Remove trailing '\n' for monitor and syslog */
685 fb.pos--;
686 if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
687 vty_log_fixed(fb.buf, fb.pos - fb.buf);
688 if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
689 syslog_sigsafe(priority | zlog_default->facility,
690 fb.buf, fb.pos - fb.buf);
691 {
692 int i;
693 #ifdef HAVE_GLIBC_BACKTRACE
694 bt = backtrace_symbols(array, size);
695 #endif
696 /* Just print the function addresses. */
697 for (i = 0; i < size; i++) {
698 fb.pos = buf;
699 if (bt)
700 bprintfrr(&fb, "%s", bt[i]);
701 else
702 bprintfrr(&fb, "[bt %d] 0x%tx", i,
703 (ptrdiff_t)(array[i]));
704 if (priority
705 <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
706 vty_log_fixed(fb.buf, fb.pos - fb.buf);
707 if (priority
708 <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
709 syslog_sigsafe(priority
710 | zlog_default->facility,
711 fb.buf, fb.pos - fb.buf);
712 }
713 if (bt)
714 free(bt);
715 }
716 }
717 #undef DUMP
718 #endif /* HAVE_STRACK_TRACE */
719 }
720
721 void zlog_backtrace(int priority)
722 {
723 #ifdef HAVE_LIBUNWIND
724 char buf[100];
725 unw_cursor_t cursor;
726 unw_context_t uc;
727 unw_word_t ip, off, sp;
728 Dl_info dlinfo;
729
730 unw_getcontext(&uc);
731 unw_init_local(&cursor, &uc);
732 zlog(priority, "Backtrace:");
733 while (unw_step(&cursor) > 0) {
734 char name[128] = "?";
735
736 unw_get_reg(&cursor, UNW_REG_IP, &ip);
737 unw_get_reg(&cursor, UNW_REG_SP, &sp);
738
739 if (unw_is_signal_frame(&cursor))
740 zlog(priority, " ---- signal ----");
741
742 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off))
743 snprintf(name, sizeof(name), "%s+%#lx",
744 buf, (long)off);
745
746 if (dladdr((void *)ip, &dlinfo))
747 zlog(priority, "%-30s %16lx %16lx %s (mapped at %p)",
748 name, (long)ip, (long)sp,
749 dlinfo.dli_fname, dlinfo.dli_fbase);
750 else
751 zlog(priority, "%-30s %16lx %16lx",
752 name, (long)ip, (long)sp);
753 }
754 #elif defined(HAVE_GLIBC_BACKTRACE)
755 void *array[20];
756 int size, i;
757 char **strings;
758
759 size = backtrace(array, array_size(array));
760 if (size <= 0 || (size_t)size > array_size(array)) {
761 flog_err_sys(
762 EC_LIB_SYSTEM_CALL,
763 "Cannot get backtrace, returned invalid # of frames %d "
764 "(valid range is between 1 and %lu)",
765 size, (unsigned long)(array_size(array)));
766 return;
767 }
768 zlog(priority, "Backtrace for %d stack frames:", size);
769 if (!(strings = backtrace_symbols(array, size))) {
770 flog_err_sys(EC_LIB_SYSTEM_CALL,
771 "Cannot get backtrace symbols (out of memory?)");
772 for (i = 0; i < size; i++)
773 zlog(priority, "[bt %d] %p", i, array[i]);
774 } else {
775 for (i = 0; i < size; i++)
776 zlog(priority, "[bt %d] %s", i, strings[i]);
777 free(strings);
778 }
779 #else /* !HAVE_GLIBC_BACKTRACE && !HAVE_LIBUNWIND */
780 zlog(priority, "No backtrace available on this platform.");
781 #endif
782 }
783
784 void zlog(int priority, const char *format, ...)
785 {
786 va_list args;
787
788 va_start(args, format);
789 vzlog(priority, format, args);
790 va_end(args);
791 }
792
793 #define ZLOG_FUNC(FUNCNAME, PRIORITY) \
794 void FUNCNAME(const char *format, ...) \
795 { \
796 va_list args; \
797 va_start(args, format); \
798 vzlog(PRIORITY, format, args); \
799 va_end(args); \
800 }
801
802 ZLOG_FUNC(zlog_err, LOG_ERR)
803
804 ZLOG_FUNC(zlog_warn, LOG_WARNING)
805
806 ZLOG_FUNC(zlog_info, LOG_INFO)
807
808 ZLOG_FUNC(zlog_notice, LOG_NOTICE)
809
810 ZLOG_FUNC(zlog_debug, LOG_DEBUG)
811
812 #undef ZLOG_FUNC
813
814 void zlog_thread_info(int log_level)
815 {
816 struct thread *tc;
817 tc = pthread_getspecific(thread_current);
818
819 if (tc)
820 zlog(log_level,
821 "Current thread function %s, scheduled from "
822 "file %s, line %u",
823 tc->funcname, tc->schedfrom, tc->schedfrom_line);
824 else
825 zlog(log_level, "Current thread not known/applicable");
826 }
827
828 void _zlog_assert_failed(const char *assertion, const char *file,
829 unsigned int line, const char *function)
830 {
831 /* Force fallback file logging? */
832 if (zlog_default && !zlog_default->fp
833 && ((logfile_fd = open_crashlog()) >= 0)
834 && ((zlog_default->fp = fdopen(logfile_fd, "w")) != NULL))
835 zlog_default->maxlvl[ZLOG_DEST_FILE] = LOG_ERR;
836 zlog(LOG_CRIT, "Assertion `%s' failed in file %s, line %u, function %s",
837 assertion, file, line, (function ? function : "?"));
838 zlog_backtrace(LOG_CRIT);
839 zlog_thread_info(LOG_CRIT);
840 log_memstats(stderr, "log");
841 abort();
842 }
843
844 void memory_oom(size_t size, const char *name)
845 {
846 flog_err_sys(EC_LIB_SYSTEM_CALL,
847 "out of memory: failed to allocate %zu bytes for %s"
848 "object",
849 size, name);
850 zlog_backtrace(LOG_ERR);
851 abort();
852 }
853
854 /* Open log stream */
855 void openzlog(const char *progname, const char *protoname,
856 unsigned short instance, int syslog_flags, int syslog_facility)
857 {
858 struct zlog *zl;
859 unsigned int i;
860
861 zl = XCALLOC(MTYPE_ZLOG, sizeof(struct zlog));
862
863 zl->ident = progname;
864 zl->protoname = protoname;
865 zl->instance = instance;
866 zl->facility = syslog_facility;
867 zl->syslog_options = syslog_flags;
868
869 /* Set default logging levels. */
870 for (i = 0; i < array_size(zl->maxlvl); i++)
871 zl->maxlvl[i] = ZLOG_DISABLED;
872 zl->maxlvl[ZLOG_DEST_MONITOR] = LOG_DEBUG;
873 zl->default_lvl = LOG_DEBUG;
874
875 openlog(progname, syslog_flags, zl->facility);
876
877 pthread_mutex_lock(&loglock);
878 zlog_default = zl;
879 pthread_mutex_unlock(&loglock);
880
881 #ifdef HAVE_GLIBC_BACKTRACE
882 /* work around backtrace() using lazily resolved dynamically linked
883 * symbols, which will otherwise cause funny breakage in the SEGV
884 * handler.
885 * (particularly, the dynamic linker can call malloc(), which uses locks
886 * in programs linked with -pthread, thus can deadlock.) */
887 void *bt[4];
888 backtrace(bt, array_size(bt));
889 free(backtrace_symbols(bt, 0));
890 backtrace_symbols_fd(bt, 0, 0);
891 #endif
892 }
893
894 void closezlog(void)
895 {
896 pthread_mutex_lock(&loglock);
897 struct zlog *zl = zlog_default;
898
899 closelog();
900
901 if (zl->fp != NULL)
902 fclose(zl->fp);
903
904 XFREE(MTYPE_ZLOG, zl->filename);
905
906 XFREE(MTYPE_ZLOG, zl);
907 zlog_default = NULL;
908 pthread_mutex_unlock(&loglock);
909 }
910
911 /* Called from command.c. */
912 void zlog_set_level(zlog_dest_t dest, int log_level)
913 {
914 pthread_mutex_lock(&loglock);
915 zlog_default->maxlvl[dest] = log_level;
916 pthread_mutex_unlock(&loglock);
917 }
918
919 int zlog_set_file(const char *filename, int log_level)
920 {
921 struct zlog *zl;
922 FILE *fp;
923 mode_t oldumask;
924 int ret = 1;
925
926 /* There is opend file. */
927 zlog_reset_file();
928
929 /* Open file. */
930 oldumask = umask(0777 & ~LOGFILE_MASK);
931 fp = fopen(filename, "a");
932 umask(oldumask);
933 if (fp == NULL) {
934 ret = 0;
935 } else {
936 pthread_mutex_lock(&loglock);
937 zl = zlog_default;
938
939 /* Set flags. */
940 zl->filename = XSTRDUP(MTYPE_ZLOG, filename);
941 zl->maxlvl[ZLOG_DEST_FILE] = log_level;
942 zl->fp = fp;
943 logfile_fd = fileno(fp);
944 pthread_mutex_unlock(&loglock);
945 }
946
947 return ret;
948 }
949
950 /* Reset opend file. */
951 int zlog_reset_file(void)
952 {
953 pthread_mutex_lock(&loglock);
954
955 struct zlog *zl = zlog_default;
956
957 if (zl->fp)
958 fclose(zl->fp);
959 zl->fp = NULL;
960 logfile_fd = -1;
961 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
962
963 XFREE(MTYPE_ZLOG, zl->filename);
964 zl->filename = NULL;
965
966 pthread_mutex_unlock(&loglock);
967
968 return 1;
969 }
970
971 /* Reopen log file. */
972 int zlog_rotate(void)
973 {
974 pthread_mutex_lock(&loglock);
975
976 struct zlog *zl = zlog_default;
977 int level;
978 int ret = 1;
979
980 if (zl->fp)
981 fclose(zl->fp);
982 zl->fp = NULL;
983 logfile_fd = -1;
984 level = zl->maxlvl[ZLOG_DEST_FILE];
985 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
986
987 if (zl->filename) {
988 mode_t oldumask;
989 int save_errno;
990
991 oldumask = umask(0777 & ~LOGFILE_MASK);
992 zl->fp = fopen(zl->filename, "a");
993 save_errno = errno;
994 umask(oldumask);
995 if (zl->fp == NULL) {
996
997 pthread_mutex_unlock(&loglock);
998
999 flog_err_sys(
1000 EC_LIB_SYSTEM_CALL,
1001 "Log rotate failed: cannot open file %s for append: %s",
1002 zl->filename, safe_strerror(save_errno));
1003 ret = -1;
1004
1005 pthread_mutex_lock(&loglock);
1006 } else {
1007 logfile_fd = fileno(zl->fp);
1008 zl->maxlvl[ZLOG_DEST_FILE] = level;
1009 }
1010 }
1011
1012 pthread_mutex_unlock(&loglock);
1013
1014 return ret;
1015 }
1016
1017 /* Wrapper around strerror to handle case where it returns NULL. */
1018 const char *safe_strerror(int errnum)
1019 {
1020 const char *s = strerror(errnum);
1021 return (s != NULL) ? s : "Unknown error";
1022 }
1023
1024 #define DESC_ENTRY(T) [(T)] = { (T), (#T), '\0' }
1025 static const struct zebra_desc_table command_types[] = {
1026 DESC_ENTRY(ZEBRA_INTERFACE_ADD),
1027 DESC_ENTRY(ZEBRA_INTERFACE_DELETE),
1028 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_ADD),
1029 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_DELETE),
1030 DESC_ENTRY(ZEBRA_INTERFACE_UP),
1031 DESC_ENTRY(ZEBRA_INTERFACE_DOWN),
1032 DESC_ENTRY(ZEBRA_INTERFACE_SET_MASTER),
1033 DESC_ENTRY(ZEBRA_ROUTE_ADD),
1034 DESC_ENTRY(ZEBRA_ROUTE_DELETE),
1035 DESC_ENTRY(ZEBRA_ROUTE_NOTIFY_OWNER),
1036 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ADD),
1037 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DELETE),
1038 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_ADD),
1039 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_DELETE),
1040 DESC_ENTRY(ZEBRA_ROUTER_ID_ADD),
1041 DESC_ENTRY(ZEBRA_ROUTER_ID_DELETE),
1042 DESC_ENTRY(ZEBRA_ROUTER_ID_UPDATE),
1043 DESC_ENTRY(ZEBRA_HELLO),
1044 DESC_ENTRY(ZEBRA_CAPABILITIES),
1045 DESC_ENTRY(ZEBRA_NEXTHOP_REGISTER),
1046 DESC_ENTRY(ZEBRA_NEXTHOP_UNREGISTER),
1047 DESC_ENTRY(ZEBRA_NEXTHOP_UPDATE),
1048 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_ADD),
1049 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_DELETE),
1050 DESC_ENTRY(ZEBRA_INTERFACE_BFD_DEST_UPDATE),
1051 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_REGISTER),
1052 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_UNREGISTER),
1053 DESC_ENTRY(ZEBRA_IMPORT_CHECK_UPDATE),
1054 DESC_ENTRY(ZEBRA_BFD_DEST_REGISTER),
1055 DESC_ENTRY(ZEBRA_BFD_DEST_DEREGISTER),
1056 DESC_ENTRY(ZEBRA_BFD_DEST_UPDATE),
1057 DESC_ENTRY(ZEBRA_BFD_DEST_REPLAY),
1058 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_ADD),
1059 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_DEL),
1060 DESC_ENTRY(ZEBRA_VRF_UNREGISTER),
1061 DESC_ENTRY(ZEBRA_VRF_ADD),
1062 DESC_ENTRY(ZEBRA_VRF_DELETE),
1063 DESC_ENTRY(ZEBRA_VRF_LABEL),
1064 DESC_ENTRY(ZEBRA_INTERFACE_VRF_UPDATE),
1065 DESC_ENTRY(ZEBRA_BFD_CLIENT_REGISTER),
1066 DESC_ENTRY(ZEBRA_BFD_CLIENT_DEREGISTER),
1067 DESC_ENTRY(ZEBRA_INTERFACE_ENABLE_RADV),
1068 DESC_ENTRY(ZEBRA_INTERFACE_DISABLE_RADV),
1069 DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB),
1070 DESC_ENTRY(ZEBRA_INTERFACE_LINK_PARAMS),
1071 DESC_ENTRY(ZEBRA_MPLS_LABELS_ADD),
1072 DESC_ENTRY(ZEBRA_MPLS_LABELS_DELETE),
1073 DESC_ENTRY(ZEBRA_IPMR_ROUTE_STATS),
1074 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT),
1075 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT_ASYNC),
1076 DESC_ENTRY(ZEBRA_GET_LABEL_CHUNK),
1077 DESC_ENTRY(ZEBRA_RELEASE_LABEL_CHUNK),
1078 DESC_ENTRY(ZEBRA_FEC_REGISTER),
1079 DESC_ENTRY(ZEBRA_FEC_UNREGISTER),
1080 DESC_ENTRY(ZEBRA_FEC_UPDATE),
1081 DESC_ENTRY(ZEBRA_ADVERTISE_ALL_VNI),
1082 DESC_ENTRY(ZEBRA_ADVERTISE_DEFAULT_GW),
1083 DESC_ENTRY(ZEBRA_ADVERTISE_SVI_MACIP),
1084 DESC_ENTRY(ZEBRA_ADVERTISE_SUBNET),
1085 DESC_ENTRY(ZEBRA_LOCAL_ES_ADD),
1086 DESC_ENTRY(ZEBRA_LOCAL_ES_DEL),
1087 DESC_ENTRY(ZEBRA_VNI_ADD),
1088 DESC_ENTRY(ZEBRA_VNI_DEL),
1089 DESC_ENTRY(ZEBRA_L3VNI_ADD),
1090 DESC_ENTRY(ZEBRA_L3VNI_DEL),
1091 DESC_ENTRY(ZEBRA_REMOTE_VTEP_ADD),
1092 DESC_ENTRY(ZEBRA_REMOTE_VTEP_DEL),
1093 DESC_ENTRY(ZEBRA_MACIP_ADD),
1094 DESC_ENTRY(ZEBRA_MACIP_DEL),
1095 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_ADD),
1096 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_DEL),
1097 DESC_ENTRY(ZEBRA_REMOTE_MACIP_ADD),
1098 DESC_ENTRY(ZEBRA_REMOTE_MACIP_DEL),
1099 DESC_ENTRY(ZEBRA_DUPLICATE_ADDR_DETECTION),
1100 DESC_ENTRY(ZEBRA_PW_ADD),
1101 DESC_ENTRY(ZEBRA_PW_DELETE),
1102 DESC_ENTRY(ZEBRA_PW_SET),
1103 DESC_ENTRY(ZEBRA_PW_UNSET),
1104 DESC_ENTRY(ZEBRA_PW_STATUS_UPDATE),
1105 DESC_ENTRY(ZEBRA_RULE_ADD),
1106 DESC_ENTRY(ZEBRA_RULE_DELETE),
1107 DESC_ENTRY(ZEBRA_RULE_NOTIFY_OWNER),
1108 DESC_ENTRY(ZEBRA_TABLE_MANAGER_CONNECT),
1109 DESC_ENTRY(ZEBRA_GET_TABLE_CHUNK),
1110 DESC_ENTRY(ZEBRA_RELEASE_TABLE_CHUNK),
1111 DESC_ENTRY(ZEBRA_IPSET_CREATE),
1112 DESC_ENTRY(ZEBRA_IPSET_DESTROY),
1113 DESC_ENTRY(ZEBRA_IPSET_ENTRY_ADD),
1114 DESC_ENTRY(ZEBRA_IPSET_ENTRY_DELETE),
1115 DESC_ENTRY(ZEBRA_IPSET_NOTIFY_OWNER),
1116 DESC_ENTRY(ZEBRA_IPSET_ENTRY_NOTIFY_OWNER),
1117 DESC_ENTRY(ZEBRA_IPTABLE_ADD),
1118 DESC_ENTRY(ZEBRA_IPTABLE_DELETE),
1119 DESC_ENTRY(ZEBRA_IPTABLE_NOTIFY_OWNER),
1120 DESC_ENTRY(ZEBRA_VXLAN_FLOOD_CONTROL),
1121 DESC_ENTRY(ZEBRA_VXLAN_SG_ADD),
1122 DESC_ENTRY(ZEBRA_VXLAN_SG_DEL),
1123 DESC_ENTRY(ZEBRA_VXLAN_SG_REPLAY),
1124 };
1125 #undef DESC_ENTRY
1126
1127 static const struct zebra_desc_table unknown = {0, "unknown", '?'};
1128
1129 static const struct zebra_desc_table *zroute_lookup(unsigned int zroute)
1130 {
1131 unsigned int i;
1132
1133 if (zroute >= array_size(route_types)) {
1134 flog_err(EC_LIB_DEVELOPMENT, "unknown zebra route type: %u",
1135 zroute);
1136 return &unknown;
1137 }
1138 if (zroute == route_types[zroute].type)
1139 return &route_types[zroute];
1140 for (i = 0; i < array_size(route_types); i++) {
1141 if (zroute == route_types[i].type) {
1142 zlog_warn(
1143 "internal error: route type table out of order "
1144 "while searching for %u, please notify developers",
1145 zroute);
1146 return &route_types[i];
1147 }
1148 }
1149 flog_err(EC_LIB_DEVELOPMENT,
1150 "internal error: cannot find route type %u in table!", zroute);
1151 return &unknown;
1152 }
1153
1154 const char *zebra_route_string(unsigned int zroute)
1155 {
1156 return zroute_lookup(zroute)->string;
1157 }
1158
1159 char zebra_route_char(unsigned int zroute)
1160 {
1161 return zroute_lookup(zroute)->chr;
1162 }
1163
1164 const char *zserv_command_string(unsigned int command)
1165 {
1166 if (command >= array_size(command_types)) {
1167 flog_err(EC_LIB_DEVELOPMENT, "unknown zserv command type: %u",
1168 command);
1169 return unknown.string;
1170 }
1171 return command_types[command].string;
1172 }
1173
1174 int proto_name2num(const char *s)
1175 {
1176 unsigned i;
1177
1178 for (i = 0; i < array_size(route_types); ++i)
1179 if (strcasecmp(s, route_types[i].string) == 0)
1180 return route_types[i].type;
1181 return -1;
1182 }
1183
1184 int proto_redistnum(int afi, const char *s)
1185 {
1186 if (!s)
1187 return -1;
1188
1189 if (afi == AFI_IP) {
1190 if (strmatch(s, "kernel"))
1191 return ZEBRA_ROUTE_KERNEL;
1192 else if (strmatch(s, "connected"))
1193 return ZEBRA_ROUTE_CONNECT;
1194 else if (strmatch(s, "static"))
1195 return ZEBRA_ROUTE_STATIC;
1196 else if (strmatch(s, "rip"))
1197 return ZEBRA_ROUTE_RIP;
1198 else if (strmatch(s, "eigrp"))
1199 return ZEBRA_ROUTE_EIGRP;
1200 else if (strmatch(s, "ospf"))
1201 return ZEBRA_ROUTE_OSPF;
1202 else if (strmatch(s, "isis"))
1203 return ZEBRA_ROUTE_ISIS;
1204 else if (strmatch(s, "bgp"))
1205 return ZEBRA_ROUTE_BGP;
1206 else if (strmatch(s, "table"))
1207 return ZEBRA_ROUTE_TABLE;
1208 else if (strmatch(s, "vnc"))
1209 return ZEBRA_ROUTE_VNC;
1210 else if (strmatch(s, "vnc-direct"))
1211 return ZEBRA_ROUTE_VNC_DIRECT;
1212 else if (strmatch(s, "nhrp"))
1213 return ZEBRA_ROUTE_NHRP;
1214 else if (strmatch(s, "babel"))
1215 return ZEBRA_ROUTE_BABEL;
1216 else if (strmatch(s, "sharp"))
1217 return ZEBRA_ROUTE_SHARP;
1218 else if (strmatch(s, "openfabric"))
1219 return ZEBRA_ROUTE_OPENFABRIC;
1220 }
1221 if (afi == AFI_IP6) {
1222 if (strmatch(s, "kernel"))
1223 return ZEBRA_ROUTE_KERNEL;
1224 else if (strmatch(s, "connected"))
1225 return ZEBRA_ROUTE_CONNECT;
1226 else if (strmatch(s, "static"))
1227 return ZEBRA_ROUTE_STATIC;
1228 else if (strmatch(s, "ripng"))
1229 return ZEBRA_ROUTE_RIPNG;
1230 else if (strmatch(s, "ospf6"))
1231 return ZEBRA_ROUTE_OSPF6;
1232 else if (strmatch(s, "isis"))
1233 return ZEBRA_ROUTE_ISIS;
1234 else if (strmatch(s, "bgp"))
1235 return ZEBRA_ROUTE_BGP;
1236 else if (strmatch(s, "table"))
1237 return ZEBRA_ROUTE_TABLE;
1238 else if (strmatch(s, "vnc"))
1239 return ZEBRA_ROUTE_VNC;
1240 else if (strmatch(s, "vnc-direct"))
1241 return ZEBRA_ROUTE_VNC_DIRECT;
1242 else if (strmatch(s, "nhrp"))
1243 return ZEBRA_ROUTE_NHRP;
1244 else if (strmatch(s, "babel"))
1245 return ZEBRA_ROUTE_BABEL;
1246 else if (strmatch(s, "sharp"))
1247 return ZEBRA_ROUTE_SHARP;
1248 else if (strmatch(s, "openfabric"))
1249 return ZEBRA_ROUTE_OPENFABRIC;
1250 }
1251 return -1;
1252 }
1253
1254 void zlog_hexdump(const void *mem, unsigned int len)
1255 {
1256 unsigned long i = 0;
1257 unsigned int j = 0;
1258 unsigned int columns = 8;
1259 /*
1260 * 19 bytes for 0xADDRESS:
1261 * 24 bytes for data; 2 chars plus a space per data byte
1262 * 1 byte for space
1263 * 8 bytes for ASCII representation
1264 * 1 byte for a newline
1265 * =====================
1266 * 53 bytes per 8 bytes of data
1267 * 1 byte for null term
1268 */
1269 size_t bs = ((len / 8) + 1) * 53 + 1;
1270 char buf[bs];
1271 char *s = buf;
1272 const unsigned char *memch = mem;
1273
1274 memset(buf, 0, sizeof(buf));
1275
1276 for (i = 0; i < len + ((len % columns) ? (columns - len % columns) : 0);
1277 i++) {
1278 /* print offset */
1279 if (i % columns == 0)
1280 s += snprintf(s, bs - (s - buf),
1281 "0x%016lx: ", (unsigned long)memch + i);
1282
1283 /* print hex data */
1284 if (i < len)
1285 s += snprintf(s, bs - (s - buf), "%02x ", memch[i]);
1286
1287 /* end of block, just aligning for ASCII dump */
1288 else
1289 s += snprintf(s, bs - (s - buf), " ");
1290
1291 /* print ASCII dump */
1292 if (i % columns == (columns - 1)) {
1293 for (j = i - (columns - 1); j <= i; j++) {
1294 /* end of block not really printing */
1295 if (j >= len)
1296 s += snprintf(s, bs - (s - buf), " ");
1297 else if (isprint(memch[j]))
1298 s += snprintf(s, bs - (s - buf), "%c",
1299 memch[j]);
1300 else /* other char */
1301 s += snprintf(s, bs - (s - buf), ".");
1302 }
1303 s += snprintf(s, bs - (s - buf), "\n");
1304 }
1305 }
1306 zlog_debug("\n%s", buf);
1307 }
1308
1309 const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, size_t inlen)
1310 {
1311 const char *inbuf = in;
1312 char *pos = buf, *end = buf + bufsz;
1313 const char *iend = inbuf + inlen;
1314
1315 memset(buf, 0, bufsz);
1316 for (; inbuf < iend; inbuf++) {
1317 /* don't write partial escape sequence */
1318 if (end - pos < 5)
1319 break;
1320
1321 if (*inbuf == '\n')
1322 snprintf(pos, end - pos, "\\n");
1323 else if (*inbuf == '\r')
1324 snprintf(pos, end - pos, "\\r");
1325 else if (*inbuf == '\t')
1326 snprintf(pos, end - pos, "\\t");
1327 else if (*inbuf < ' ' || *inbuf == '"' || *inbuf >= 127)
1328 snprintf(pos, end - pos, "\\x%02hhx", *inbuf);
1329 else
1330 *pos = *inbuf;
1331
1332 pos += strlen(pos);
1333 }
1334 return buf;
1335 }