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