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