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
14 * Written by Steve Deering, Stanford University, February 1989.
16 * (An earlier version of DVMRP was implemented by David Waitzman of
17 * BBN STC by extending Berkeley's routed program. Some of Waitzman's
18 * extensions have been incorporated into mrouted, but none of the
19 * original routed code has been adopted.)
24 static const char rcsid[] =
25 "$FreeBSD: src/usr.sbin/mrouted/main.c,v 1.16.2.4 2002/09/12 16:27:49 nectar Exp $";
42 extern char *configfilename;
43 char versionstring[100];
45 static char pidfilename[] = _PATH_MROUTED_PID;
46 static char dumpfilename[] = _PATH_MROUTED_DUMP;
47 static char cachefilename[] = _PATH_MROUTED_CACHE;
48 static char genidfilename[] = _PATH_MROUTED_GENID;
50 static int haveterminal = 1;
51 int did_final_init = 0;
53 static int sighandled = 0;
54 #define GOT_SIGINT 0x01
55 #define GOT_SIGHUP 0x02
56 #define GOT_SIGUSR1 0x04
57 #define GOT_SIGUSR2 0x08
59 int cache_lifetime = DEFAULT_CACHE_LIFETIME;
60 int prune_lifetime = AVERAGE_PRUNE_LIFETIME;
64 time_t mrouted_init_time;
72 static struct ihandler {
73 int fd; /* File descriptor */
74 ihfunc_t func; /* Function to call with &fd_set */
75 } ihandlers[NHANDLERS];
76 static int nhandlers = 0;
78 static struct debugname {
83 { "packet", DEBUG_PKT, 2 },
84 { "pkt", DEBUG_PKT, 3 },
85 { "pruning", DEBUG_PRUNE, 1 },
86 { "prunes", DEBUG_PRUNE, 1 },
87 { "routing", DEBUG_ROUTE, 1 },
88 { "routes", DEBUG_ROUTE, 1 },
89 { "route_detail", DEBUG_RTDETAIL, 6 },
90 { "rtdetail", DEBUG_RTDETAIL, 2 },
91 { "peers", DEBUG_PEER, 2 },
92 { "neighbors", DEBUG_PEER, 1 },
93 { "cache", DEBUG_CACHE, 1 },
94 { "timeout", DEBUG_TIMEOUT, 1 },
95 { "callout", DEBUG_TIMEOUT, 2 },
96 { "interface", DEBUG_IF, 2 },
97 { "vif", DEBUG_IF, 1 },
98 { "membership", DEBUG_MEMBER, 1 },
99 { "groups", DEBUG_MEMBER, 1 },
100 { "traceroute", DEBUG_TRACE, 2 },
101 { "mtrace", DEBUG_TRACE, 2 },
102 { "igmp", DEBUG_IGMP, 1 },
103 { "icmp", DEBUG_ICMP, 2 },
104 { "rsrr", DEBUG_RSRR, 2 },
105 { "3", 0xffffffff, 1 } /* compat. */
109 * Forward declarations.
111 static void final_init __P((void *));
112 static void fasttimer __P((void *));
113 static void timer __P((void *));
114 static void dump __P((void));
115 static void dump_version __P((FILE *));
116 static void fdump __P((void));
117 static void cdump __P((void));
118 static void restart __P((void));
119 static void handler __P((int));
120 static void cleanup __P((void));
121 static void resetlogging __P((void *));
122 static void usage __P((void));
124 /* To shut up gcc -Wstrict-prototypes */
125 int main __P((int argc, char **argv));
128 register_input_handler(fd, func)
132 if (nhandlers >= NHANDLERS)
135 ihandlers[nhandlers].fd = fd;
136 ihandlers[nhandlers++].func = func;
146 register int recvlen;
149 struct timeval tv, difftime, curtime, lasttime, *timeout;
152 fd_set rfds, readers;
153 int nfds, n, i, secs;
154 extern char todaysversion[];
157 struct timeval timeout, *tvp = &timeout;
158 struct timeval sched, *svp = &sched, now, *nvp = &now;
165 errx(1, "must be root");
167 progname = strrchr(argv[0], '/');
174 while (argc > 0 && *argv[0] == '-') {
175 if (strcmp(*argv, "-d") == 0) {
176 if (argc > 1 && *(argv + 1)[0] != '-') {
189 for (i = 0, d = debugnames;
190 i < sizeof(debugnames) / sizeof(debugnames[0]);
192 if (len >= d->nchars && strncmp(d->name, p, len) == 0)
194 if (i == sizeof(debugnames) / sizeof(debugnames[0])) {
197 fprintf(stderr, "Valid debug levels: ");
198 for (i = 0, d = debugnames;
199 i < sizeof(debugnames) / sizeof(debugnames[0]);
201 if ((j & d->level) == d->level) {
204 fputs(d->name, stderr);
215 debug = DEFAULT_DEBUG;
216 } else if (strcmp(*argv, "-c") == 0) {
219 configfilename = *argv;
222 } else if (strcmp(*argv, "-p") == 0) {
223 log(LOG_WARNING, 0, "disabling pruning is no longer supported");
225 } else if (strcmp(*argv, "-P") == 0) {
226 if (argc > 1 && isdigit(*(argv + 1)[0])) {
228 dest_port = atoi(*argv);
230 dest_port = DEFAULT_PORT;
245 fprintf(stderr, "debug level 0x%x ", debug);
247 for (d = debugnames; d < debugnames +
248 sizeof(debugnames) / sizeof(debugnames[0]); d++) {
249 if ((tmpd & d->level) == d->level) {
251 fprintf(stderr, "%c%s", c, d->name);
255 fprintf(stderr, ")\n");
259 (void)openlog("mrouted", LOG_PID, LOG_DAEMON);
260 (void)setlogmask(LOG_UPTO(LOG_NOTICE));
262 (void)openlog("mrouted", LOG_PID);
264 sprintf(versionstring, "mrouted version %s", todaysversion);
266 log(LOG_DEBUG, 0, "%s starting", versionstring);
275 gettimeofday(&tv, 0);
276 dvmrp_genid = tv.tv_sec;
278 fp = fopen(genidfilename, "r");
280 fscanf(fp, "%d", &prev_genid);
281 if (prev_genid == dvmrp_genid)
286 fp = fopen(genidfilename, "w");
288 fprintf(fp, "%d", dvmrp_genid);
292 /* Start up the log rate-limiter */
303 * Unfortunately, you can't k_get_version() unless you've
304 * k_init_dvmrp()'d. Now that we want to move the
305 * k_init_dvmrp() to later in the initialization sequence,
306 * we have to do the disgusting hack of initializing,
307 * getting the version, then stopping the kernel multicast
311 vers = k_get_version();
314 * This function must change whenever the kernel version changes
316 if ((((vers >> 8) & 0xff) != 3) ||
317 ((vers & 0xff) != 5))
318 log(LOG_ERR, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
319 (vers >> 8) & 0xff, vers & 0xff,
320 PROTOCOL_VERSION, MROUTED_VERSION);
327 gettimeofday(nvp, 0);
328 if (nvp->tv_usec < 500000L){
329 svp->tv_usec = nvp->tv_usec + 500000L;
330 svp->tv_sec = nvp->tv_sec;
332 svp->tv_usec = nvp->tv_usec - 500000L;
333 svp->tv_sec = nvp->tv_sec + 1;
343 sa.sa_handler = handler;
344 sa.sa_flags = 0; /* Interrupt system calls */
345 sigemptyset(&sa.sa_mask);
346 sigaction(SIGHUP, &sa, NULL);
347 sigaction(SIGTERM, &sa, NULL);
348 sigaction(SIGINT, &sa, NULL);
349 sigaction(SIGUSR1, &sa, NULL);
350 sigaction(SIGUSR2, &sa, NULL);
352 if (igmp_socket >= FD_SETSIZE)
353 log(LOG_ERR, 0, "descriptor too big");
355 FD_SET(igmp_socket, &readers);
356 nfds = igmp_socket + 1;
357 for (i = 0; i < nhandlers; i++) {
358 if (ihandlers[i].fd >= FD_SETSIZE)
359 log(LOG_ERR, 0, "descriptor too big");
360 FD_SET(ihandlers[i].fd, &readers);
361 if (ihandlers[i].fd >= nfds)
362 nfds = ihandlers[i].fd + 1;
367 IF_DEBUG(DEBUG_ROUTE)
370 /* schedule first timer interrupt */
371 timer_setTimer(1, fasttimer, NULL);
372 timer_setTimer(TIMER_INTERVAL, timer, NULL);
376 * Detach from the terminal
388 #if defined(SYSV) || defined(linux)
392 t = open(_PATH_TTY, 2);
394 (void)ioctl(t, TIOCNOTTY, (char *)0);
404 fp = fopen(pidfilename, "w");
406 fprintf(fp, "%d\n", (int)getpid());
411 * This will cause black holes for the first few seconds after startup,
412 * since we are exchanging routes but not actually forwarding.
413 * However, it eliminates much of the startup transient.
415 * It's possible that we can set a flag which says not to report any
416 * routes (just accept reports) until this timer fires, and then
417 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
420 timer_setTimer(10, final_init, NULL);
426 difftime.tv_usec = 0;
427 gettimeofday(&curtime, NULL);
430 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
431 secs = timer_nextTimer();
436 timeout->tv_sec = secs;
437 timeout->tv_usec = 0;
441 if (nvp->tv_sec > svp->tv_sec
442 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
445 if (nvp->tv_usec < 500000L){
446 svp->tv_usec = nvp->tv_usec + 500000L;
447 svp->tv_sec = nvp->tv_sec;
449 svp->tv_usec = nvp->tv_usec - 500000L;
450 svp->tv_sec = nvp->tv_sec + 1;
456 tvp->tv_usec = 500000L;
459 snmp_select_info(&nfds, &rfds, tvp, &block);
461 tvp = NULL; /* block without timeout */
462 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
465 if (sighandled & GOT_SIGINT) {
466 sighandled &= ~GOT_SIGINT;
469 if (sighandled & GOT_SIGHUP) {
470 sighandled &= ~GOT_SIGHUP;
473 if (sighandled & GOT_SIGUSR1) {
474 sighandled &= ~GOT_SIGUSR1;
477 if (sighandled & GOT_SIGUSR2) {
478 sighandled &= ~GOT_SIGUSR2;
482 if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
484 log(LOG_WARNING, errno, "select failed");
489 if (FD_ISSET(igmp_socket, &rfds)) {
490 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
493 if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
496 accept_igmp(recvlen);
499 for (i = 0; i < nhandlers; i++) {
500 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
501 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
509 snmp_timeout(); /* poll */
512 * Handle timeout queue.
514 * If select + packet processing took more than 1 second,
515 * or if there is a timeout pending, age the timeout queue.
517 * If not, collect usec in difftime to make sure that the
518 * time doesn't drift too badly.
520 * If the timeout handlers took more than 1 second,
521 * age the timeout queue again. XXX This introduces the
522 * potential for infinite loops!
526 * If the select timed out, then there's no other
527 * activity to account for and we don't need to
531 curtime.tv_sec = lasttime.tv_sec + secs;
532 curtime.tv_usec = lasttime.tv_usec;
533 n = -1; /* don't do this next time through the loop */
535 gettimeofday(&curtime, NULL);
536 difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
537 difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
538 while (difftime.tv_usec >= 1000000) {
540 difftime.tv_usec -= 1000000;
542 if (difftime.tv_usec < 0) {
544 difftime.tv_usec += 1000000;
547 if (secs == 0 || difftime.tv_sec > 0)
548 age_callout_queue(difftime.tv_sec);
550 } while (difftime.tv_sec > 0);
552 log(LOG_NOTICE, 0, "%s exiting", versionstring);
561 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
571 log(LOG_NOTICE, 0, "%s%s", versionstring, s ? s : "");
575 k_init_dvmrp(); /* enable DVMRP routing in kernel */
578 * Install the vifs in the kernel as late as possible in the
579 * initialization sequence.
583 time(&mrouted_init_time);
588 * routine invoked every second. Its main goal is to cycle through
589 * the routing table and send partial updates to all neighbors at a
590 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
591 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
592 * do all the other time-based processing.
598 static unsigned int tlast;
599 static unsigned int nsent;
600 register unsigned int t = tlast + 1;
604 * if we're in the last second, send everything that's left.
605 * otherwise send at least the fraction we should have sent by now.
607 if (t >= ROUTE_REPORT_INTERVAL) {
608 register int nleft = nroutes - nsent;
610 if ((n = report_next_chunk()) <= 0)
617 register unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
618 while (nsent < ncum) {
619 if ((n = report_next_chunk()) <= 0)
626 timer_setTimer(1, fasttimer, NULL);
630 * The 'virtual_time' variable is initialized to a value that will cause the
631 * first invocation of timer() to send a probe or route report to all vifs
632 * and send group membership queries to all subnets for which this router is
633 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
634 * after the router starts up. Note that probes for neighbors and queries
635 * for group memberships are also sent at start-up time, as part of initial-
636 * ization. This repetition after a short interval is desirable for quickly
637 * building up topology and membership information in the presence of possible
640 * 'virtual_time' advances at a rate that is only a crude approximation of
641 * real time, because it does not take into account any time spent processing,
642 * and because the timer intervals are sometimes shrunk by a random amount to
643 * avoid unwanted synchronization with other routers.
646 u_long virtual_time = 0;
650 * Timer routine. Performs periodic neighbor probing, route reporting, and
651 * group querying duties, and drives various timers in routing entries and
652 * virtual interface data structures.
658 age_routes(); /* Advance the timers in the route entries */
659 age_vifs(); /* Advance the timers for neighbors */
660 age_table_entry(); /* Advance the timers for the cache entries */
662 if (virtual_time % IGMP_QUERY_INTERVAL == 0) {
664 * Time to query the local group memberships on all subnets
665 * for which this router is the elected querier.
670 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
672 * Time to send a probe on all vifs from which no neighbors have
673 * been heard. Also, check if any inoperative interfaces have now
674 * come up. (If they have, they will also be probed as part of
675 * their initialization.)
677 probe_for_neighbors();
683 delay_change_reports = FALSE;
684 if (routes_changed) {
686 * Some routes have changed since the last timer interrupt, but
687 * have not been reported yet. Report the changed routes to all
690 report_to_all_neighbors(CHANGED_ROUTES);
698 * Advance virtual time
700 virtual_time += TIMER_INTERVAL;
701 timer_setTimer(TIMER_INTERVAL, timer, NULL);
708 static in_cleanup = 0;
716 report_to_all_neighbors(ALL_ROUTES);
723 * Signal handler. Take note of the fact that the signal arrived
724 * so that the main loop can take care of it.
733 sighandled |= GOT_SIGINT;
737 sighandled |= GOT_SIGHUP;
741 sighandled |= GOT_SIGUSR1;
745 sighandled |= GOT_SIGUSR2;
751 * Dump internal data structures to stderr.
767 fprintf(fp, "%s ", versionstring);
770 scaletime(t - mrouted_init_time));
772 fprintf(fp, "(not yet initialized)");
773 fprintf(fp, " %s\n", ctime(&t));
777 * Dump internal data structures to a file.
784 fp = fopen(dumpfilename, "w");
795 * Dump local cache contents to a file.
802 fp = fopen(cachefilename, "w");
819 s = (char *)malloc(sizeof(" restart"));
821 log(LOG_ERR, 0, "out of memory");
822 strcpy(s, " restart");
825 * reset all the entries
837 * start processing again
845 /*XXX Schedule final_init() as main does? */
848 /* schedule timer interrupts */
849 timer_setTimer(1, fasttimer, NULL);
850 timer_setTimer(TIMER_INTERVAL, timer, NULL);
853 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
854 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
855 static int log_nmsgs = 0;
864 if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
865 nxttime = LOG_SHUT_UP;
866 narg = (void *)&log_nmsgs; /* just need some valid void * */
867 syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
873 timer_setTimer(nxttime, resetlogging, narg);
880 #define SCALETIMEBUFLEN 20
881 static char buf1[20];
882 static char buf2[20];
883 static char *buf = buf1;
893 sprintf(p, "%2ld:%02ld:%02ld", t / 3600, (t % 3600) / 60, t % 60);
894 p[SCALETIMEBUFLEN - 1] = '\0';
899 #define NLOGMSGS 10000
900 #define LOGMSGSIZE 200
901 char *logmsg[NLOGMSGS];
902 static int logmsgno = 0;
910 f = fopen("/var/tmp/mrouted.log", "a");
912 log(LOG_ERR, errno, "can't open /var/tmp/mrouted.log");
915 fprintf(f, "--------------------------------------------\n");
917 i = (logmsgno + 1) % NLOGMSGS;
919 while (i != logmsgno) {
921 fprintf(f, "%s\n", logmsg[i]);
924 i = (i + 1) % NLOGMSGS;
932 * Log errors and other messages to the system log daemon and to stderr,
933 * according to the severity of the message and the current debug level.
934 * For errors of severity LOG_ERR or worse, terminate the program.
938 log(int severity, int syserr, char *format, ...)
941 static char fmt[211] = "warning - ";
947 static int ringbufinit = 0;
950 va_start(ap, format);
954 log(severity, syserr, format, va_alist)
955 int severity, syserr;
960 static char fmt[311] = "warning - ";
967 static int ringbufinit = 0;
972 vsnprintf(&fmt[10], sizeof(fmt) - 10, format, ap);
974 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
980 for (i = 0; i < NLOGMSGS; i++) {
981 logmsg[i] = malloc(LOGMSGSIZE);
982 if (logmsg[i] == 0) {
983 syslog(LOG_ERR, "out of memory");
990 gettimeofday(&now,NULL);
991 now_sec = now.tv_sec;
992 thyme = localtime(&now_sec);
993 snprintf(logmsg[logmsgno++], LOGMSGSIZE, "%02d:%02d:%02d.%03ld %s err %d",
994 thyme->tm_hour, thyme->tm_min, thyme->tm_sec,
995 now.tv_usec / 1000, msg, syserr);
996 logmsgno %= NLOGMSGS;
997 if (severity <= LOG_NOTICE)
1000 * Log to stderr if we haven't forked yet and it's a warning or worse,
1001 * or if we're debugging.
1003 if (haveterminal && (debug || severity <= LOG_WARNING)) {
1004 gettimeofday(&now,NULL);
1005 now_sec = now.tv_sec;
1006 thyme = localtime(&now_sec);
1008 fprintf(stderr, "%s: ", progname);
1009 fprintf(stderr, "%02d:%02d:%02d.%03ld %s", thyme->tm_hour,
1010 thyme->tm_min, thyme->tm_sec, now.tv_usec / 1000, msg);
1012 fprintf(stderr, "\n");
1013 else if (syserr < sys_nerr)
1014 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
1016 fprintf(stderr, ": errno %d\n", syserr);
1020 * Always log things that are worse than warnings, no matter what
1021 * the log_nmsgs rate limiter says.
1022 * Only count things worse than debugging in the rate limiter
1023 * (since if you put daemon.debug in syslog.conf you probably
1024 * actually want to log the debugging messages so they shouldn't
1027 if ((severity < LOG_WARNING) || (log_nmsgs < LOG_MAX_MSGS)) {
1028 if (severity < LOG_DEBUG)
1032 syslog(severity, "%s: %m", msg);
1034 syslog(severity, "%s", msg);
1037 if (severity <= LOG_ERR) exit(-1);
1042 md_log(what, origin, mcastgrp)
1044 u_int32 origin, mcastgrp;
1046 static FILE *f = NULL;
1051 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
1052 log(LOG_ERR, errno, "open /tmp/mrouted.clog");
1056 gettimeofday(&tv, NULL);
1062 fwrite(buf, sizeof(u_int32), 4, f);