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