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.
6 * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
7 * Leland Stanford Junior University.
10 * main.c,v 3.8.4.29 1998/03/01 01:49:00 fenner Exp
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 $
17 * Written by Steve Deering, Stanford University, February 1989.
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.)
40 extern char *configfilename;
41 char versionstring[100];
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;
48 static int haveterminal = 1;
49 int did_final_init = 0;
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
57 int cache_lifetime = DEFAULT_CACHE_LIFETIME;
58 int prune_lifetime = AVERAGE_PRUNE_LIFETIME;
62 time_t mrouted_init_time;
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;
76 static struct debugname {
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. */
107 * Forward declarations.
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));
122 /* To shut up gcc -Wstrict-prototypes */
123 int main __P((int argc, char **argv));
126 register_input_handler(fd, func)
130 if (nhandlers >= NHANDLERS)
133 ihandlers[nhandlers].fd = fd;
134 ihandlers[nhandlers++].func = func;
144 register int recvlen;
147 struct timeval tv, difftime, curtime, lasttime, *timeout;
150 fd_set rfds, readers;
151 int nfds, n, i, secs;
152 extern char todaysversion[];
155 struct timeval timeout, *tvp = &timeout;
156 struct timeval sched, *svp = &sched, now, *nvp = &now;
163 errx(1, "must be root");
165 progname = strrchr(argv[0], '/');
172 while (argc > 0 && *argv[0] == '-') {
173 if (strcmp(*argv, "-d") == 0) {
174 if (argc > 1 && *(argv + 1)[0] != '-') {
187 for (i = 0, d = debugnames;
188 i < sizeof(debugnames) / sizeof(debugnames[0]);
190 if (len >= d->nchars && strncmp(d->name, p, len) == 0)
192 if (i == sizeof(debugnames) / sizeof(debugnames[0])) {
195 fprintf(stderr, "Valid debug levels: ");
196 for (i = 0, d = debugnames;
197 i < sizeof(debugnames) / sizeof(debugnames[0]);
199 if ((j & d->level) == d->level) {
202 fputs(d->name, stderr);
213 debug = DEFAULT_DEBUG;
214 } else if (strcmp(*argv, "-c") == 0) {
217 configfilename = *argv;
220 } else if (strcmp(*argv, "-p") == 0) {
221 log(LOG_WARNING, 0, "disabling pruning is no longer supported");
223 } else if (strcmp(*argv, "-P") == 0) {
224 if (argc > 1 && isdigit(*(argv + 1)[0])) {
226 dest_port = atoi(*argv);
228 dest_port = DEFAULT_PORT;
243 fprintf(stderr, "debug level 0x%x ", debug);
245 for (d = debugnames; d < debugnames +
246 sizeof(debugnames) / sizeof(debugnames[0]); d++) {
247 if ((tmpd & d->level) == d->level) {
249 fprintf(stderr, "%c%s", c, d->name);
253 fprintf(stderr, ")\n");
257 (void)openlog("mrouted", LOG_PID, LOG_DAEMON);
258 (void)setlogmask(LOG_UPTO(LOG_NOTICE));
260 (void)openlog("mrouted", LOG_PID);
262 sprintf(versionstring, "mrouted version %s", todaysversion);
264 log(LOG_DEBUG, 0, "%s starting", versionstring);
273 gettimeofday(&tv, 0);
274 dvmrp_genid = tv.tv_sec;
276 fp = fopen(genidfilename, "r");
278 fscanf(fp, "%d", &prev_genid);
279 if (prev_genid == dvmrp_genid)
284 fp = fopen(genidfilename, "w");
286 fprintf(fp, "%d", dvmrp_genid);
290 /* Start up the log rate-limiter */
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
309 vers = k_get_version();
312 * This function must change whenever the kernel version changes
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);
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;
330 svp->tv_usec = nvp->tv_usec - 500000L;
331 svp->tv_sec = nvp->tv_sec + 1;
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);
350 if (igmp_socket >= FD_SETSIZE)
351 log(LOG_ERR, 0, "descriptor too big");
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;
365 IF_DEBUG(DEBUG_ROUTE)
368 /* schedule first timer interrupt */
369 timer_setTimer(1, fasttimer, NULL);
370 timer_setTimer(TIMER_INTERVAL, timer, NULL);
374 * Detach from the terminal
386 #if defined(SYSV) || defined(linux)
390 t = open(_PATH_TTY, 2);
392 (void)ioctl(t, TIOCNOTTY, (char *)0);
402 fp = fopen(pidfilename, "w");
404 fprintf(fp, "%d\n", (int)getpid());
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.
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
418 timer_setTimer(10, final_init, NULL);
424 difftime.tv_usec = 0;
425 gettimeofday(&curtime, NULL);
428 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
429 secs = timer_nextTimer();
434 timeout->tv_sec = secs;
435 timeout->tv_usec = 0;
439 if (nvp->tv_sec > svp->tv_sec
440 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
443 if (nvp->tv_usec < 500000L){
444 svp->tv_usec = nvp->tv_usec + 500000L;
445 svp->tv_sec = nvp->tv_sec;
447 svp->tv_usec = nvp->tv_usec - 500000L;
448 svp->tv_sec = nvp->tv_sec + 1;
454 tvp->tv_usec = 500000L;
457 snmp_select_info(&nfds, &rfds, tvp, &block);
459 tvp = NULL; /* block without timeout */
460 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
463 if (sighandled & GOT_SIGINT) {
464 sighandled &= ~GOT_SIGINT;
467 if (sighandled & GOT_SIGHUP) {
468 sighandled &= ~GOT_SIGHUP;
471 if (sighandled & GOT_SIGUSR1) {
472 sighandled &= ~GOT_SIGUSR1;
475 if (sighandled & GOT_SIGUSR2) {
476 sighandled &= ~GOT_SIGUSR2;
480 if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
482 log(LOG_WARNING, errno, "select failed");
487 if (FD_ISSET(igmp_socket, &rfds)) {
488 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
491 if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
494 accept_igmp(recvlen);
497 for (i = 0; i < nhandlers; i++) {
498 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
499 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
507 snmp_timeout(); /* poll */
510 * Handle timeout queue.
512 * If select + packet processing took more than 1 second,
513 * or if there is a timeout pending, age the timeout queue.
515 * If not, collect usec in difftime to make sure that the
516 * time doesn't drift too badly.
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!
524 * If the select timed out, then there's no other
525 * activity to account for and we don't need to
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 */
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) {
538 difftime.tv_usec -= 1000000;
540 if (difftime.tv_usec < 0) {
542 difftime.tv_usec += 1000000;
545 if (secs == 0 || difftime.tv_sec > 0)
546 age_callout_queue(difftime.tv_sec);
548 } while (difftime.tv_sec > 0);
550 log(LOG_NOTICE, 0, "%s exiting", versionstring);
559 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
569 log(LOG_NOTICE, 0, "%s%s", versionstring, s ? s : "");
573 k_init_dvmrp(); /* enable DVMRP routing in kernel */
576 * Install the vifs in the kernel as late as possible in the
577 * initialization sequence.
581 time(&mrouted_init_time);
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.
596 static unsigned int tlast;
597 static unsigned int nsent;
598 register unsigned int t = tlast + 1;
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.
605 if (t >= ROUTE_REPORT_INTERVAL) {
606 register int nleft = nroutes - nsent;
608 if ((n = report_next_chunk()) <= 0)
615 register unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
616 while (nsent < ncum) {
617 if ((n = report_next_chunk()) <= 0)
624 timer_setTimer(1, fasttimer, NULL);
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
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.
644 u_long virtual_time = 0;
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.
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 */
660 if (virtual_time % IGMP_QUERY_INTERVAL == 0) {
662 * Time to query the local group memberships on all subnets
663 * for which this router is the elected querier.
668 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
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.)
675 probe_for_neighbors();
681 delay_change_reports = FALSE;
682 if (routes_changed) {
684 * Some routes have changed since the last timer interrupt, but
685 * have not been reported yet. Report the changed routes to all
688 report_to_all_neighbors(CHANGED_ROUTES);
696 * Advance virtual time
698 virtual_time += TIMER_INTERVAL;
699 timer_setTimer(TIMER_INTERVAL, timer, NULL);
706 static in_cleanup = 0;
714 report_to_all_neighbors(ALL_ROUTES);
721 * Signal handler. Take note of the fact that the signal arrived
722 * so that the main loop can take care of it.
731 sighandled |= GOT_SIGINT;
735 sighandled |= GOT_SIGHUP;
739 sighandled |= GOT_SIGUSR1;
743 sighandled |= GOT_SIGUSR2;
749 * Dump internal data structures to stderr.
765 fprintf(fp, "%s ", versionstring);
768 scaletime(t - mrouted_init_time));
770 fprintf(fp, "(not yet initialized)");
771 fprintf(fp, " %s\n", ctime(&t));
775 * Dump internal data structures to a file.
782 fp = fopen(dumpfilename, "w");
793 * Dump local cache contents to a file.
800 fp = fopen(cachefilename, "w");
817 s = (char *)malloc(sizeof(" restart"));
819 log(LOG_ERR, 0, "out of memory");
820 strcpy(s, " restart");
823 * reset all the entries
835 * start processing again
843 /*XXX Schedule final_init() as main does? */
846 /* schedule timer interrupts */
847 timer_setTimer(1, fasttimer, NULL);
848 timer_setTimer(TIMER_INTERVAL, timer, NULL);
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;
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",
871 timer_setTimer(nxttime, resetlogging, narg);
878 #define SCALETIMEBUFLEN 20
879 static char buf1[20];
880 static char buf2[20];
881 static char *buf = buf1;
891 sprintf(p, "%2ld:%02ld:%02ld", t / 3600, (t % 3600) / 60, t % 60);
892 p[SCALETIMEBUFLEN - 1] = '\0';
897 #define NLOGMSGS 10000
898 #define LOGMSGSIZE 200
899 char *logmsg[NLOGMSGS];
900 static int logmsgno = 0;
908 f = fopen("/var/tmp/mrouted.log", "a");
910 log(LOG_ERR, errno, "can't open /var/tmp/mrouted.log");
913 fprintf(f, "--------------------------------------------\n");
915 i = (logmsgno + 1) % NLOGMSGS;
917 while (i != logmsgno) {
919 fprintf(f, "%s\n", logmsg[i]);
922 i = (i + 1) % NLOGMSGS;
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.
936 log(int severity, int syserr, char *format, ...)
939 static char fmt[211] = "warning - ";
945 static int ringbufinit = 0;
948 va_start(ap, format);
952 log(severity, syserr, format, va_alist)
953 int severity, syserr;
958 static char fmt[311] = "warning - ";
965 static int ringbufinit = 0;
970 vsnprintf(&fmt[10], sizeof(fmt) - 10, format, ap);
972 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
978 for (i = 0; i < NLOGMSGS; i++) {
979 logmsg[i] = malloc(LOGMSGSIZE);
980 if (logmsg[i] == 0) {
981 syslog(LOG_ERR, "out of memory");
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)
998 * Log to stderr if we haven't forked yet and it's a warning or worse,
999 * or if we're debugging.
1001 if (haveterminal && (debug || severity <= LOG_WARNING)) {
1002 gettimeofday(&now,NULL);
1003 now_sec = now.tv_sec;
1004 thyme = localtime(&now_sec);
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);
1010 fprintf(stderr, "\n");
1011 else if (syserr < sys_nerr)
1012 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
1014 fprintf(stderr, ": errno %d\n", syserr);
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
1025 if ((severity < LOG_WARNING) || (log_nmsgs < LOG_MAX_MSGS)) {
1026 if (severity < LOG_DEBUG)
1030 syslog(severity, "%s: %m", msg);
1032 syslog(severity, "%s", msg);
1035 if (severity <= LOG_ERR) exit(-1);
1040 md_log(what, origin, mcastgrp)
1042 u_int32 origin, mcastgrp;
1044 static FILE *f = NULL;
1049 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
1050 log(LOG_ERR, errno, "open /tmp/mrouted.clog");
1054 gettimeofday(&tv, NULL);
1060 fwrite(buf, sizeof(u_int32), 4, f);