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 $
16 * Written by Steve Deering, Stanford University, February 1989.
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.)
35 extern char *configfilename;
36 char versionstring[100];
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;
43 static int haveterminal = 1;
44 int did_final_init = 0;
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
52 int cache_lifetime = DEFAULT_CACHE_LIFETIME;
53 int prune_lifetime = AVERAGE_PRUNE_LIFETIME;
57 time_t mrouted_init_time;
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;
71 static struct debugname {
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. */
102 * Forward declarations.
104 static void final_init(void *);
105 static void fasttimer(void *);
106 static void timer(void *);
107 static void dump(void);
108 static void dump_version(FILE *);
109 static void fdump(void);
110 static void cdump(void);
111 static void restart(void);
112 static void handler(int);
113 static void cleanup(void);
114 static void resetlogging(void *);
115 static void usage(void);
117 /* To shut up gcc -Wstrict-prototypes */
118 int main(int argc, char **argv);
121 register_input_handler(int fd, ihfunc_t func)
123 if (nhandlers >= NHANDLERS)
126 ihandlers[nhandlers].fd = fd;
127 ihandlers[nhandlers++].func = func;
133 main(int argc, char **argv)
138 struct timeval tv, difftime, curtime, lasttime, *timeout;
141 fd_set rfds, readers;
142 int nfds, n, i, secs;
143 extern char todaysversion[];
146 struct timeval timeout, *tvp = &timeout;
147 struct timeval sched, *svp = &sched, now, *nvp = &now;
154 errx(1, "must be root");
156 progname = strrchr(argv[0], '/');
163 while (argc > 0 && *argv[0] == '-') {
164 if (strcmp(*argv, "-d") == 0) {
165 if (argc > 1 && *(argv + 1)[0] != '-') {
178 for (i = 0, d = debugnames;
179 i < sizeof(debugnames) / sizeof(debugnames[0]);
181 if (len >= d->nchars && strncmp(d->name, p, len) == 0)
183 if (i == sizeof(debugnames) / sizeof(debugnames[0])) {
186 fprintf(stderr, "Valid debug levels: ");
187 for (i = 0, d = debugnames;
188 i < sizeof(debugnames) / sizeof(debugnames[0]);
190 if ((j & d->level) == d->level) {
193 fputs(d->name, stderr);
204 debug = DEFAULT_DEBUG;
205 } else if (strcmp(*argv, "-c") == 0) {
208 configfilename = *argv;
211 } else if (strcmp(*argv, "-p") == 0) {
212 dolog(LOG_WARNING, 0, "disabling pruning is no longer supported");
214 } else if (strcmp(*argv, "-P") == 0) {
215 if (argc > 1 && isdigit(*(argv + 1)[0])) {
217 dest_port = atoi(*argv);
219 dest_port = DEFAULT_PORT;
234 fprintf(stderr, "debug level 0x%x ", debug);
236 for (d = debugnames; d < debugnames +
237 sizeof(debugnames) / sizeof(debugnames[0]); d++) {
238 if ((tmpd & d->level) == d->level) {
240 fprintf(stderr, "%c%s", c, d->name);
244 fprintf(stderr, ")\n");
248 openlog("mrouted", LOG_PID, LOG_DAEMON);
249 setlogmask(LOG_UPTO(LOG_NOTICE));
251 openlog("mrouted", LOG_PID);
253 sprintf(versionstring, "mrouted version %s", todaysversion);
255 dolog(LOG_DEBUG, 0, "%s starting", versionstring);
264 gettimeofday(&tv, 0);
265 dvmrp_genid = tv.tv_sec;
267 fp = fopen(genidfilename, "r");
269 fscanf(fp, "%d", &prev_genid);
270 if (prev_genid == dvmrp_genid)
275 fp = fopen(genidfilename, "w");
277 fprintf(fp, "%d", dvmrp_genid);
281 /* Start up the log rate-limiter */
292 * Unfortunately, you can't k_get_version() unless you've
293 * k_init_dvmrp()'d. Now that we want to move the
294 * k_init_dvmrp() to later in the initialization sequence,
295 * we have to do the disgusting hack of initializing,
296 * getting the version, then stopping the kernel multicast
300 vers = k_get_version();
303 * This function must change whenever the kernel version changes
305 if ((((vers >> 8) & 0xff) != 3) ||
306 ((vers & 0xff) != 5))
307 dolog(LOG_ERR, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
308 (vers >> 8) & 0xff, vers & 0xff,
309 PROTOCOL_VERSION, MROUTED_VERSION);
316 gettimeofday(nvp, 0);
317 if (nvp->tv_usec < 500000L){
318 svp->tv_usec = nvp->tv_usec + 500000L;
319 svp->tv_sec = nvp->tv_sec;
321 svp->tv_usec = nvp->tv_usec - 500000L;
322 svp->tv_sec = nvp->tv_sec + 1;
332 sa.sa_handler = handler;
333 sa.sa_flags = 0; /* Interrupt system calls */
334 sigemptyset(&sa.sa_mask);
335 sigaction(SIGHUP, &sa, NULL);
336 sigaction(SIGTERM, &sa, NULL);
337 sigaction(SIGINT, &sa, NULL);
338 sigaction(SIGUSR1, &sa, NULL);
339 sigaction(SIGUSR2, &sa, NULL);
341 if (igmp_socket >= FD_SETSIZE)
342 dolog(LOG_ERR, 0, "descriptor too big");
344 FD_SET(igmp_socket, &readers);
345 nfds = igmp_socket + 1;
346 for (i = 0; i < nhandlers; i++) {
347 if (ihandlers[i].fd >= FD_SETSIZE)
348 dolog(LOG_ERR, 0, "descriptor too big");
349 FD_SET(ihandlers[i].fd, &readers);
350 if (ihandlers[i].fd >= nfds)
351 nfds = ihandlers[i].fd + 1;
356 IF_DEBUG(DEBUG_ROUTE)
359 /* schedule first timer interrupt */
360 timer_setTimer(1, fasttimer, NULL);
361 timer_setTimer(TIMER_INTERVAL, timer, NULL);
365 * Detach from the terminal
377 #if defined(SYSV) || defined(linux)
381 t = open(_PATH_TTY, 2);
383 ioctl(t, TIOCNOTTY, NULL);
393 fp = fopen(pidfilename, "w");
395 fprintf(fp, "%d\n", (int)getpid());
400 * This will cause black holes for the first few seconds after startup,
401 * since we are exchanging routes but not actually forwarding.
402 * However, it eliminates much of the startup transient.
404 * It's possible that we can set a flag which says not to report any
405 * routes (just accept reports) until this timer fires, and then
406 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
409 timer_setTimer(10, final_init, NULL);
415 difftime.tv_usec = 0;
416 gettimeofday(&curtime, NULL);
419 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
420 secs = timer_nextTimer();
425 timeout->tv_sec = secs;
426 timeout->tv_usec = 0;
429 #error "THIS IS BROKEN"
430 if (nvp->tv_sec > svp->tv_sec
431 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
434 if (nvp->tv_usec < 500000L){
435 svp->tv_usec = nvp->tv_usec + 500000L;
436 svp->tv_sec = nvp->tv_sec;
438 svp->tv_usec = nvp->tv_usec - 500000L;
439 svp->tv_sec = nvp->tv_sec + 1;
445 tvp->tv_usec = 500000L;
448 snmp_select_info(&nfds, &rfds, tvp, &block);
450 tvp = NULL; /* block without timeout */
451 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
454 if (sighandled & GOT_SIGINT) {
455 sighandled &= ~GOT_SIGINT;
458 if (sighandled & GOT_SIGHUP) {
459 sighandled &= ~GOT_SIGHUP;
462 if (sighandled & GOT_SIGUSR1) {
463 sighandled &= ~GOT_SIGUSR1;
466 if (sighandled & GOT_SIGUSR2) {
467 sighandled &= ~GOT_SIGUSR2;
471 if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
473 dolog(LOG_WARNING, errno, "select failed");
478 if (FD_ISSET(igmp_socket, &rfds)) {
479 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
482 if (errno != EINTR) dolog(LOG_ERR, errno, "recvfrom");
485 accept_igmp(recvlen);
488 for (i = 0; i < nhandlers; i++) {
489 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
490 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
496 #error "THIS IS BROKEN"
498 snmp_timeout(); /* poll */
501 * Handle timeout queue.
503 * If select + packet processing took more than 1 second,
504 * or if there is a timeout pending, age the timeout queue.
506 * If not, collect usec in difftime to make sure that the
507 * time doesn't drift too badly.
509 * If the timeout handlers took more than 1 second,
510 * age the timeout queue again. XXX This introduces the
511 * potential for infinite loops!
515 * If the select timed out, then there's no other
516 * activity to account for and we don't need to
520 curtime.tv_sec = lasttime.tv_sec + secs;
521 curtime.tv_usec = lasttime.tv_usec;
522 n = -1; /* don't do this next time through the loop */
524 gettimeofday(&curtime, NULL);
525 difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
526 difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
527 while (difftime.tv_usec >= 1000000) {
529 difftime.tv_usec -= 1000000;
531 if (difftime.tv_usec < 0) {
533 difftime.tv_usec += 1000000;
536 if (secs == 0 || difftime.tv_sec > 0)
537 age_callout_queue(difftime.tv_sec);
539 } while (difftime.tv_sec > 0);
541 dolog(LOG_NOTICE, 0, "%s exiting", versionstring);
550 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
559 dolog(LOG_NOTICE, 0, "%s%s", versionstring, s ? s : "");
563 k_init_dvmrp(); /* enable DVMRP routing in kernel */
566 * Install the vifs in the kernel as late as possible in the
567 * initialization sequence.
571 time(&mrouted_init_time);
576 * routine invoked every second. Its main goal is to cycle through
577 * the routing table and send partial updates to all neighbors at a
578 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
579 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
580 * do all the other time-based processing.
585 static unsigned int tlast;
586 static unsigned int nsent;
587 unsigned int t = tlast + 1;
591 * if we're in the last second, send everything that's left.
592 * otherwise send at least the fraction we should have sent by now.
594 if (t >= ROUTE_REPORT_INTERVAL) {
595 int nleft = nroutes - nsent;
597 if ((n = report_next_chunk()) <= 0)
604 unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
605 while (nsent < ncum) {
606 if ((n = report_next_chunk()) <= 0)
613 timer_setTimer(1, fasttimer, NULL);
617 * The 'virtual_time' variable is initialized to a value that will cause the
618 * first invocation of timer() to send a probe or route report to all vifs
619 * and send group membership queries to all subnets for which this router is
620 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
621 * after the router starts up. Note that probes for neighbors and queries
622 * for group memberships are also sent at start-up time, as part of initial-
623 * ization. This repetition after a short interval is desirable for quickly
624 * building up topology and membership information in the presence of possible
627 * 'virtual_time' advances at a rate that is only a crude approximation of
628 * real time, because it does not take into account any time spent processing,
629 * and because the timer intervals are sometimes shrunk by a random amount to
630 * avoid unwanted synchronization with other routers.
633 u_long virtual_time = 0;
637 * Timer routine. Performs periodic neighbor probing, route reporting, and
638 * group querying duties, and drives various timers in routing entries and
639 * virtual interface data structures.
644 age_routes(); /* Advance the timers in the route entries */
645 age_vifs(); /* Advance the timers for neighbors */
646 age_table_entry(); /* Advance the timers for the cache entries */
648 if (virtual_time % IGMP_QUERY_INTERVAL == 0) {
650 * Time to query the local group memberships on all subnets
651 * for which this router is the elected querier.
656 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
658 * Time to send a probe on all vifs from which no neighbors have
659 * been heard. Also, check if any inoperative interfaces have now
660 * come up. (If they have, they will also be probed as part of
661 * their initialization.)
663 probe_for_neighbors();
669 delay_change_reports = FALSE;
670 if (routes_changed) {
672 * Some routes have changed since the last timer interrupt, but
673 * have not been reported yet. Report the changed routes to all
676 report_to_all_neighbors(CHANGED_ROUTES);
684 * Advance virtual time
686 virtual_time += TIMER_INTERVAL;
687 timer_setTimer(TIMER_INTERVAL, timer, NULL);
694 static int in_cleanup = 0;
702 report_to_all_neighbors(ALL_ROUTES);
709 * Signal handler. Take note of the fact that the signal arrived
710 * so that the main loop can take care of it.
718 sighandled |= GOT_SIGINT;
722 sighandled |= GOT_SIGHUP;
726 sighandled |= GOT_SIGUSR1;
730 sighandled |= GOT_SIGUSR2;
736 * Dump internal data structures to stderr.
746 dump_version(FILE *fp)
751 fprintf(fp, "%s ", versionstring);
754 scaletime(t - mrouted_init_time));
756 fprintf(fp, "(not yet initialized)");
757 fprintf(fp, " %s\n", ctime(&t));
761 * Dump internal data structures to a file.
768 fp = fopen(dumpfilename, "w");
779 * Dump local cache contents to a file.
786 fp = fopen(cachefilename, "w");
803 s = (char *)malloc(sizeof(" restart"));
805 dolog(LOG_ERR, 0, "out of memory");
806 strcpy(s, " restart");
809 * reset all the entries
821 * start processing again
829 /*XXX Schedule final_init() as main does? */
832 /* schedule timer interrupts */
833 timer_setTimer(1, fasttimer, NULL);
834 timer_setTimer(TIMER_INTERVAL, timer, NULL);
837 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
838 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
839 static int log_nmsgs = 0;
842 resetlogging(void *arg)
847 if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
848 nxttime = LOG_SHUT_UP;
849 narg = (void *)&log_nmsgs; /* just need some valid void * */
850 syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
856 timer_setTimer(nxttime, resetlogging, narg);
862 #define SCALETIMEBUFLEN 20
863 static char buf1[20];
864 static char buf2[20];
865 static char *buf = buf1;
875 sprintf(p, "%2ld:%02ld:%02ld", t / 3600, (t % 3600) / 60, t % 60);
876 p[SCALETIMEBUFLEN - 1] = '\0';
881 #define NLOGMSGS 10000
882 #define LOGMSGSIZE 200
883 char *logmsg[NLOGMSGS];
884 static int logmsgno = 0;
892 f = fopen("/var/tmp/mrouted.log", "a");
894 dolog(LOG_ERR, errno, "can't open /var/tmp/mrouted.log");
897 fprintf(f, "--------------------------------------------\n");
899 i = (logmsgno + 1) % NLOGMSGS;
901 while (i != logmsgno) {
903 fprintf(f, "%s\n", logmsg[i]);
906 i = (i + 1) % NLOGMSGS;
914 * Log errors and other messages to the system log daemon and to stderr,
915 * according to the severity of the message and the current debug level.
916 * For errors of severity LOG_ERR or worse, terminate the program.
920 dolog(int severity, int syserr, char *format, ...)
923 static char fmt[211] = "warning - ";
929 static int ringbufinit = 0;
932 va_start(ap, format);
933 vsnprintf(&fmt[10], sizeof(fmt) - 10, format, ap);
935 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
941 for (i = 0; i < NLOGMSGS; i++) {
942 logmsg[i] = malloc(LOGMSGSIZE);
943 if (logmsg[i] == NULL) {
944 syslog(LOG_ERR, "out of memory");
951 gettimeofday(&now,NULL);
952 now_sec = now.tv_sec;
953 thyme = localtime(&now_sec);
954 snprintf(logmsg[logmsgno++], LOGMSGSIZE, "%02d:%02d:%02d.%03ld %s err %d",
955 thyme->tm_hour, thyme->tm_min, thyme->tm_sec,
956 now.tv_usec / 1000, msg, syserr);
957 logmsgno %= NLOGMSGS;
958 if (severity <= LOG_NOTICE)
961 * Log to stderr if we haven't forked yet and it's a warning or worse,
962 * or if we're debugging.
964 if (haveterminal && (debug || severity <= LOG_WARNING)) {
965 gettimeofday(&now,NULL);
966 now_sec = now.tv_sec;
967 thyme = localtime(&now_sec);
969 fprintf(stderr, "%s: ", progname);
970 fprintf(stderr, "%02d:%02d:%02d.%03ld %s", thyme->tm_hour,
971 thyme->tm_min, thyme->tm_sec, now.tv_usec / 1000, msg);
973 fprintf(stderr, "\n");
974 else if (syserr < sys_nerr)
975 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
977 fprintf(stderr, ": errno %d\n", syserr);
981 * Always log things that are worse than warnings, no matter what
982 * the log_nmsgs rate limiter says.
983 * Only count things worse than debugging in the rate limiter
984 * (since if you put daemon.debug in syslog.conf you probably
985 * actually want to log the debugging messages so they shouldn't
988 if ((severity < LOG_WARNING) || (log_nmsgs < LOG_MAX_MSGS)) {
989 if (severity < LOG_DEBUG)
993 syslog(severity, "%s: %m", msg);
995 syslog(severity, "%s", msg);
998 if (severity <= LOG_ERR) exit(-1);
1003 md_log(int what, u_int32 origin, u_int32 mcastgrp)
1005 static FILE *f = NULL;
1010 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
1011 dolog(LOG_ERR, errno, "open /tmp/mrouted.clog");
1015 gettimeofday(&tv, NULL);
1021 fwrite(buf, sizeof(u_int32), 4, f);