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