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