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);
118 register_input_handler(int fd, ihfunc_t func)
120 if (nhandlers >= NHANDLERS)
123 ihandlers[nhandlers].fd = fd;
124 ihandlers[nhandlers++].func = func;
130 main(int argc, char **argv)
135 struct timeval tv, difftime, curtime, lasttime, *timeout;
138 fd_set rfds, readers;
139 int nfds, n, i, secs;
140 extern char todaysversion[];
143 struct timeval timeout, *tvp = &timeout;
144 struct timeval sched, *svp = &sched, now, *nvp = &now;
151 errx(1, "must be root");
153 progname = strrchr(argv[0], '/');
160 while (argc > 0 && *argv[0] == '-') {
161 if (strcmp(*argv, "-d") == 0) {
162 if (argc > 1 && *(argv + 1)[0] != '-') {
175 for (i = 0, d = debugnames;
176 i < sizeof(debugnames) / sizeof(debugnames[0]);
178 if (len >= d->nchars && strncmp(d->name, p, len) == 0)
180 if (i == sizeof(debugnames) / sizeof(debugnames[0])) {
183 fprintf(stderr, "Valid debug levels: ");
184 for (i = 0, d = debugnames;
185 i < sizeof(debugnames) / sizeof(debugnames[0]);
187 if ((j & d->level) == d->level) {
190 fputs(d->name, stderr);
201 debug = DEFAULT_DEBUG;
202 } else if (strcmp(*argv, "-c") == 0) {
205 configfilename = *argv;
208 } else if (strcmp(*argv, "-p") == 0) {
209 dolog(LOG_WARNING, 0, "disabling pruning is no longer supported");
211 } else if (strcmp(*argv, "-P") == 0) {
212 if (argc > 1 && isdigit(*(argv + 1)[0])) {
214 dest_port = atoi(*argv);
216 dest_port = DEFAULT_PORT;
231 fprintf(stderr, "debug level 0x%x ", debug);
233 for (d = debugnames; d < debugnames +
234 sizeof(debugnames) / sizeof(debugnames[0]); d++) {
235 if ((tmpd & d->level) == d->level) {
237 fprintf(stderr, "%c%s", c, d->name);
241 fprintf(stderr, ")\n");
245 openlog("mrouted", LOG_PID, LOG_DAEMON);
246 setlogmask(LOG_UPTO(LOG_NOTICE));
248 openlog("mrouted", LOG_PID);
250 sprintf(versionstring, "mrouted version %s", todaysversion);
252 dolog(LOG_DEBUG, 0, "%s starting", versionstring);
261 gettimeofday(&tv, 0);
262 dvmrp_genid = tv.tv_sec;
264 fp = fopen(genidfilename, "r");
266 fscanf(fp, "%d", &prev_genid);
267 if (prev_genid == dvmrp_genid)
272 fp = fopen(genidfilename, "w");
274 fprintf(fp, "%d", dvmrp_genid);
278 /* Start up the log rate-limiter */
289 * Unfortunately, you can't k_get_version() unless you've
290 * k_init_dvmrp()'d. Now that we want to move the
291 * k_init_dvmrp() to later in the initialization sequence,
292 * we have to do the disgusting hack of initializing,
293 * getting the version, then stopping the kernel multicast
297 vers = k_get_version();
300 * This function must change whenever the kernel version changes
302 if ((((vers >> 8) & 0xff) != 3) ||
303 ((vers & 0xff) != 5))
304 dolog(LOG_ERR, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
305 (vers >> 8) & 0xff, vers & 0xff,
306 PROTOCOL_VERSION, MROUTED_VERSION);
313 gettimeofday(nvp, 0);
314 if (nvp->tv_usec < 500000L){
315 svp->tv_usec = nvp->tv_usec + 500000L;
316 svp->tv_sec = nvp->tv_sec;
318 svp->tv_usec = nvp->tv_usec - 500000L;
319 svp->tv_sec = nvp->tv_sec + 1;
329 sa.sa_handler = handler;
330 sa.sa_flags = 0; /* Interrupt system calls */
331 sigemptyset(&sa.sa_mask);
332 sigaction(SIGHUP, &sa, NULL);
333 sigaction(SIGTERM, &sa, NULL);
334 sigaction(SIGINT, &sa, NULL);
335 sigaction(SIGUSR1, &sa, NULL);
336 sigaction(SIGUSR2, &sa, NULL);
338 if (igmp_socket >= FD_SETSIZE)
339 dolog(LOG_ERR, 0, "descriptor too big");
341 FD_SET(igmp_socket, &readers);
342 nfds = igmp_socket + 1;
343 for (i = 0; i < nhandlers; i++) {
344 if (ihandlers[i].fd >= FD_SETSIZE)
345 dolog(LOG_ERR, 0, "descriptor too big");
346 FD_SET(ihandlers[i].fd, &readers);
347 if (ihandlers[i].fd >= nfds)
348 nfds = ihandlers[i].fd + 1;
353 IF_DEBUG(DEBUG_ROUTE)
356 /* schedule first timer interrupt */
357 timer_setTimer(1, fasttimer, NULL);
358 timer_setTimer(TIMER_INTERVAL, timer, NULL);
362 * Detach from the terminal
374 #if defined(SYSV) || defined(linux)
378 t = open(_PATH_TTY, 2);
380 ioctl(t, TIOCNOTTY, NULL);
390 fp = fopen(pidfilename, "w");
392 fprintf(fp, "%d\n", (int)getpid());
397 * This will cause black holes for the first few seconds after startup,
398 * since we are exchanging routes but not actually forwarding.
399 * However, it eliminates much of the startup transient.
401 * It's possible that we can set a flag which says not to report any
402 * routes (just accept reports) until this timer fires, and then
403 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
406 timer_setTimer(10, final_init, NULL);
412 difftime.tv_usec = 0;
413 gettimeofday(&curtime, NULL);
416 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
417 secs = timer_nextTimer();
422 timeout->tv_sec = secs;
423 timeout->tv_usec = 0;
426 #error "THIS IS BROKEN"
427 if (nvp->tv_sec > svp->tv_sec
428 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
431 if (nvp->tv_usec < 500000L){
432 svp->tv_usec = nvp->tv_usec + 500000L;
433 svp->tv_sec = nvp->tv_sec;
435 svp->tv_usec = nvp->tv_usec - 500000L;
436 svp->tv_sec = nvp->tv_sec + 1;
442 tvp->tv_usec = 500000L;
445 snmp_select_info(&nfds, &rfds, tvp, &block);
447 tvp = NULL; /* block without timeout */
448 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
451 if (sighandled & GOT_SIGINT) {
452 sighandled &= ~GOT_SIGINT;
455 if (sighandled & GOT_SIGHUP) {
456 sighandled &= ~GOT_SIGHUP;
459 if (sighandled & GOT_SIGUSR1) {
460 sighandled &= ~GOT_SIGUSR1;
463 if (sighandled & GOT_SIGUSR2) {
464 sighandled &= ~GOT_SIGUSR2;
468 if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
470 dolog(LOG_WARNING, errno, "select failed");
475 if (FD_ISSET(igmp_socket, &rfds)) {
476 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
479 if (errno != EINTR) dolog(LOG_ERR, errno, "recvfrom");
482 accept_igmp(recvlen);
485 for (i = 0; i < nhandlers; i++) {
486 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
487 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
493 #error "THIS IS BROKEN"
495 snmp_timeout(); /* poll */
498 * Handle timeout queue.
500 * If select + packet processing took more than 1 second,
501 * or if there is a timeout pending, age the timeout queue.
503 * If not, collect usec in difftime to make sure that the
504 * time doesn't drift too badly.
506 * If the timeout handlers took more than 1 second,
507 * age the timeout queue again. XXX This introduces the
508 * potential for infinite loops!
512 * If the select timed out, then there's no other
513 * activity to account for and we don't need to
517 curtime.tv_sec = lasttime.tv_sec + secs;
518 curtime.tv_usec = lasttime.tv_usec;
519 n = -1; /* don't do this next time through the loop */
521 gettimeofday(&curtime, NULL);
522 difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
523 difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
524 while (difftime.tv_usec >= 1000000) {
526 difftime.tv_usec -= 1000000;
528 if (difftime.tv_usec < 0) {
530 difftime.tv_usec += 1000000;
533 if (secs == 0 || difftime.tv_sec > 0)
534 age_callout_queue(difftime.tv_sec);
536 } while (difftime.tv_sec > 0);
538 dolog(LOG_NOTICE, 0, "%s exiting", versionstring);
547 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
556 dolog(LOG_NOTICE, 0, "%s%s", versionstring, s ? s : "");
560 k_init_dvmrp(); /* enable DVMRP routing in kernel */
563 * Install the vifs in the kernel as late as possible in the
564 * initialization sequence.
568 time(&mrouted_init_time);
573 * routine invoked every second. Its main goal is to cycle through
574 * the routing table and send partial updates to all neighbors at a
575 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
576 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
577 * do all the other time-based processing.
582 static unsigned int tlast;
583 static unsigned int nsent;
584 unsigned int t = tlast + 1;
588 * if we're in the last second, send everything that's left.
589 * otherwise send at least the fraction we should have sent by now.
591 if (t >= ROUTE_REPORT_INTERVAL) {
592 int nleft = nroutes - nsent;
594 if ((n = report_next_chunk()) <= 0)
601 unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
602 while (nsent < ncum) {
603 if ((n = report_next_chunk()) <= 0)
610 timer_setTimer(1, fasttimer, NULL);
614 * The 'virtual_time' variable is initialized to a value that will cause the
615 * first invocation of timer() to send a probe or route report to all vifs
616 * and send group membership queries to all subnets for which this router is
617 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
618 * after the router starts up. Note that probes for neighbors and queries
619 * for group memberships are also sent at start-up time, as part of initial-
620 * ization. This repetition after a short interval is desirable for quickly
621 * building up topology and membership information in the presence of possible
624 * 'virtual_time' advances at a rate that is only a crude approximation of
625 * real time, because it does not take into account any time spent processing,
626 * and because the timer intervals are sometimes shrunk by a random amount to
627 * avoid unwanted synchronization with other routers.
630 u_long virtual_time = 0;
634 * Timer routine. Performs periodic neighbor probing, route reporting, and
635 * group querying duties, and drives various timers in routing entries and
636 * virtual interface data structures.
641 age_routes(); /* Advance the timers in the route entries */
642 age_vifs(); /* Advance the timers for neighbors */
643 age_table_entry(); /* Advance the timers for the cache entries */
645 if (virtual_time % IGMP_QUERY_INTERVAL == 0) {
647 * Time to query the local group memberships on all subnets
648 * for which this router is the elected querier.
653 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
655 * Time to send a probe on all vifs from which no neighbors have
656 * been heard. Also, check if any inoperative interfaces have now
657 * come up. (If they have, they will also be probed as part of
658 * their initialization.)
660 probe_for_neighbors();
666 delay_change_reports = FALSE;
667 if (routes_changed) {
669 * Some routes have changed since the last timer interrupt, but
670 * have not been reported yet. Report the changed routes to all
673 report_to_all_neighbors(CHANGED_ROUTES);
681 * Advance virtual time
683 virtual_time += TIMER_INTERVAL;
684 timer_setTimer(TIMER_INTERVAL, timer, NULL);
691 static int in_cleanup = 0;
699 report_to_all_neighbors(ALL_ROUTES);
706 * Signal handler. Take note of the fact that the signal arrived
707 * so that the main loop can take care of it.
715 sighandled |= GOT_SIGINT;
719 sighandled |= GOT_SIGHUP;
723 sighandled |= GOT_SIGUSR1;
727 sighandled |= GOT_SIGUSR2;
733 * Dump internal data structures to stderr.
743 dump_version(FILE *fp)
748 fprintf(fp, "%s ", versionstring);
751 scaletime(t - mrouted_init_time));
753 fprintf(fp, "(not yet initialized)");
754 fprintf(fp, " %s\n", ctime(&t));
758 * Dump internal data structures to a file.
765 fp = fopen(dumpfilename, "w");
776 * Dump local cache contents to a file.
783 fp = fopen(cachefilename, "w");
800 s = (char *)malloc(sizeof(" restart"));
802 dolog(LOG_ERR, 0, "out of memory");
803 strcpy(s, " restart");
806 * reset all the entries
818 * start processing again
826 /*XXX Schedule final_init() as main does? */
829 /* schedule timer interrupts */
830 timer_setTimer(1, fasttimer, NULL);
831 timer_setTimer(TIMER_INTERVAL, timer, NULL);
834 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
835 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
836 static int log_nmsgs = 0;
839 resetlogging(void *arg)
844 if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
845 nxttime = LOG_SHUT_UP;
846 narg = (void *)&log_nmsgs; /* just need some valid void * */
847 syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
853 timer_setTimer(nxttime, resetlogging, narg);
859 #define SCALETIMEBUFLEN 20
860 static char buf1[20];
861 static char buf2[20];
862 static char *buf = buf1;
872 sprintf(p, "%2ld:%02ld:%02ld", t / 3600, (t % 3600) / 60, t % 60);
873 p[SCALETIMEBUFLEN - 1] = '\0';
878 #define NLOGMSGS 10000
879 #define LOGMSGSIZE 200
880 char *logmsg[NLOGMSGS];
881 static int logmsgno = 0;
889 f = fopen("/var/tmp/mrouted.log", "a");
891 dolog(LOG_ERR, errno, "can't open /var/tmp/mrouted.log");
894 fprintf(f, "--------------------------------------------\n");
896 i = (logmsgno + 1) % NLOGMSGS;
898 while (i != logmsgno) {
900 fprintf(f, "%s\n", logmsg[i]);
903 i = (i + 1) % NLOGMSGS;
911 * Log errors and other messages to the system log daemon and to stderr,
912 * according to the severity of the message and the current debug level.
913 * For errors of severity LOG_ERR or worse, terminate the program.
917 dolog(int severity, int syserr, char *format, ...)
920 static char fmt[211] = "warning - ";
926 static int ringbufinit = 0;
929 va_start(ap, format);
930 vsnprintf(&fmt[10], sizeof(fmt) - 10, format, ap);
932 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
938 for (i = 0; i < NLOGMSGS; i++) {
939 logmsg[i] = malloc(LOGMSGSIZE);
940 if (logmsg[i] == NULL) {
941 syslog(LOG_ERR, "out of memory");
948 gettimeofday(&now,NULL);
949 now_sec = now.tv_sec;
950 thyme = localtime(&now_sec);
951 snprintf(logmsg[logmsgno++], LOGMSGSIZE, "%02d:%02d:%02d.%03ld %s err %d",
952 thyme->tm_hour, thyme->tm_min, thyme->tm_sec,
953 now.tv_usec / 1000, msg, syserr);
954 logmsgno %= NLOGMSGS;
955 if (severity <= LOG_NOTICE)
958 * Log to stderr if we haven't forked yet and it's a warning or worse,
959 * or if we're debugging.
961 if (haveterminal && (debug || severity <= LOG_WARNING)) {
962 gettimeofday(&now,NULL);
963 now_sec = now.tv_sec;
964 thyme = localtime(&now_sec);
966 fprintf(stderr, "%s: ", progname);
967 fprintf(stderr, "%02d:%02d:%02d.%03ld %s", thyme->tm_hour,
968 thyme->tm_min, thyme->tm_sec, now.tv_usec / 1000, msg);
970 fprintf(stderr, "\n");
971 else if (syserr < sys_nerr)
972 fprintf(stderr, ": %s\n", sys_errlist[syserr]);
974 fprintf(stderr, ": errno %d\n", syserr);
978 * Always log things that are worse than warnings, no matter what
979 * the log_nmsgs rate limiter says.
980 * Only count things worse than debugging in the rate limiter
981 * (since if you put daemon.debug in syslog.conf you probably
982 * actually want to log the debugging messages so they shouldn't
985 if ((severity < LOG_WARNING) || (log_nmsgs < LOG_MAX_MSGS)) {
986 if (severity < LOG_DEBUG)
990 syslog(severity, "%s: %m", msg);
992 syslog(severity, "%s", msg);
995 if (severity <= LOG_ERR) exit(-1);
1000 md_log(int what, u_int32 origin, u_int32 mcastgrp)
1002 static FILE *f = NULL;
1007 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
1008 dolog(LOG_ERR, errno, "open /tmp/mrouted.clog");
1012 gettimeofday(&tv, NULL);
1018 fwrite(buf, sizeof(u_int32), 4, f);