MFC r1.6 r1.30 r1.28 (HEAD):
[dragonfly.git] / usr.sbin / mrouted / main.c
blob5c55d39f7046198bd0ca6d99854d31a0a2516e59
1 /*
2 * The mrouted program is covered by the license in the accompanying file
3 * named "LICENSE". Use of the mrouted program represents acceptance of
4 * the terms and conditions listed in that file.
6 * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
7 * Leland Stanford Junior University.
10 * main.c,v 3.8.4.29 1998/03/01 01:49:00 fenner Exp
12 * $FreeBSD: src/usr.sbin/mrouted/main.c,v 1.16.2.4 2002/09/12 16:27:49 nectar Exp $
13 * $DragonFly: src/usr.sbin/mrouted/main.c,v 1.5 2004/12/18 22:48:04 swildner Exp $
17 * Written by Steve Deering, Stanford University, February 1989.
19 * (An earlier version of DVMRP was implemented by David Waitzman of
20 * BBN STC by extending Berkeley's routed program. Some of Waitzman's
21 * extensions have been incorporated into mrouted, but none of the
22 * original routed code has been adopted.)
26 #include <err.h>
27 #include "defs.h"
28 #ifdef __STDC__
29 #include <stdarg.h>
30 #else
31 #include <varargs.h>
32 #endif
33 #include <fcntl.h>
34 #include <paths.h>
36 #ifdef SNMP
37 #include "snmp.h"
38 #endif
40 extern char *configfilename;
41 char versionstring[100];
43 static char pidfilename[] = _PATH_MROUTED_PID;
44 static char dumpfilename[] = _PATH_MROUTED_DUMP;
45 static char cachefilename[] = _PATH_MROUTED_CACHE;
46 static char genidfilename[] = _PATH_MROUTED_GENID;
48 static int haveterminal = 1;
49 int did_final_init = 0;
51 static int sighandled = 0;
52 #define GOT_SIGINT 0x01
53 #define GOT_SIGHUP 0x02
54 #define GOT_SIGUSR1 0x04
55 #define GOT_SIGUSR2 0x08
57 int cache_lifetime = DEFAULT_CACHE_LIFETIME;
58 int prune_lifetime = AVERAGE_PRUNE_LIFETIME;
60 int debug = 0;
61 char *progname;
62 time_t mrouted_init_time;
64 #ifdef SNMP
65 #define NHANDLERS 34
66 #else
67 #define NHANDLERS 2
68 #endif
70 static struct ihandler {
71 int fd; /* File descriptor */
72 ihfunc_t func; /* Function to call with &fd_set */
73 } ihandlers[NHANDLERS];
74 static int nhandlers = 0;
76 static struct debugname {
77 char *name;
78 int level;
79 int nchars;
80 } debugnames[] = {
81 { "packet", DEBUG_PKT, 2 },
82 { "pkt", DEBUG_PKT, 3 },
83 { "pruning", DEBUG_PRUNE, 1 },
84 { "prunes", DEBUG_PRUNE, 1 },
85 { "routing", DEBUG_ROUTE, 1 },
86 { "routes", DEBUG_ROUTE, 1 },
87 { "route_detail", DEBUG_RTDETAIL, 6 },
88 { "rtdetail", DEBUG_RTDETAIL, 2 },
89 { "peers", DEBUG_PEER, 2 },
90 { "neighbors", DEBUG_PEER, 1 },
91 { "cache", DEBUG_CACHE, 1 },
92 { "timeout", DEBUG_TIMEOUT, 1 },
93 { "callout", DEBUG_TIMEOUT, 2 },
94 { "interface", DEBUG_IF, 2 },
95 { "vif", DEBUG_IF, 1 },
96 { "membership", DEBUG_MEMBER, 1 },
97 { "groups", DEBUG_MEMBER, 1 },
98 { "traceroute", DEBUG_TRACE, 2 },
99 { "mtrace", DEBUG_TRACE, 2 },
100 { "igmp", DEBUG_IGMP, 1 },
101 { "icmp", DEBUG_ICMP, 2 },
102 { "rsrr", DEBUG_RSRR, 2 },
103 { "3", 0xffffffff, 1 } /* compat. */
107 * Forward declarations.
109 static void final_init(void *);
110 static void fasttimer(void *);
111 static void timer(void *);
112 static void dump(void);
113 static void dump_version(FILE *);
114 static void fdump(void);
115 static void cdump(void);
116 static void restart(void);
117 static void handler(int);
118 static void cleanup(void);
119 static void resetlogging(void *);
120 static void usage(void);
122 /* To shut up gcc -Wstrict-prototypes */
123 int main(int argc, char **argv);
126 register_input_handler(int fd, ihfunc_t func)
128 if (nhandlers >= NHANDLERS)
129 return -1;
131 ihandlers[nhandlers].fd = fd;
132 ihandlers[nhandlers++].func = func;
134 return 0;
138 main(int argc, char **argv)
140 int recvlen;
141 int dummy;
142 FILE *fp;
143 struct timeval tv, difftime, curtime, lasttime, *timeout;
144 u_int32 prev_genid;
145 int vers;
146 fd_set rfds, readers;
147 int nfds, n, i, secs;
148 extern char todaysversion[];
149 struct sigaction sa;
150 #ifdef SNMP
151 struct timeval timeout, *tvp = &timeout;
152 struct timeval sched, *svp = &sched, now, *nvp = &now;
153 int index, block;
154 #endif
156 setlinebuf(stderr);
158 if (geteuid() != 0)
159 errx(1, "must be root");
161 progname = strrchr(argv[0], '/');
162 if (progname)
163 progname++;
164 else
165 progname = argv[0];
167 argv++, argc--;
168 while (argc > 0 && *argv[0] == '-') {
169 if (strcmp(*argv, "-d") == 0) {
170 if (argc > 1 && *(argv + 1)[0] != '-') {
171 char *p,*q;
172 int i, len;
173 struct debugname *d;
175 argv++, argc--;
176 debug = 0;
177 p = *argv; q = NULL;
178 while (p) {
179 q = strchr(p, ',');
180 if (q)
181 *q++ = '\0';
182 len = strlen(p);
183 for (i = 0, d = debugnames;
184 i < sizeof(debugnames) / sizeof(debugnames[0]);
185 i++, d++)
186 if (len >= d->nchars && strncmp(d->name, p, len) == 0)
187 break;
188 if (i == sizeof(debugnames) / sizeof(debugnames[0])) {
189 int j = 0xffffffff;
190 int k = 0;
191 fprintf(stderr, "Valid debug levels: ");
192 for (i = 0, d = debugnames;
193 i < sizeof(debugnames) / sizeof(debugnames[0]);
194 i++, d++) {
195 if ((j & d->level) == d->level) {
196 if (k++)
197 putc(',', stderr);
198 fputs(d->name, stderr);
199 j &= ~d->level;
202 putc('\n', stderr);
203 usage();
205 debug |= d->level;
206 p = q;
208 } else
209 debug = DEFAULT_DEBUG;
210 } else if (strcmp(*argv, "-c") == 0) {
211 if (argc > 1) {
212 argv++, argc--;
213 configfilename = *argv;
214 } else
215 usage();
216 } else if (strcmp(*argv, "-p") == 0) {
217 log(LOG_WARNING, 0, "disabling pruning is no longer supported");
218 #ifdef SNMP
219 } else if (strcmp(*argv, "-P") == 0) {
220 if (argc > 1 && isdigit(*(argv + 1)[0])) {
221 argv++, argc--;
222 dest_port = atoi(*argv);
223 } else
224 dest_port = DEFAULT_PORT;
225 #endif
226 } else
227 usage();
228 argv++, argc--;
231 if (argc > 0)
232 usage();
234 if (debug != 0) {
235 struct debugname *d;
236 char c;
237 int tmpd = debug;
239 fprintf(stderr, "debug level 0x%x ", debug);
240 c = '(';
241 for (d = debugnames; d < debugnames +
242 sizeof(debugnames) / sizeof(debugnames[0]); d++) {
243 if ((tmpd & d->level) == d->level) {
244 tmpd &= ~d->level;
245 fprintf(stderr, "%c%s", c, d->name);
246 c = ',';
249 fprintf(stderr, ")\n");
252 #ifdef LOG_DAEMON
253 openlog("mrouted", LOG_PID, LOG_DAEMON);
254 setlogmask(LOG_UPTO(LOG_NOTICE));
255 #else
256 openlog("mrouted", LOG_PID);
257 #endif
258 sprintf(versionstring, "mrouted version %s", todaysversion);
260 log(LOG_DEBUG, 0, "%s starting", versionstring);
262 #ifdef SYSV
263 srand48(time(NULL));
264 #endif
267 * Get generation id
269 gettimeofday(&tv, 0);
270 dvmrp_genid = tv.tv_sec;
272 fp = fopen(genidfilename, "r");
273 if (fp != NULL) {
274 fscanf(fp, "%d", &prev_genid);
275 if (prev_genid == dvmrp_genid)
276 dvmrp_genid++;
277 fclose(fp);
280 fp = fopen(genidfilename, "w");
281 if (fp != NULL) {
282 fprintf(fp, "%d", dvmrp_genid);
283 fclose(fp);
286 /* Start up the log rate-limiter */
287 resetlogging(NULL);
289 callout_init();
290 init_igmp();
291 init_icmp();
292 init_ipip();
293 init_routes();
294 init_ktable();
295 #ifndef OLD_KERNEL
297 * Unfortunately, you can't k_get_version() unless you've
298 * k_init_dvmrp()'d. Now that we want to move the
299 * k_init_dvmrp() to later in the initialization sequence,
300 * we have to do the disgusting hack of initializing,
301 * getting the version, then stopping the kernel multicast
302 * forwarding.
304 k_init_dvmrp();
305 vers = k_get_version();
306 k_stop_dvmrp();
307 /*XXX
308 * This function must change whenever the kernel version changes
310 if ((((vers >> 8) & 0xff) != 3) ||
311 ((vers & 0xff) != 5))
312 log(LOG_ERR, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
313 (vers >> 8) & 0xff, vers & 0xff,
314 PROTOCOL_VERSION, MROUTED_VERSION);
315 #endif
317 #ifdef SNMP
318 if (i = snmp_init())
319 return i;
321 gettimeofday(nvp, 0);
322 if (nvp->tv_usec < 500000L){
323 svp->tv_usec = nvp->tv_usec + 500000L;
324 svp->tv_sec = nvp->tv_sec;
325 } else {
326 svp->tv_usec = nvp->tv_usec - 500000L;
327 svp->tv_sec = nvp->tv_sec + 1;
329 #endif /* SNMP */
331 init_vifs();
333 #ifdef RSRR
334 rsrr_init();
335 #endif /* RSRR */
337 sa.sa_handler = handler;
338 sa.sa_flags = 0; /* Interrupt system calls */
339 sigemptyset(&sa.sa_mask);
340 sigaction(SIGHUP, &sa, NULL);
341 sigaction(SIGTERM, &sa, NULL);
342 sigaction(SIGINT, &sa, NULL);
343 sigaction(SIGUSR1, &sa, NULL);
344 sigaction(SIGUSR2, &sa, NULL);
346 if (igmp_socket >= FD_SETSIZE)
347 log(LOG_ERR, 0, "descriptor too big");
348 FD_ZERO(&readers);
349 FD_SET(igmp_socket, &readers);
350 nfds = igmp_socket + 1;
351 for (i = 0; i < nhandlers; i++) {
352 if (ihandlers[i].fd >= FD_SETSIZE)
353 log(LOG_ERR, 0, "descriptor too big");
354 FD_SET(ihandlers[i].fd, &readers);
355 if (ihandlers[i].fd >= nfds)
356 nfds = ihandlers[i].fd + 1;
359 IF_DEBUG(DEBUG_IF)
360 dump_vifs(stderr);
361 IF_DEBUG(DEBUG_ROUTE)
362 dump_routes(stderr);
364 /* schedule first timer interrupt */
365 timer_setTimer(1, fasttimer, NULL);
366 timer_setTimer(TIMER_INTERVAL, timer, NULL);
368 if (debug == 0) {
370 * Detach from the terminal
372 int t;
374 haveterminal = 0;
375 if (fork()) exit(0);
376 close(0);
377 close(1);
378 close(2);
379 open("/", 0);
380 dup2(0, 1);
381 dup2(0, 2);
382 #if defined(SYSV) || defined(linux)
383 setpgrp();
384 #else
385 #ifdef TIOCNOTTY
386 t = open(_PATH_TTY, 2);
387 if (t >= 0) {
388 ioctl(t, TIOCNOTTY, (char *)0);
389 close(t);
391 #else
392 if (setsid() < 0)
393 perror("setsid");
394 #endif
395 #endif
398 fp = fopen(pidfilename, "w");
399 if (fp != NULL) {
400 fprintf(fp, "%d\n", (int)getpid());
401 fclose(fp);
404 /* XXX HACK
405 * This will cause black holes for the first few seconds after startup,
406 * since we are exchanging routes but not actually forwarding.
407 * However, it eliminates much of the startup transient.
409 * It's possible that we can set a flag which says not to report any
410 * routes (just accept reports) until this timer fires, and then
411 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
412 * turning on DVMRP.
414 timer_setTimer(10, final_init, NULL);
417 * Main receive loop.
419 dummy = 0;
420 difftime.tv_usec = 0;
421 gettimeofday(&curtime, NULL);
422 lasttime = curtime;
423 for(;;) {
424 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
425 secs = timer_nextTimer();
426 if (secs == -1)
427 timeout = NULL;
428 else {
429 timeout = &tv;
430 timeout->tv_sec = secs;
431 timeout->tv_usec = 0;
433 #ifdef SNMP
434 #error "THIS IS BROKEN"
435 if (nvp->tv_sec > svp->tv_sec
436 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
437 alarmTimer(nvp);
438 eventTimer(nvp);
439 if (nvp->tv_usec < 500000L){
440 svp->tv_usec = nvp->tv_usec + 500000L;
441 svp->tv_sec = nvp->tv_sec;
442 } else {
443 svp->tv_usec = nvp->tv_usec - 500000L;
444 svp->tv_sec = nvp->tv_sec + 1;
448 tvp = &timeout;
449 tvp->tv_sec = 0;
450 tvp->tv_usec = 500000L;
452 block = 0;
453 snmp_select_info(&nfds, &rfds, tvp, &block);
454 if (block == 1)
455 tvp = NULL; /* block without timeout */
456 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
457 #endif
458 if (sighandled) {
459 if (sighandled & GOT_SIGINT) {
460 sighandled &= ~GOT_SIGINT;
461 break;
463 if (sighandled & GOT_SIGHUP) {
464 sighandled &= ~GOT_SIGHUP;
465 restart();
467 if (sighandled & GOT_SIGUSR1) {
468 sighandled &= ~GOT_SIGUSR1;
469 fdump();
471 if (sighandled & GOT_SIGUSR2) {
472 sighandled &= ~GOT_SIGUSR2;
473 cdump();
476 if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
477 if (errno != EINTR)
478 log(LOG_WARNING, errno, "select failed");
479 continue;
482 if (n > 0) {
483 if (FD_ISSET(igmp_socket, &rfds)) {
484 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
485 0, NULL, &dummy);
486 if (recvlen < 0) {
487 if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
488 continue;
490 accept_igmp(recvlen);
493 for (i = 0; i < nhandlers; i++) {
494 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
495 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
500 #ifdef SNMP
501 #error "THIS IS BROKEN"
502 snmp_read(&rfds);
503 snmp_timeout(); /* poll */
504 #endif
506 * Handle timeout queue.
508 * If select + packet processing took more than 1 second,
509 * or if there is a timeout pending, age the timeout queue.
511 * If not, collect usec in difftime to make sure that the
512 * time doesn't drift too badly.
514 * If the timeout handlers took more than 1 second,
515 * age the timeout queue again. XXX This introduces the
516 * potential for infinite loops!
518 do {
520 * If the select timed out, then there's no other
521 * activity to account for and we don't need to
522 * call gettimeofday.
524 if (n == 0) {
525 curtime.tv_sec = lasttime.tv_sec + secs;
526 curtime.tv_usec = lasttime.tv_usec;
527 n = -1; /* don't do this next time through the loop */
528 } else
529 gettimeofday(&curtime, NULL);
530 difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
531 difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
532 while (difftime.tv_usec >= 1000000) {
533 difftime.tv_sec++;
534 difftime.tv_usec -= 1000000;
536 if (difftime.tv_usec < 0) {
537 difftime.tv_sec--;
538 difftime.tv_usec += 1000000;
540 lasttime = curtime;
541 if (secs == 0 || difftime.tv_sec > 0)
542 age_callout_queue(difftime.tv_sec);
543 secs = -1;
544 } while (difftime.tv_sec > 0);
546 log(LOG_NOTICE, 0, "%s exiting", versionstring);
547 cleanup();
548 exit(0);
551 static void
552 usage(void)
554 fprintf(stderr,
555 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
556 exit(1);
559 static void
560 final_init(void *i)
562 char *s = (char *)i;
564 log(LOG_NOTICE, 0, "%s%s", versionstring, s ? s : "");
565 if (s)
566 free(s);
568 k_init_dvmrp(); /* enable DVMRP routing in kernel */
571 * Install the vifs in the kernel as late as possible in the
572 * initialization sequence.
574 init_installvifs();
576 time(&mrouted_init_time);
577 did_final_init = 1;
581 * routine invoked every second. Its main goal is to cycle through
582 * the routing table and send partial updates to all neighbors at a
583 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
584 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
585 * do all the other time-based processing.
587 static void
588 fasttimer(void *i)
590 static unsigned int tlast;
591 static unsigned int nsent;
592 unsigned int t = tlast + 1;
593 int n;
596 * if we're in the last second, send everything that's left.
597 * otherwise send at least the fraction we should have sent by now.
599 if (t >= ROUTE_REPORT_INTERVAL) {
600 int nleft = nroutes - nsent;
601 while (nleft > 0) {
602 if ((n = report_next_chunk()) <= 0)
603 break;
604 nleft -= n;
606 tlast = 0;
607 nsent = 0;
608 } else {
609 unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
610 while (nsent < ncum) {
611 if ((n = report_next_chunk()) <= 0)
612 break;
613 nsent += n;
615 tlast = t;
618 timer_setTimer(1, fasttimer, NULL);
622 * The 'virtual_time' variable is initialized to a value that will cause the
623 * first invocation of timer() to send a probe or route report to all vifs
624 * and send group membership queries to all subnets for which this router is
625 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
626 * after the router starts up. Note that probes for neighbors and queries
627 * for group memberships are also sent at start-up time, as part of initial-
628 * ization. This repetition after a short interval is desirable for quickly
629 * building up topology and membership information in the presence of possible
630 * packet loss.
632 * 'virtual_time' advances at a rate that is only a crude approximation of
633 * real time, because it does not take into account any time spent processing,
634 * and because the timer intervals are sometimes shrunk by a random amount to
635 * avoid unwanted synchronization with other routers.
638 u_long virtual_time = 0;
642 * Timer routine. Performs periodic neighbor probing, route reporting, and
643 * group querying duties, and drives various timers in routing entries and
644 * virtual interface data structures.
646 static void
647 timer(void *i)
649 age_routes(); /* Advance the timers in the route entries */
650 age_vifs(); /* Advance the timers for neighbors */
651 age_table_entry(); /* Advance the timers for the cache entries */
653 if (virtual_time % IGMP_QUERY_INTERVAL == 0) {
655 * Time to query the local group memberships on all subnets
656 * for which this router is the elected querier.
658 query_groups();
661 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
663 * Time to send a probe on all vifs from which no neighbors have
664 * been heard. Also, check if any inoperative interfaces have now
665 * come up. (If they have, they will also be probed as part of
666 * their initialization.)
668 probe_for_neighbors();
670 if (vifs_down)
671 check_vif_state();
674 delay_change_reports = FALSE;
675 if (routes_changed) {
677 * Some routes have changed since the last timer interrupt, but
678 * have not been reported yet. Report the changed routes to all
679 * neighbors.
681 report_to_all_neighbors(CHANGED_ROUTES);
684 #ifdef SNMP
685 sync_timer();
686 #endif
689 * Advance virtual time
691 virtual_time += TIMER_INTERVAL;
692 timer_setTimer(TIMER_INTERVAL, timer, NULL);
696 static void
697 cleanup(void)
699 static in_cleanup = 0;
701 if (!in_cleanup) {
702 in_cleanup++;
703 #ifdef RSRR
704 rsrr_clean();
705 #endif /* RSRR */
706 expire_all_routes();
707 report_to_all_neighbors(ALL_ROUTES);
708 if (did_final_init)
709 k_stop_dvmrp();
714 * Signal handler. Take note of the fact that the signal arrived
715 * so that the main loop can take care of it.
717 static void
718 handler(int sig)
720 switch (sig) {
721 case SIGINT:
722 case SIGTERM:
723 sighandled |= GOT_SIGINT;
724 break;
726 case SIGHUP:
727 sighandled |= GOT_SIGHUP;
728 break;
730 case SIGUSR1:
731 sighandled |= GOT_SIGUSR1;
732 break;
734 case SIGUSR2:
735 sighandled |= GOT_SIGUSR2;
736 break;
741 * Dump internal data structures to stderr.
743 static void
744 dump(void)
746 dump_vifs(stderr);
747 dump_routes(stderr);
750 static void
751 dump_version(FILE *fp)
753 time_t t;
755 time(&t);
756 fprintf(fp, "%s ", versionstring);
757 if (did_final_init)
758 fprintf(fp, "up %s",
759 scaletime(t - mrouted_init_time));
760 else
761 fprintf(fp, "(not yet initialized)");
762 fprintf(fp, " %s\n", ctime(&t));
766 * Dump internal data structures to a file.
768 static void
769 fdump(void)
771 FILE *fp;
773 fp = fopen(dumpfilename, "w");
774 if (fp != NULL) {
775 dump_version(fp);
776 dump_vifs(fp);
777 dump_routes(fp);
778 fclose(fp);
784 * Dump local cache contents to a file.
786 static void
787 cdump(void)
789 FILE *fp;
791 fp = fopen(cachefilename, "w");
792 if (fp != NULL) {
793 dump_version(fp);
794 dump_cache(fp);
795 fclose(fp);
801 * Restart mrouted
803 static void
804 restart(void)
806 char *s;
808 s = (char *)malloc(sizeof(" restart"));
809 if (s == NULL)
810 log(LOG_ERR, 0, "out of memory");
811 strcpy(s, " restart");
814 * reset all the entries
816 free_all_prunes();
817 free_all_routes();
818 free_all_callouts();
819 stop_all_vifs();
820 k_stop_dvmrp();
821 close(igmp_socket);
822 close(udp_socket);
823 did_final_init = 0;
826 * start processing again
828 dvmrp_genid++;
830 init_igmp();
831 init_routes();
832 init_ktable();
833 init_vifs();
834 /*XXX Schedule final_init() as main does? */
835 final_init(s);
837 /* schedule timer interrupts */
838 timer_setTimer(1, fasttimer, NULL);
839 timer_setTimer(TIMER_INTERVAL, timer, NULL);
842 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
843 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
844 static int log_nmsgs = 0;
846 static void
847 resetlogging(void *arg)
849 int nxttime = 60;
850 void *narg = NULL;
852 if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
853 nxttime = LOG_SHUT_UP;
854 narg = (void *)&log_nmsgs; /* just need some valid void * */
855 syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
856 LOG_SHUT_UP / 60);
857 } else {
858 log_nmsgs = 0;
861 timer_setTimer(nxttime, resetlogging, narg);
864 char *
865 scaletime(u_long t)
867 #define SCALETIMEBUFLEN 20
868 static char buf1[20];
869 static char buf2[20];
870 static char *buf = buf1;
871 char *p;
873 p = buf;
874 if (buf == buf1)
875 buf = buf2;
876 else
877 buf = buf1;
879 /* XXX snprintf */
880 sprintf(p, "%2ld:%02ld:%02ld", t / 3600, (t % 3600) / 60, t % 60);
881 p[SCALETIMEBUFLEN - 1] = '\0';
882 return p;
885 #ifdef RINGBUFFER
886 #define NLOGMSGS 10000
887 #define LOGMSGSIZE 200
888 char *logmsg[NLOGMSGS];
889 static int logmsgno = 0;
891 void
892 printringbuf(void)
894 FILE *f;
895 int i;
897 f = fopen("/var/tmp/mrouted.log", "a");
898 if (f == NULL) {
899 log(LOG_ERR, errno, "can't open /var/tmp/mrouted.log");
900 /*NOTREACHED*/
902 fprintf(f, "--------------------------------------------\n");
904 i = (logmsgno + 1) % NLOGMSGS;
906 while (i != logmsgno) {
907 if (*logmsg[i]) {
908 fprintf(f, "%s\n", logmsg[i]);
909 *logmsg[i] = '\0';
911 i = (i + 1) % NLOGMSGS;
914 fclose(f);
916 #endif
919 * Log errors and other messages to the system log daemon and to stderr,
920 * according to the severity of the message and the current debug level.
921 * For errors of severity LOG_ERR or worse, terminate the program.
924 void
925 log(int severity, int syserr, char *format, ...)
927 va_list ap;
928 static char fmt[211] = "warning - ";
929 char *msg;
930 struct timeval now;
931 time_t now_sec;
932 struct tm *thyme;
933 #ifdef RINGBUFFER
934 static int ringbufinit = 0;
935 #endif
937 va_start(ap, format);
938 vsnprintf(&fmt[10], sizeof(fmt) - 10, format, ap);
939 va_end(ap);
940 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
942 #ifdef RINGBUFFER
943 if (!ringbufinit) {
944 int i;
946 for (i = 0; i < NLOGMSGS; i++) {
947 logmsg[i] = malloc(LOGMSGSIZE);
948 if (logmsg[i] == 0) {
949 syslog(LOG_ERR, "out of memory");
950 exit(-1);
952 *logmsg[i] = 0;
954 ringbufinit = 1;
956 gettimeofday(&now,NULL);
957 now_sec = now.tv_sec;
958 thyme = localtime(&now_sec);
959 snprintf(logmsg[logmsgno++], LOGMSGSIZE, "%02d:%02d:%02d.%03ld %s err %d",
960 thyme->tm_hour, thyme->tm_min, thyme->tm_sec,
961 now.tv_usec / 1000, msg, syserr);
962 logmsgno %= NLOGMSGS;
963 if (severity <= LOG_NOTICE)
964 #endif
966 * Log to stderr if we haven't forked yet and it's a warning or worse,
967 * or if we're debugging.
969 if (haveterminal && (debug || severity <= LOG_WARNING)) {
970 gettimeofday(&now,NULL);
971 now_sec = now.tv_sec;
972 thyme = localtime(&now_sec);
973 if (!debug)
974 fprintf(stderr, "%s: ", progname);
975 fprintf(stderr, "%02d:%02d:%02d.%03ld %s", thyme->tm_hour,
976 thyme->tm_min, thyme->tm_sec, now.tv_usec / 1000, msg);
977 if (syserr == 0)
978 fprintf(stderr, "\n");
979 else if (syserr < sys_nerr)
980 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
981 else
982 fprintf(stderr, ": errno %d\n", syserr);
986 * Always log things that are worse than warnings, no matter what
987 * the log_nmsgs rate limiter says.
988 * Only count things worse than debugging in the rate limiter
989 * (since if you put daemon.debug in syslog.conf you probably
990 * actually want to log the debugging messages so they shouldn't
991 * be rate-limited)
993 if ((severity < LOG_WARNING) || (log_nmsgs < LOG_MAX_MSGS)) {
994 if (severity < LOG_DEBUG)
995 log_nmsgs++;
996 if (syserr != 0) {
997 errno = syserr;
998 syslog(severity, "%s: %m", msg);
999 } else
1000 syslog(severity, "%s", msg);
1003 if (severity <= LOG_ERR) exit(-1);
1006 #ifdef DEBUG_MFC
1007 void
1008 md_log(int what, u_int32 origin, u_int32 mcastgrp)
1010 static FILE *f = NULL;
1011 struct timeval tv;
1012 u_int32 buf[4];
1014 if (!f) {
1015 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
1016 log(LOG_ERR, errno, "open /tmp/mrouted.clog");
1020 gettimeofday(&tv, NULL);
1021 buf[0] = tv.tv_sec;
1022 buf[1] = what;
1023 buf[2] = origin;
1024 buf[3] = mcastgrp;
1026 fwrite(buf, sizeof(u_int32), 4, f);
1028 #endif