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