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