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