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