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