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