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