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_version(FILE *);
108 static void fdump(void);
109 static void cdump(void);
110 static void restart(void);
111 static void handler(int);
112 static void cleanup(void);
113 static void resetlogging(void *);
114 static void usage(void);
117 register_input_handler(int fd
, ihfunc_t func
)
119 if (nhandlers
>= NHANDLERS
)
122 ihandlers
[nhandlers
].fd
= fd
;
123 ihandlers
[nhandlers
++].func
= func
;
129 main(int argc
, char **argv
)
134 struct timeval tv
, difftime
, curtime
, lasttime
, *timeout
;
137 fd_set rfds
, readers
;
138 int nfds
, n
, i
, secs
;
139 extern char todaysversion
[];
142 struct timeval timeout
, *tvp
= &timeout
;
143 struct timeval sched
, *svp
= &sched
, now
, *nvp
= &now
;
150 errx(1, "must be root");
152 progname
= strrchr(argv
[0], '/');
159 while (argc
> 0 && *argv
[0] == '-') {
160 if (strcmp(*argv
, "-d") == 0) {
161 if (argc
> 1 && *(argv
+ 1)[0] != '-') {
174 for (i
= 0, d
= debugnames
;
175 i
< sizeof(debugnames
) / sizeof(debugnames
[0]);
177 if (len
>= d
->nchars
&& strncmp(d
->name
, p
, len
) == 0)
179 if (i
== sizeof(debugnames
) / sizeof(debugnames
[0])) {
182 fprintf(stderr
, "Valid debug levels: ");
183 for (i
= 0, d
= debugnames
;
184 i
< sizeof(debugnames
) / sizeof(debugnames
[0]);
186 if ((j
& d
->level
) == d
->level
) {
189 fputs(d
->name
, stderr
);
200 debug
= DEFAULT_DEBUG
;
201 } else if (strcmp(*argv
, "-c") == 0) {
204 configfilename
= *argv
;
207 } else if (strcmp(*argv
, "-p") == 0) {
208 dolog(LOG_WARNING
, 0, "disabling pruning is no longer supported");
210 } else if (strcmp(*argv
, "-P") == 0) {
211 if (argc
> 1 && isdigit(*(argv
+ 1)[0])) {
213 dest_port
= atoi(*argv
);
215 dest_port
= DEFAULT_PORT
;
230 fprintf(stderr
, "debug level 0x%x ", debug
);
232 for (d
= debugnames
; d
< debugnames
+
233 sizeof(debugnames
) / sizeof(debugnames
[0]); d
++) {
234 if ((tmpd
& d
->level
) == d
->level
) {
236 fprintf(stderr
, "%c%s", c
, d
->name
);
240 fprintf(stderr
, ")\n");
244 openlog("mrouted", LOG_PID
, LOG_DAEMON
);
245 setlogmask(LOG_UPTO(LOG_NOTICE
));
247 openlog("mrouted", LOG_PID
);
249 sprintf(versionstring
, "mrouted version %s", todaysversion
);
251 dolog(LOG_DEBUG
, 0, "%s starting", versionstring
);
260 gettimeofday(&tv
, 0);
261 dvmrp_genid
= tv
.tv_sec
;
263 fp
= fopen(genidfilename
, "r");
265 fscanf(fp
, "%d", &prev_genid
);
266 if (prev_genid
== dvmrp_genid
)
271 fp
= fopen(genidfilename
, "w");
273 fprintf(fp
, "%d", dvmrp_genid
);
277 /* Start up the log rate-limiter */
288 * Unfortunately, you can't k_get_version() unless you've
289 * k_init_dvmrp()'d. Now that we want to move the
290 * k_init_dvmrp() to later in the initialization sequence,
291 * we have to do the disgusting hack of initializing,
292 * getting the version, then stopping the kernel multicast
296 vers
= k_get_version();
299 * This function must change whenever the kernel version changes
301 if ((((vers
>> 8) & 0xff) != 3) ||
302 ((vers
& 0xff) != 5))
303 dolog(LOG_ERR
, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
304 (vers
>> 8) & 0xff, vers
& 0xff,
305 PROTOCOL_VERSION
, MROUTED_VERSION
);
312 gettimeofday(nvp
, 0);
313 if (nvp
->tv_usec
< 500000L){
314 svp
->tv_usec
= nvp
->tv_usec
+ 500000L;
315 svp
->tv_sec
= nvp
->tv_sec
;
317 svp
->tv_usec
= nvp
->tv_usec
- 500000L;
318 svp
->tv_sec
= nvp
->tv_sec
+ 1;
328 sa
.sa_handler
= handler
;
329 sa
.sa_flags
= 0; /* Interrupt system calls */
330 sigemptyset(&sa
.sa_mask
);
331 sigaction(SIGHUP
, &sa
, NULL
);
332 sigaction(SIGTERM
, &sa
, NULL
);
333 sigaction(SIGINT
, &sa
, NULL
);
334 sigaction(SIGUSR1
, &sa
, NULL
);
335 sigaction(SIGUSR2
, &sa
, NULL
);
337 if (igmp_socket
>= FD_SETSIZE
)
338 dolog(LOG_ERR
, 0, "descriptor too big");
340 FD_SET(igmp_socket
, &readers
);
341 nfds
= igmp_socket
+ 1;
342 for (i
= 0; i
< nhandlers
; i
++) {
343 if (ihandlers
[i
].fd
>= FD_SETSIZE
)
344 dolog(LOG_ERR
, 0, "descriptor too big");
345 FD_SET(ihandlers
[i
].fd
, &readers
);
346 if (ihandlers
[i
].fd
>= nfds
)
347 nfds
= ihandlers
[i
].fd
+ 1;
352 IF_DEBUG(DEBUG_ROUTE
)
355 /* schedule first timer interrupt */
356 timer_setTimer(1, fasttimer
, NULL
);
357 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
361 * Detach from the terminal
373 #if defined(SYSV) || defined(linux)
377 t
= open(_PATH_TTY
, 2);
379 ioctl(t
, TIOCNOTTY
, NULL
);
389 fp
= fopen(pidfilename
, "w");
391 fprintf(fp
, "%d\n", (int)getpid());
396 * This will cause black holes for the first few seconds after startup,
397 * since we are exchanging routes but not actually forwarding.
398 * However, it eliminates much of the startup transient.
400 * It's possible that we can set a flag which says not to report any
401 * routes (just accept reports) until this timer fires, and then
402 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
405 timer_setTimer(10, final_init
, NULL
);
411 difftime
.tv_usec
= 0;
412 gettimeofday(&curtime
, NULL
);
415 bcopy((char *)&readers
, (char *)&rfds
, sizeof(rfds
));
416 secs
= timer_nextTimer();
421 timeout
->tv_sec
= secs
;
422 timeout
->tv_usec
= 0;
425 #error "THIS IS BROKEN"
426 if (nvp
->tv_sec
> svp
->tv_sec
427 || (nvp
->tv_sec
== svp
->tv_sec
&& nvp
->tv_usec
> svp
->tv_usec
)){
430 if (nvp
->tv_usec
< 500000L){
431 svp
->tv_usec
= nvp
->tv_usec
+ 500000L;
432 svp
->tv_sec
= nvp
->tv_sec
;
434 svp
->tv_usec
= nvp
->tv_usec
- 500000L;
435 svp
->tv_sec
= nvp
->tv_sec
+ 1;
441 tvp
->tv_usec
= 500000L;
444 snmp_select_info(&nfds
, &rfds
, tvp
, &block
);
446 tvp
= NULL
; /* block without timeout */
447 if ((n
= select(nfds
, &rfds
, NULL
, NULL
, tvp
)) < 0)
450 if (sighandled
& GOT_SIGINT
) {
451 sighandled
&= ~GOT_SIGINT
;
454 if (sighandled
& GOT_SIGHUP
) {
455 sighandled
&= ~GOT_SIGHUP
;
458 if (sighandled
& GOT_SIGUSR1
) {
459 sighandled
&= ~GOT_SIGUSR1
;
462 if (sighandled
& GOT_SIGUSR2
) {
463 sighandled
&= ~GOT_SIGUSR2
;
467 if ((n
= select(nfds
, &rfds
, NULL
, NULL
, timeout
)) < 0) {
469 dolog(LOG_WARNING
, errno
, "select failed");
474 if (FD_ISSET(igmp_socket
, &rfds
)) {
475 recvlen
= recvfrom(igmp_socket
, recv_buf
, RECV_BUF_SIZE
,
478 if (errno
!= EINTR
) dolog(LOG_ERR
, errno
, "recvfrom");
481 accept_igmp(recvlen
);
484 for (i
= 0; i
< nhandlers
; i
++) {
485 if (FD_ISSET(ihandlers
[i
].fd
, &rfds
)) {
486 (*ihandlers
[i
].func
)(ihandlers
[i
].fd
, &rfds
);
492 #error "THIS IS BROKEN"
494 snmp_timeout(); /* poll */
497 * Handle timeout queue.
499 * If select + packet processing took more than 1 second,
500 * or if there is a timeout pending, age the timeout queue.
502 * If not, collect usec in difftime to make sure that the
503 * time doesn't drift too badly.
505 * If the timeout handlers took more than 1 second,
506 * age the timeout queue again. XXX This introduces the
507 * potential for infinite loops!
511 * If the select timed out, then there's no other
512 * activity to account for and we don't need to
516 curtime
.tv_sec
= lasttime
.tv_sec
+ secs
;
517 curtime
.tv_usec
= lasttime
.tv_usec
;
518 n
= -1; /* don't do this next time through the loop */
520 gettimeofday(&curtime
, NULL
);
521 difftime
.tv_sec
= curtime
.tv_sec
- lasttime
.tv_sec
;
522 difftime
.tv_usec
+= curtime
.tv_usec
- lasttime
.tv_usec
;
523 while (difftime
.tv_usec
>= 1000000) {
525 difftime
.tv_usec
-= 1000000;
527 if (difftime
.tv_usec
< 0) {
529 difftime
.tv_usec
+= 1000000;
532 if (secs
== 0 || difftime
.tv_sec
> 0)
533 age_callout_queue(difftime
.tv_sec
);
535 } while (difftime
.tv_sec
> 0);
537 dolog(LOG_NOTICE
, 0, "%s exiting", versionstring
);
546 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
555 dolog(LOG_NOTICE
, 0, "%s%s", versionstring
, s
? s
: "");
559 k_init_dvmrp(); /* enable DVMRP routing in kernel */
562 * Install the vifs in the kernel as late as possible in the
563 * initialization sequence.
567 time(&mrouted_init_time
);
572 * routine invoked every second. Its main goal is to cycle through
573 * the routing table and send partial updates to all neighbors at a
574 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
575 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
576 * do all the other time-based processing.
581 static unsigned int tlast
;
582 static unsigned int nsent
;
583 unsigned int t
= tlast
+ 1;
587 * if we're in the last second, send everything that's left.
588 * otherwise send at least the fraction we should have sent by now.
590 if (t
>= ROUTE_REPORT_INTERVAL
) {
591 int nleft
= nroutes
- nsent
;
593 if ((n
= report_next_chunk()) <= 0)
600 unsigned int ncum
= nroutes
* t
/ ROUTE_REPORT_INTERVAL
;
601 while (nsent
< ncum
) {
602 if ((n
= report_next_chunk()) <= 0)
609 timer_setTimer(1, fasttimer
, NULL
);
613 * The 'virtual_time' variable is initialized to a value that will cause the
614 * first invocation of timer() to send a probe or route report to all vifs
615 * and send group membership queries to all subnets for which this router is
616 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
617 * after the router starts up. Note that probes for neighbors and queries
618 * for group memberships are also sent at start-up time, as part of initial-
619 * ization. This repetition after a short interval is desirable for quickly
620 * building up topology and membership information in the presence of possible
623 * 'virtual_time' advances at a rate that is only a crude approximation of
624 * real time, because it does not take into account any time spent processing,
625 * and because the timer intervals are sometimes shrunk by a random amount to
626 * avoid unwanted synchronization with other routers.
629 u_long virtual_time
= 0;
633 * Timer routine. Performs periodic neighbor probing, route reporting, and
634 * group querying duties, and drives various timers in routing entries and
635 * virtual interface data structures.
640 age_routes(); /* Advance the timers in the route entries */
641 age_vifs(); /* Advance the timers for neighbors */
642 age_table_entry(); /* Advance the timers for the cache entries */
644 if (virtual_time
% IGMP_QUERY_INTERVAL
== 0) {
646 * Time to query the local group memberships on all subnets
647 * for which this router is the elected querier.
652 if (virtual_time
% NEIGHBOR_PROBE_INTERVAL
== 0) {
654 * Time to send a probe on all vifs from which no neighbors have
655 * been heard. Also, check if any inoperative interfaces have now
656 * come up. (If they have, they will also be probed as part of
657 * their initialization.)
659 probe_for_neighbors();
665 delay_change_reports
= FALSE
;
666 if (routes_changed
) {
668 * Some routes have changed since the last timer interrupt, but
669 * have not been reported yet. Report the changed routes to all
672 report_to_all_neighbors(CHANGED_ROUTES
);
680 * Advance virtual time
682 virtual_time
+= TIMER_INTERVAL
;
683 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
690 static int in_cleanup
= 0;
698 report_to_all_neighbors(ALL_ROUTES
);
705 * Signal handler. Take note of the fact that the signal arrived
706 * so that the main loop can take care of it.
714 sighandled
|= GOT_SIGINT
;
718 sighandled
|= GOT_SIGHUP
;
722 sighandled
|= GOT_SIGUSR1
;
726 sighandled
|= GOT_SIGUSR2
;
732 dump_version(FILE *fp
)
737 fprintf(fp
, "%s ", versionstring
);
740 scaletime(t
- mrouted_init_time
));
742 fprintf(fp
, "(not yet initialized)");
743 fprintf(fp
, " %s\n", ctime(&t
));
747 * Dump internal data structures to a file.
754 fp
= fopen(dumpfilename
, "w");
765 * Dump local cache contents to a file.
772 fp
= fopen(cachefilename
, "w");
789 s
= (char *)malloc(sizeof(" restart"));
791 dolog(LOG_ERR
, 0, "out of memory");
792 strcpy(s
, " restart");
795 * reset all the entries
807 * start processing again
815 /*XXX Schedule final_init() as main does? */
818 /* schedule timer interrupts */
819 timer_setTimer(1, fasttimer
, NULL
);
820 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
823 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
824 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
825 static int log_nmsgs
= 0;
828 resetlogging(void *arg
)
833 if (arg
== NULL
&& log_nmsgs
> LOG_MAX_MSGS
) {
834 nxttime
= LOG_SHUT_UP
;
835 narg
= (void *)&log_nmsgs
; /* just need some valid void * */
836 syslog(LOG_WARNING
, "logging too fast, shutting up for %d minutes",
842 timer_setTimer(nxttime
, resetlogging
, narg
);
848 #define SCALETIMEBUFLEN 20
849 static char buf1
[20];
850 static char buf2
[20];
851 static char *buf
= buf1
;
861 sprintf(p
, "%2ld:%02ld:%02ld", t
/ 3600, (t
% 3600) / 60, t
% 60);
862 p
[SCALETIMEBUFLEN
- 1] = '\0';
867 #define NLOGMSGS 10000
868 #define LOGMSGSIZE 200
869 char *logmsg
[NLOGMSGS
];
870 static int logmsgno
= 0;
878 f
= fopen("/var/tmp/mrouted.log", "a");
880 dolog(LOG_ERR
, errno
, "can't open /var/tmp/mrouted.log");
883 fprintf(f
, "--------------------------------------------\n");
885 i
= (logmsgno
+ 1) % NLOGMSGS
;
887 while (i
!= logmsgno
) {
889 fprintf(f
, "%s\n", logmsg
[i
]);
892 i
= (i
+ 1) % NLOGMSGS
;
900 * Log errors and other messages to the system log daemon and to stderr,
901 * according to the severity of the message and the current debug level.
902 * For errors of severity LOG_ERR or worse, terminate the program.
906 dolog(int severity
, int syserr
, char *format
, ...)
909 static char fmt
[211] = "warning - ";
915 static int ringbufinit
= 0;
918 va_start(ap
, format
);
919 vsnprintf(&fmt
[10], sizeof(fmt
) - 10, format
, ap
);
921 msg
= (severity
== LOG_WARNING
) ? fmt
: &fmt
[10];
927 for (i
= 0; i
< NLOGMSGS
; i
++) {
928 logmsg
[i
] = malloc(LOGMSGSIZE
);
929 if (logmsg
[i
] == NULL
) {
930 syslog(LOG_ERR
, "out of memory");
937 gettimeofday(&now
,NULL
);
938 now_sec
= now
.tv_sec
;
939 thyme
= localtime(&now_sec
);
940 snprintf(logmsg
[logmsgno
++], LOGMSGSIZE
, "%02d:%02d:%02d.%03ld %s err %d",
941 thyme
->tm_hour
, thyme
->tm_min
, thyme
->tm_sec
,
942 now
.tv_usec
/ 1000, msg
, syserr
);
943 logmsgno
%= NLOGMSGS
;
944 if (severity
<= LOG_NOTICE
)
947 * Log to stderr if we haven't forked yet and it's a warning or worse,
948 * or if we're debugging.
950 if (haveterminal
&& (debug
|| severity
<= LOG_WARNING
)) {
951 gettimeofday(&now
,NULL
);
952 now_sec
= now
.tv_sec
;
953 thyme
= localtime(&now_sec
);
955 fprintf(stderr
, "%s: ", progname
);
956 fprintf(stderr
, "%02d:%02d:%02d.%03ld %s", thyme
->tm_hour
,
957 thyme
->tm_min
, thyme
->tm_sec
, now
.tv_usec
/ 1000, msg
);
959 fprintf(stderr
, "\n");
960 else if (syserr
< sys_nerr
)
961 fprintf(stderr
, ": %s\n", sys_errlist
[syserr
]);
963 fprintf(stderr
, ": errno %d\n", syserr
);
967 * Always log things that are worse than warnings, no matter what
968 * the log_nmsgs rate limiter says.
969 * Only count things worse than debugging in the rate limiter
970 * (since if you put daemon.debug in syslog.conf you probably
971 * actually want to log the debugging messages so they shouldn't
974 if ((severity
< LOG_WARNING
) || (log_nmsgs
< LOG_MAX_MSGS
)) {
975 if (severity
< LOG_DEBUG
)
979 syslog(severity
, "%s: %m", msg
);
981 syslog(severity
, "%s", msg
);
984 if (severity
<= LOG_ERR
) exit(-1);
989 md_log(int what
, u_int32 origin
, u_int32 mcastgrp
)
991 static FILE *f
= NULL
;
996 if ((f
= fopen("/tmp/mrouted.clog", "w")) == NULL
) {
997 dolog(LOG_ERR
, errno
, "open /tmp/mrouted.clog");
1001 gettimeofday(&tv
, NULL
);
1007 fwrite(buf
, sizeof(u_int32
), 4, f
);