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