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