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