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.5 2004/12/18 22:48:04 swildner 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(void *);
110 static void fasttimer(void *);
111 static void timer(void *);
112 static void dump(void);
113 static void dump_version(FILE *);
114 static void fdump(void);
115 static void cdump(void);
116 static void restart(void);
117 static void handler(int);
118 static void cleanup(void);
119 static void resetlogging(void *);
120 static void usage(void);
122 /* To shut up gcc -Wstrict-prototypes */
123 int main(int argc
, char **argv
);
126 register_input_handler(int fd
, ihfunc_t func
)
128 if (nhandlers
>= NHANDLERS
)
131 ihandlers
[nhandlers
].fd
= fd
;
132 ihandlers
[nhandlers
++].func
= func
;
138 main(int argc
, char **argv
)
143 struct timeval tv
, difftime
, curtime
, lasttime
, *timeout
;
146 fd_set rfds
, readers
;
147 int nfds
, n
, i
, secs
;
148 extern char todaysversion
[];
151 struct timeval timeout
, *tvp
= &timeout
;
152 struct timeval sched
, *svp
= &sched
, now
, *nvp
= &now
;
159 errx(1, "must be root");
161 progname
= strrchr(argv
[0], '/');
168 while (argc
> 0 && *argv
[0] == '-') {
169 if (strcmp(*argv
, "-d") == 0) {
170 if (argc
> 1 && *(argv
+ 1)[0] != '-') {
183 for (i
= 0, d
= debugnames
;
184 i
< sizeof(debugnames
) / sizeof(debugnames
[0]);
186 if (len
>= d
->nchars
&& strncmp(d
->name
, p
, len
) == 0)
188 if (i
== sizeof(debugnames
) / sizeof(debugnames
[0])) {
191 fprintf(stderr
, "Valid debug levels: ");
192 for (i
= 0, d
= debugnames
;
193 i
< sizeof(debugnames
) / sizeof(debugnames
[0]);
195 if ((j
& d
->level
) == d
->level
) {
198 fputs(d
->name
, stderr
);
209 debug
= DEFAULT_DEBUG
;
210 } else if (strcmp(*argv
, "-c") == 0) {
213 configfilename
= *argv
;
216 } else if (strcmp(*argv
, "-p") == 0) {
217 log(LOG_WARNING
, 0, "disabling pruning is no longer supported");
219 } else if (strcmp(*argv
, "-P") == 0) {
220 if (argc
> 1 && isdigit(*(argv
+ 1)[0])) {
222 dest_port
= atoi(*argv
);
224 dest_port
= DEFAULT_PORT
;
239 fprintf(stderr
, "debug level 0x%x ", debug
);
241 for (d
= debugnames
; d
< debugnames
+
242 sizeof(debugnames
) / sizeof(debugnames
[0]); d
++) {
243 if ((tmpd
& d
->level
) == d
->level
) {
245 fprintf(stderr
, "%c%s", c
, d
->name
);
249 fprintf(stderr
, ")\n");
253 openlog("mrouted", LOG_PID
, LOG_DAEMON
);
254 setlogmask(LOG_UPTO(LOG_NOTICE
));
256 openlog("mrouted", LOG_PID
);
258 sprintf(versionstring
, "mrouted version %s", todaysversion
);
260 log(LOG_DEBUG
, 0, "%s starting", versionstring
);
269 gettimeofday(&tv
, 0);
270 dvmrp_genid
= tv
.tv_sec
;
272 fp
= fopen(genidfilename
, "r");
274 fscanf(fp
, "%d", &prev_genid
);
275 if (prev_genid
== dvmrp_genid
)
280 fp
= fopen(genidfilename
, "w");
282 fprintf(fp
, "%d", dvmrp_genid
);
286 /* Start up the log rate-limiter */
297 * Unfortunately, you can't k_get_version() unless you've
298 * k_init_dvmrp()'d. Now that we want to move the
299 * k_init_dvmrp() to later in the initialization sequence,
300 * we have to do the disgusting hack of initializing,
301 * getting the version, then stopping the kernel multicast
305 vers
= k_get_version();
308 * This function must change whenever the kernel version changes
310 if ((((vers
>> 8) & 0xff) != 3) ||
311 ((vers
& 0xff) != 5))
312 log(LOG_ERR
, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
313 (vers
>> 8) & 0xff, vers
& 0xff,
314 PROTOCOL_VERSION
, MROUTED_VERSION
);
321 gettimeofday(nvp
, 0);
322 if (nvp
->tv_usec
< 500000L){
323 svp
->tv_usec
= nvp
->tv_usec
+ 500000L;
324 svp
->tv_sec
= nvp
->tv_sec
;
326 svp
->tv_usec
= nvp
->tv_usec
- 500000L;
327 svp
->tv_sec
= nvp
->tv_sec
+ 1;
337 sa
.sa_handler
= handler
;
338 sa
.sa_flags
= 0; /* Interrupt system calls */
339 sigemptyset(&sa
.sa_mask
);
340 sigaction(SIGHUP
, &sa
, NULL
);
341 sigaction(SIGTERM
, &sa
, NULL
);
342 sigaction(SIGINT
, &sa
, NULL
);
343 sigaction(SIGUSR1
, &sa
, NULL
);
344 sigaction(SIGUSR2
, &sa
, NULL
);
346 if (igmp_socket
>= FD_SETSIZE
)
347 log(LOG_ERR
, 0, "descriptor too big");
349 FD_SET(igmp_socket
, &readers
);
350 nfds
= igmp_socket
+ 1;
351 for (i
= 0; i
< nhandlers
; i
++) {
352 if (ihandlers
[i
].fd
>= FD_SETSIZE
)
353 log(LOG_ERR
, 0, "descriptor too big");
354 FD_SET(ihandlers
[i
].fd
, &readers
);
355 if (ihandlers
[i
].fd
>= nfds
)
356 nfds
= ihandlers
[i
].fd
+ 1;
361 IF_DEBUG(DEBUG_ROUTE
)
364 /* schedule first timer interrupt */
365 timer_setTimer(1, fasttimer
, NULL
);
366 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
370 * Detach from the terminal
382 #if defined(SYSV) || defined(linux)
386 t
= open(_PATH_TTY
, 2);
388 ioctl(t
, TIOCNOTTY
, (char *)0);
398 fp
= fopen(pidfilename
, "w");
400 fprintf(fp
, "%d\n", (int)getpid());
405 * This will cause black holes for the first few seconds after startup,
406 * since we are exchanging routes but not actually forwarding.
407 * However, it eliminates much of the startup transient.
409 * It's possible that we can set a flag which says not to report any
410 * routes (just accept reports) until this timer fires, and then
411 * do a report_to_all_neighbors(ALL_ROUTES) immediately before
414 timer_setTimer(10, final_init
, NULL
);
420 difftime
.tv_usec
= 0;
421 gettimeofday(&curtime
, NULL
);
424 bcopy((char *)&readers
, (char *)&rfds
, sizeof(rfds
));
425 secs
= timer_nextTimer();
430 timeout
->tv_sec
= secs
;
431 timeout
->tv_usec
= 0;
434 #error "THIS IS BROKEN"
435 if (nvp
->tv_sec
> svp
->tv_sec
436 || (nvp
->tv_sec
== svp
->tv_sec
&& nvp
->tv_usec
> svp
->tv_usec
)){
439 if (nvp
->tv_usec
< 500000L){
440 svp
->tv_usec
= nvp
->tv_usec
+ 500000L;
441 svp
->tv_sec
= nvp
->tv_sec
;
443 svp
->tv_usec
= nvp
->tv_usec
- 500000L;
444 svp
->tv_sec
= nvp
->tv_sec
+ 1;
450 tvp
->tv_usec
= 500000L;
453 snmp_select_info(&nfds
, &rfds
, tvp
, &block
);
455 tvp
= NULL
; /* block without timeout */
456 if ((n
= select(nfds
, &rfds
, NULL
, NULL
, tvp
)) < 0)
459 if (sighandled
& GOT_SIGINT
) {
460 sighandled
&= ~GOT_SIGINT
;
463 if (sighandled
& GOT_SIGHUP
) {
464 sighandled
&= ~GOT_SIGHUP
;
467 if (sighandled
& GOT_SIGUSR1
) {
468 sighandled
&= ~GOT_SIGUSR1
;
471 if (sighandled
& GOT_SIGUSR2
) {
472 sighandled
&= ~GOT_SIGUSR2
;
476 if ((n
= select(nfds
, &rfds
, NULL
, NULL
, timeout
)) < 0) {
478 log(LOG_WARNING
, errno
, "select failed");
483 if (FD_ISSET(igmp_socket
, &rfds
)) {
484 recvlen
= recvfrom(igmp_socket
, recv_buf
, RECV_BUF_SIZE
,
487 if (errno
!= EINTR
) log(LOG_ERR
, errno
, "recvfrom");
490 accept_igmp(recvlen
);
493 for (i
= 0; i
< nhandlers
; i
++) {
494 if (FD_ISSET(ihandlers
[i
].fd
, &rfds
)) {
495 (*ihandlers
[i
].func
)(ihandlers
[i
].fd
, &rfds
);
501 #error "THIS IS BROKEN"
503 snmp_timeout(); /* poll */
506 * Handle timeout queue.
508 * If select + packet processing took more than 1 second,
509 * or if there is a timeout pending, age the timeout queue.
511 * If not, collect usec in difftime to make sure that the
512 * time doesn't drift too badly.
514 * If the timeout handlers took more than 1 second,
515 * age the timeout queue again. XXX This introduces the
516 * potential for infinite loops!
520 * If the select timed out, then there's no other
521 * activity to account for and we don't need to
525 curtime
.tv_sec
= lasttime
.tv_sec
+ secs
;
526 curtime
.tv_usec
= lasttime
.tv_usec
;
527 n
= -1; /* don't do this next time through the loop */
529 gettimeofday(&curtime
, NULL
);
530 difftime
.tv_sec
= curtime
.tv_sec
- lasttime
.tv_sec
;
531 difftime
.tv_usec
+= curtime
.tv_usec
- lasttime
.tv_usec
;
532 while (difftime
.tv_usec
>= 1000000) {
534 difftime
.tv_usec
-= 1000000;
536 if (difftime
.tv_usec
< 0) {
538 difftime
.tv_usec
+= 1000000;
541 if (secs
== 0 || difftime
.tv_sec
> 0)
542 age_callout_queue(difftime
.tv_sec
);
544 } while (difftime
.tv_sec
> 0);
546 log(LOG_NOTICE
, 0, "%s exiting", versionstring
);
555 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
564 log(LOG_NOTICE
, 0, "%s%s", versionstring
, s
? s
: "");
568 k_init_dvmrp(); /* enable DVMRP routing in kernel */
571 * Install the vifs in the kernel as late as possible in the
572 * initialization sequence.
576 time(&mrouted_init_time
);
581 * routine invoked every second. Its main goal is to cycle through
582 * the routing table and send partial updates to all neighbors at a
583 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
584 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
585 * do all the other time-based processing.
590 static unsigned int tlast
;
591 static unsigned int nsent
;
592 unsigned int t
= tlast
+ 1;
596 * if we're in the last second, send everything that's left.
597 * otherwise send at least the fraction we should have sent by now.
599 if (t
>= ROUTE_REPORT_INTERVAL
) {
600 int nleft
= nroutes
- nsent
;
602 if ((n
= report_next_chunk()) <= 0)
609 unsigned int ncum
= nroutes
* t
/ ROUTE_REPORT_INTERVAL
;
610 while (nsent
< ncum
) {
611 if ((n
= report_next_chunk()) <= 0)
618 timer_setTimer(1, fasttimer
, NULL
);
622 * The 'virtual_time' variable is initialized to a value that will cause the
623 * first invocation of timer() to send a probe or route report to all vifs
624 * and send group membership queries to all subnets for which this router is
625 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
626 * after the router starts up. Note that probes for neighbors and queries
627 * for group memberships are also sent at start-up time, as part of initial-
628 * ization. This repetition after a short interval is desirable for quickly
629 * building up topology and membership information in the presence of possible
632 * 'virtual_time' advances at a rate that is only a crude approximation of
633 * real time, because it does not take into account any time spent processing,
634 * and because the timer intervals are sometimes shrunk by a random amount to
635 * avoid unwanted synchronization with other routers.
638 u_long virtual_time
= 0;
642 * Timer routine. Performs periodic neighbor probing, route reporting, and
643 * group querying duties, and drives various timers in routing entries and
644 * virtual interface data structures.
649 age_routes(); /* Advance the timers in the route entries */
650 age_vifs(); /* Advance the timers for neighbors */
651 age_table_entry(); /* Advance the timers for the cache entries */
653 if (virtual_time
% IGMP_QUERY_INTERVAL
== 0) {
655 * Time to query the local group memberships on all subnets
656 * for which this router is the elected querier.
661 if (virtual_time
% NEIGHBOR_PROBE_INTERVAL
== 0) {
663 * Time to send a probe on all vifs from which no neighbors have
664 * been heard. Also, check if any inoperative interfaces have now
665 * come up. (If they have, they will also be probed as part of
666 * their initialization.)
668 probe_for_neighbors();
674 delay_change_reports
= FALSE
;
675 if (routes_changed
) {
677 * Some routes have changed since the last timer interrupt, but
678 * have not been reported yet. Report the changed routes to all
681 report_to_all_neighbors(CHANGED_ROUTES
);
689 * Advance virtual time
691 virtual_time
+= TIMER_INTERVAL
;
692 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
699 static in_cleanup
= 0;
707 report_to_all_neighbors(ALL_ROUTES
);
714 * Signal handler. Take note of the fact that the signal arrived
715 * so that the main loop can take care of it.
723 sighandled
|= GOT_SIGINT
;
727 sighandled
|= GOT_SIGHUP
;
731 sighandled
|= GOT_SIGUSR1
;
735 sighandled
|= GOT_SIGUSR2
;
741 * Dump internal data structures to stderr.
751 dump_version(FILE *fp
)
756 fprintf(fp
, "%s ", versionstring
);
759 scaletime(t
- mrouted_init_time
));
761 fprintf(fp
, "(not yet initialized)");
762 fprintf(fp
, " %s\n", ctime(&t
));
766 * Dump internal data structures to a file.
773 fp
= fopen(dumpfilename
, "w");
784 * Dump local cache contents to a file.
791 fp
= fopen(cachefilename
, "w");
808 s
= (char *)malloc(sizeof(" restart"));
810 log(LOG_ERR
, 0, "out of memory");
811 strcpy(s
, " restart");
814 * reset all the entries
826 * start processing again
834 /*XXX Schedule final_init() as main does? */
837 /* schedule timer interrupts */
838 timer_setTimer(1, fasttimer
, NULL
);
839 timer_setTimer(TIMER_INTERVAL
, timer
, NULL
);
842 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
843 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
844 static int log_nmsgs
= 0;
847 resetlogging(void *arg
)
852 if (arg
== NULL
&& log_nmsgs
> LOG_MAX_MSGS
) {
853 nxttime
= LOG_SHUT_UP
;
854 narg
= (void *)&log_nmsgs
; /* just need some valid void * */
855 syslog(LOG_WARNING
, "logging too fast, shutting up for %d minutes",
861 timer_setTimer(nxttime
, resetlogging
, narg
);
867 #define SCALETIMEBUFLEN 20
868 static char buf1
[20];
869 static char buf2
[20];
870 static char *buf
= buf1
;
880 sprintf(p
, "%2ld:%02ld:%02ld", t
/ 3600, (t
% 3600) / 60, t
% 60);
881 p
[SCALETIMEBUFLEN
- 1] = '\0';
886 #define NLOGMSGS 10000
887 #define LOGMSGSIZE 200
888 char *logmsg
[NLOGMSGS
];
889 static int logmsgno
= 0;
897 f
= fopen("/var/tmp/mrouted.log", "a");
899 log(LOG_ERR
, errno
, "can't open /var/tmp/mrouted.log");
902 fprintf(f
, "--------------------------------------------\n");
904 i
= (logmsgno
+ 1) % NLOGMSGS
;
906 while (i
!= logmsgno
) {
908 fprintf(f
, "%s\n", logmsg
[i
]);
911 i
= (i
+ 1) % NLOGMSGS
;
919 * Log errors and other messages to the system log daemon and to stderr,
920 * according to the severity of the message and the current debug level.
921 * For errors of severity LOG_ERR or worse, terminate the program.
925 log(int severity
, int syserr
, char *format
, ...)
928 static char fmt
[211] = "warning - ";
934 static int ringbufinit
= 0;
937 va_start(ap
, format
);
938 vsnprintf(&fmt
[10], sizeof(fmt
) - 10, format
, ap
);
940 msg
= (severity
== LOG_WARNING
) ? fmt
: &fmt
[10];
946 for (i
= 0; i
< NLOGMSGS
; i
++) {
947 logmsg
[i
] = malloc(LOGMSGSIZE
);
948 if (logmsg
[i
] == 0) {
949 syslog(LOG_ERR
, "out of memory");
956 gettimeofday(&now
,NULL
);
957 now_sec
= now
.tv_sec
;
958 thyme
= localtime(&now_sec
);
959 snprintf(logmsg
[logmsgno
++], LOGMSGSIZE
, "%02d:%02d:%02d.%03ld %s err %d",
960 thyme
->tm_hour
, thyme
->tm_min
, thyme
->tm_sec
,
961 now
.tv_usec
/ 1000, msg
, syserr
);
962 logmsgno
%= NLOGMSGS
;
963 if (severity
<= LOG_NOTICE
)
966 * Log to stderr if we haven't forked yet and it's a warning or worse,
967 * or if we're debugging.
969 if (haveterminal
&& (debug
|| severity
<= LOG_WARNING
)) {
970 gettimeofday(&now
,NULL
);
971 now_sec
= now
.tv_sec
;
972 thyme
= localtime(&now_sec
);
974 fprintf(stderr
, "%s: ", progname
);
975 fprintf(stderr
, "%02d:%02d:%02d.%03ld %s", thyme
->tm_hour
,
976 thyme
->tm_min
, thyme
->tm_sec
, now
.tv_usec
/ 1000, msg
);
978 fprintf(stderr
, "\n");
979 else if (syserr
< sys_nerr
)
980 fprintf(stderr
, ": %s\n", sys_errlist
[syserr
]);
982 fprintf(stderr
, ": errno %d\n", syserr
);
986 * Always log things that are worse than warnings, no matter what
987 * the log_nmsgs rate limiter says.
988 * Only count things worse than debugging in the rate limiter
989 * (since if you put daemon.debug in syslog.conf you probably
990 * actually want to log the debugging messages so they shouldn't
993 if ((severity
< LOG_WARNING
) || (log_nmsgs
< LOG_MAX_MSGS
)) {
994 if (severity
< LOG_DEBUG
)
998 syslog(severity
, "%s: %m", msg
);
1000 syslog(severity
, "%s", msg
);
1003 if (severity
<= LOG_ERR
) exit(-1);
1008 md_log(int what
, u_int32 origin
, u_int32 mcastgrp
)
1010 static FILE *f
= NULL
;
1015 if ((f
= fopen("/tmp/mrouted.clog", "w")) == NULL
) {
1016 log(LOG_ERR
, errno
, "open /tmp/mrouted.clog");
1020 gettimeofday(&tv
, NULL
);
1026 fwrite(buf
, sizeof(u_int32
), 4, f
);