xref: /openbsd-src/usr.sbin/mrouted/main.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$NetBSD: main.c,v 1.6 1995/12/10 10:07:05 mycroft Exp $	*/
2 
3 /*
4  * The mrouted program is covered by the license in the accompanying file
5  * named "LICENSE".  Use of the mrouted program represents acceptance of
6  * the terms and conditions listed in that file.
7  *
8  * The mrouted program is COPYRIGHT 1989 by The Board of Trustees of
9  * Leland Stanford Junior University.
10  */
11 
12 /*
13  * Written by Steve Deering, Stanford University, February 1989.
14  *
15  * (An earlier version of DVMRP was implemented by David Waitzman of
16  *  BBN STC by extending Berkeley's routed program.  Some of Waitzman's
17  *  extensions have been incorporated into mrouted, but none of the
18  *  original routed code has been adopted.)
19  */
20 
21 
22 #include "defs.h"
23 #ifdef __STDC__
24 #include <stdarg.h>
25 #else
26 #include <varargs.h>
27 #endif
28 #include <fcntl.h>
29 
30 #ifdef SNMP
31 #include "snmp.h"
32 #endif
33 
34 #ifndef lint
35 static char rcsid[] =
36 	"@(#) $Id: main.c,v 1.5 2001/03/09 03:24:07 deraadt Exp $";
37 #endif
38 
39 extern char *configfilename;
40 char versionstring[100];
41 
42 static char pidfilename[]  = _PATH_MROUTED_PID;
43 static char dumpfilename[] = _PATH_MROUTED_DUMP;
44 static char cachefilename[] = _PATH_MROUTED_CACHE;
45 static char genidfilename[] = _PATH_MROUTED_GENID;
46 
47 int cache_lifetime 	= DEFAULT_CACHE_LIFETIME;
48 int max_prune_lifetime 	= DEFAULT_CACHE_LIFETIME * 2;
49 
50 int debug = 0;
51 u_char pruning = 1;	/* Enable pruning by default */
52 
53 #ifdef SNMP
54 #define NHANDLERS	34
55 #else
56 #define NHANDLERS	2
57 #endif
58 
59 static struct ihandler {
60     int fd;			/* File descriptor		 */
61     ihfunc_t func;		/* Function to call with &fd_set */
62 } ihandlers[NHANDLERS];
63 static int nhandlers = 0;
64 
65 /*
66  * Forward declarations.
67  */
68 static void fasttimer __P((int));
69 static void done __P((int));
70 static void dump __P((int));
71 static void fdump __P((int));
72 static void cdump __P((int));
73 static void restart __P((int));
74 static void timer __P((void));
75 static void cleanup __P((void));
76 static void resetlogging __P((void *));
77 
78 /* To shut up gcc -Wstrict-prototypes */
79 int main __P((int argc, char **argv));
80 
81 int
82 register_input_handler(fd, func)
83     int fd;
84     ihfunc_t func;
85 {
86     if (nhandlers >= NHANDLERS)
87 	return -1;
88 
89     ihandlers[nhandlers].fd = fd;
90     ihandlers[nhandlers++].func = func;
91 
92     return 0;
93 }
94 
95 int
96 main(argc, argv)
97     int argc;
98     char *argv[];
99 {
100     register int recvlen;
101     register int omask;
102     int dummy;
103     FILE *fp;
104     struct timeval tv;
105     u_int32_t prev_genid;
106     int vers;
107     fd_set rfds, readers;
108     int nfds, n, i;
109 #ifdef SNMP
110     struct timeval  timeout, *tvp = &timeout;
111     struct timeval  sched, *svp = &sched, now, *nvp = &now;
112     int index, block;
113 #endif
114 
115     if (geteuid() != 0) {
116 	fprintf(stderr, "must be root\n");
117 	exit(1);
118     }
119     setlinebuf(stderr);
120 
121     argv++, argc--;
122     while (argc > 0 && *argv[0] == '-') {
123 	if (strcmp(*argv, "-d") == 0) {
124 	    if (argc > 1 && isdigit(*(argv + 1)[0])) {
125 		argv++, argc--;
126 		debug = atoi(*argv);
127 	    } else
128 		debug = DEFAULT_DEBUG;
129 	} else if (strcmp(*argv, "-c") == 0) {
130 	    if (argc > 1) {
131 		argv++, argc--;
132 		configfilename = *argv;
133 	    } else
134 		goto usage;
135 	} else if (strcmp(*argv, "-p") == 0) {
136 	    pruning = 0;
137 #ifdef SNMP
138    } else if (strcmp(*argv, "-P") == 0) {
139 	    if (argc > 1 && isdigit(*(argv + 1)[0])) {
140 		argv++, argc--;
141 		dest_port = atoi(*argv);
142 	    } else
143 		dest_port = DEFAULT_PORT;
144 #endif
145 	} else
146 	    goto usage;
147 	argv++, argc--;
148     }
149 
150     if (argc > 0) {
151 usage:	fprintf(stderr,
152 		"usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
153 	exit(1);
154     }
155 
156     if (debug == 0) {
157 	/*
158 	 * Detach from the terminal
159 	 */
160 	int t;
161 
162 	if (fork()) exit(0);
163 	(void)close(0);
164 	(void)close(1);
165 	(void)close(2);
166 	(void)open("/", 0);
167 	(void)dup2(0, 1);
168 	(void)dup2(0, 2);
169 #ifdef SYSV
170 	(void)setpgrp();
171 #else
172 #ifdef TIOCNOTTY
173 	t = open("/dev/tty", 2);
174 	if (t >= 0) {
175 	    (void)ioctl(t, TIOCNOTTY, (char *)0);
176 	    (void)close(t);
177 	}
178 #else
179 	if (setsid() < 0)
180 	    perror("setsid");
181 #endif
182 #endif
183     }
184     else
185 	fprintf(stderr, "debug level %u\n", debug);
186 
187 #ifdef LOG_DAEMON
188     (void)openlog("mrouted", LOG_PID, LOG_DAEMON);
189     (void)setlogmask(LOG_UPTO(LOG_NOTICE));
190 #else
191     (void)openlog("mrouted", LOG_PID);
192 #endif
193     sprintf(versionstring, "mrouted version %d.%d",
194 			PROTOCOL_VERSION, MROUTED_VERSION);
195 
196     log(LOG_NOTICE, 0, "%s", versionstring);
197 
198 #ifdef SYSV
199     srand48(time(NULL));
200 #else
201     srandom(gethostid());
202 #endif
203 
204     /*
205      * Get generation id
206      */
207     gettimeofday(&tv, 0);
208     dvmrp_genid = tv.tv_sec;
209 
210     fp = fopen(genidfilename, "r");
211     if (fp != NULL) {
212 	fscanf(fp, "%d", &prev_genid);
213 	if (prev_genid == dvmrp_genid)
214 	    dvmrp_genid++;
215 	(void) fclose(fp);
216     }
217 
218     fp = fopen(genidfilename, "w");
219     if (fp != NULL) {
220 	fprintf(fp, "%d", dvmrp_genid);
221 	(void) fclose(fp);
222     }
223 
224     callout_init();
225     init_igmp();
226     init_routes();
227     init_ktable();
228     k_init_dvmrp();		/* enable DVMRP routing in kernel */
229 
230 #ifndef OLD_KERNEL
231     vers = k_get_version();
232     /*XXX
233      * This function must change whenever the kernel version changes
234      */
235     if ((((vers >> 8) & 0xff) != 3) ||
236 	 ((vers & 0xff) != 5))
237 	log(LOG_ERR, 0, "kernel (v%d.%d)/mrouted (v%d.%d) version mismatch",
238 		(vers >> 8) & 0xff, vers & 0xff,
239 		PROTOCOL_VERSION, MROUTED_VERSION);
240 #endif
241 
242 #ifdef SNMP
243     if (i = snmp_init())
244        return i;
245 
246     gettimeofday(nvp, 0);
247     if (nvp->tv_usec < 500000L){
248    svp->tv_usec = nvp->tv_usec + 500000L;
249    svp->tv_sec = nvp->tv_sec;
250     } else {
251    svp->tv_usec = nvp->tv_usec - 500000L;
252    svp->tv_sec = nvp->tv_sec + 1;
253     }
254 #endif /* SNMP */
255 
256     init_vifs();
257 
258 #ifdef RSRR
259     rsrr_init();
260 #endif /* RSRR */
261 
262 #if defined(__STDC__) || defined(__GNUC__)
263     /*
264      * Allow cleanup if unexpected exit.  Apparently some architectures
265      * have a kernel bug where closing the socket doesn't do an
266      * ip_mrouter_done(), so we attempt to do it on exit.
267      */
268     atexit(cleanup);
269 #endif
270 
271     if (debug)
272 	fprintf(stderr, "pruning %s\n", pruning ? "on" : "off");
273 
274     fp = fopen(pidfilename, "w");
275     if (fp != NULL) {
276 	fprintf(fp, "%d\n", (int)getpid());
277 	(void) fclose(fp);
278     }
279 
280     (void)signal(SIGALRM, fasttimer);
281 
282     (void)signal(SIGHUP,  restart);
283     (void)signal(SIGTERM, done);
284     (void)signal(SIGINT,  done);
285     (void)signal(SIGUSR1, fdump);
286     (void)signal(SIGUSR2, cdump);
287     if (debug != 0)
288 	(void)signal(SIGQUIT, dump);
289 
290     FD_ZERO(&readers);
291     FD_SET(igmp_socket, &readers);
292     nfds = igmp_socket + 1;
293     for (i = 0; i < nhandlers; i++) {
294 	FD_SET(ihandlers[i].fd, &readers);
295 	if (ihandlers[i].fd >= nfds)
296 	    nfds = ihandlers[i].fd + 1;
297     }
298 
299     /*
300      * Install the vifs in the kernel as late as possible in the
301      * initialization sequence.
302      */
303     init_installvifs();
304 
305     if (debug >= 2) dump(0);
306 
307     /* Start up the log rate-limiter */
308     resetlogging(NULL);
309 
310     (void)alarm(1);	 /* schedule first timer interrupt */
311 
312     /*
313      * Main receive loop.
314      */
315     dummy = 0;
316     for(;;) {
317 #ifdef SYSV
318 	sigset_t block, oblock;
319 #endif
320 	bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
321 #ifdef SNMP
322    gettimeofday(nvp, 0);
323    if (nvp->tv_sec > svp->tv_sec
324        || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
325        alarmTimer(nvp);
326        eventTimer(nvp);
327        if (nvp->tv_usec < 500000L){
328       svp->tv_usec = nvp->tv_usec + 500000L;
329       svp->tv_sec = nvp->tv_sec;
330        } else {
331       svp->tv_usec = nvp->tv_usec - 500000L;
332       svp->tv_sec = nvp->tv_sec + 1;
333        }
334    }
335 
336 	tvp =  &timeout;
337 	tvp->tv_sec = 0;
338 	tvp->tv_usec = 500000L;
339 
340 	block = 0;
341 	snmp_select_info(&nfds, &rfds, tvp, &block);
342 	if (block == 1)
343 		tvp = NULL; /* block without timeout */
344 	if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
345 #else
346 	if ((n = select(nfds, &rfds, NULL, NULL, NULL)) < 0)
347 #endif
348    {
349             if (errno != EINTR) /* SIGALRM is expected */
350                 log(LOG_WARNING, errno, "select failed");
351             continue;
352         }
353 
354 	if (FD_ISSET(igmp_socket, &rfds)) {
355 	    recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
356 			       0, NULL, &dummy);
357 	    if (recvlen < 0) {
358 		if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
359 		continue;
360 	    }
361 #ifdef SYSV
362 	    (void)sigemptyset(&block);
363 	    (void)sigaddset(&block, SIGALRM);
364 	    if (sigprocmask(SIG_BLOCK, &block, &oblock) < 0)
365 		    log(LOG_ERR, errno, "sigprocmask");
366 #else
367 	    omask = sigblock(sigmask(SIGALRM));
368 #endif
369 	    accept_igmp(recvlen);
370 #ifdef SYSV
371 	    (void)sigprocmask(SIG_SETMASK, &oblock, (sigset_t *)NULL);
372 #else
373 	    (void)sigsetmask(omask);
374 #endif
375         }
376 
377 	for (i = 0; i < nhandlers; i++) {
378 	    if (FD_ISSET(ihandlers[i].fd, &rfds)) {
379 		(*ihandlers[i].func)(ihandlers[i].fd, &rfds);
380 	    }
381 	}
382 
383 #ifdef SNMP
384 	snmp_read(&rfds);
385 	snmp_timeout(); /* poll */
386 #endif
387     }
388 }
389 
390 
391 /*
392  * routine invoked every second.  Its main goal is to cycle through
393  * the routing table and send partial updates to all neighbors at a
394  * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
395  * seconds.  Also, every TIMER_INTERVAL seconds it calls timer() to
396  * do all the other time-based processing.
397  */
398 static void
399 fasttimer(i)
400     int i;
401 {
402     static unsigned int tlast;
403     static unsigned int nsent;
404     register unsigned int t = tlast + 1;
405     register int n;
406 
407     /*
408      * if we're in the last second, send everything that's left.
409      * otherwise send at least the fraction we should have sent by now.
410      */
411     if (t >= ROUTE_REPORT_INTERVAL) {
412 	register int nleft = nroutes - nsent;
413 	while (nleft > 0) {
414 	    if ((n = report_next_chunk()) <= 0)
415 		break;
416 	    nleft -= n;
417 	}
418 	tlast = 0;
419 	nsent = 0;
420     } else {
421 	register unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
422 	while (nsent < ncum) {
423 	    if ((n = report_next_chunk()) <= 0)
424 		break;
425 	    nsent += n;
426 	}
427 	tlast = t;
428     }
429     if ((t % TIMER_INTERVAL) == 0)
430 	timer();
431 
432     age_callout_queue();/* Advance the timer for the callout queue
433 				for groups */
434     alarm(1);
435 }
436 
437 /*
438  * The 'virtual_time' variable is initialized to a value that will cause the
439  * first invocation of timer() to send a probe or route report to all vifs
440  * and send group membership queries to all subnets for which this router is
441  * querier.  This first invocation occurs approximately TIMER_INTERVAL seconds
442  * after the router starts up.   Note that probes for neighbors and queries
443  * for group memberships are also sent at start-up time, as part of initial-
444  * ization.  This repetition after a short interval is desirable for quickly
445  * building up topology and membership information in the presence of possible
446  * packet loss.
447  *
448  * 'virtual_time' advances at a rate that is only a crude approximation of
449  * real time, because it does not take into account any time spent processing,
450  * and because the timer intervals are sometimes shrunk by a random amount to
451  * avoid unwanted synchronization with other routers.
452  */
453 
454 static u_long virtual_time = 0;
455 
456 
457 /*
458  * Timer routine.  Performs periodic neighbor probing, route reporting, and
459  * group querying duties, and drives various timers in routing entries and
460  * virtual interface data structures.
461  */
462 static void
463 timer()
464 {
465     age_routes();	/* Advance the timers in the route entries     */
466     age_vifs();		/* Advance the timers for neighbors */
467     age_table_entry();	/* Advance the timers for the cache entries */
468 
469     if (virtual_time % GROUP_QUERY_INTERVAL == 0) {
470 	/*
471 	 * Time to query the local group memberships on all subnets
472 	 * for which this router is the elected querier.
473 	 */
474 	query_groups();
475     }
476 
477     if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
478 	/*
479 	 * Time to send a probe on all vifs from which no neighbors have
480 	 * been heard.  Also, check if any inoperative interfaces have now
481 	 * come up.  (If they have, they will also be probed as part of
482 	 * their initialization.)
483 	 */
484 	probe_for_neighbors();
485 
486 	if (vifs_down)
487 	    check_vif_state();
488     }
489 
490     delay_change_reports = FALSE;
491     if (routes_changed) {
492 	/*
493 	 * Some routes have changed since the last timer interrupt, but
494 	 * have not been reported yet.  Report the changed routes to all
495 	 * neighbors.
496 	 */
497 	report_to_all_neighbors(CHANGED_ROUTES);
498     }
499 
500 #ifdef SNMP
501     sync_timer();
502 #endif
503 
504     /*
505      * Advance virtual time
506      */
507     virtual_time += TIMER_INTERVAL;
508 }
509 
510 
511 /*
512  * On termination, let everyone know we're going away.
513  */
514 static void
515 done(i)
516     int i;
517 {
518     log(LOG_NOTICE, 0, "%s exiting", versionstring);
519     cleanup();
520     _exit(1);
521 }
522 
523 static void
524 cleanup()
525 {
526     static in_cleanup = 0;
527 
528     if (!in_cleanup) {
529 	in_cleanup++;
530 #ifdef RSRR
531 	rsrr_clean();
532 #endif /* RSRR */
533 	expire_all_routes();
534 	report_to_all_neighbors(ALL_ROUTES);
535 	k_stop_dvmrp();
536     }
537 }
538 
539 
540 /*
541  * Dump internal data structures to stderr.
542  */
543 static void
544 dump(i)
545     int i;
546 {
547     dump_vifs(stderr);
548     dump_routes(stderr);
549 }
550 
551 
552 /*
553  * Dump internal data structures to a file.
554  */
555 static void
556 fdump(i)
557     int i;
558 {
559     FILE *fp;
560 
561     fp = fopen(dumpfilename, "w");
562     if (fp != NULL) {
563 	dump_vifs(fp);
564 	dump_routes(fp);
565 	(void) fclose(fp);
566     }
567 }
568 
569 
570 /*
571  * Dump local cache contents to a file.
572  */
573 static void
574 cdump(i)
575     int i;
576 {
577     FILE *fp;
578 
579     fp = fopen(cachefilename, "w");
580     if (fp != NULL) {
581 	dump_cache(fp);
582 	(void) fclose(fp);
583     }
584 }
585 
586 
587 /*
588  * Restart mrouted
589  */
590 static void
591 restart(i)
592     int i;
593 {
594     register int omask;
595 #ifdef SYSV
596     sigset_t block, oblock;
597 #endif
598 
599     log(LOG_NOTICE, 0, "%s restart", versionstring);
600 
601     /*
602      * reset all the entries
603      */
604 #ifdef SYSV
605     (void)sigemptyset(&block);
606     (void)sigaddset(&block, SIGALRM);
607     if (sigprocmask(SIG_BLOCK, &block, &oblock) < 0)
608 	log(LOG_ERR, errno, "sigprocmask");
609 #else
610     omask = sigblock(sigmask(SIGALRM));
611 #endif
612     free_all_prunes();
613     free_all_routes();
614     stop_all_vifs();
615     k_stop_dvmrp();
616     close(igmp_socket);
617     close(udp_socket);
618 
619     /*
620      * start processing again
621      */
622     dvmrp_genid++;
623     pruning = 1;
624 
625     init_igmp();
626     init_routes();
627     init_ktable();
628     init_vifs();
629     k_init_dvmrp();		/* enable DVMRP routing in kernel */
630     init_installvifs();
631 
632 #ifdef SYSV
633     (void)sigprocmask(SIG_SETMASK, &oblock, (sigset_t *)NULL);
634 #else
635     (void)sigsetmask(omask);
636 #endif
637 }
638 
639 #define LOG_MAX_MSGS	20	/* if > 20/minute then shut up for a while */
640 #define LOG_SHUT_UP	600	/* shut up for 10 minutes */
641 static int log_nmsgs = 0;
642 
643 static void
644 resetlogging(arg)
645     void *arg;
646 {
647     int nxttime = 60;
648     void *narg = NULL;
649 
650     if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
651 	nxttime = LOG_SHUT_UP;
652 	narg = (void *)&log_nmsgs;	/* just need some valid void * */
653 	syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
654 			LOG_SHUT_UP / 60);
655     } else {
656 	log_nmsgs = 0;
657     }
658 
659     timer_setTimer(nxttime, resetlogging, narg);
660 }
661 
662 /*
663  * Log errors and other messages to the system log daemon and to stderr,
664  * according to the severity of the message and the current debug level.
665  * For errors of severity LOG_ERR or worse, terminate the program.
666  */
667 #ifdef __STDC__
668 void
669 log(int severity, int syserr, char *format, ...)
670 {
671     va_list ap;
672     static char fmt[211] = "warning - ";
673     char *msg;
674     char tbuf[20];
675     struct timeval now;
676     struct tm *thyme;
677     time_t t;
678 
679     va_start(ap, format);
680 #else
681 /*VARARGS3*/
682 void
683 log(severity, syserr, format, va_alist)
684     int severity, syserr;
685     char *format;
686     va_dcl
687 {
688     va_list ap;
689     static char fmt[211] = "warning - ";
690     char *msg;
691     char tbuf[20];
692     struct timeval now;
693     struct tm *thyme;
694     time_t t;
695 
696     va_start(ap);
697 #endif
698     vsprintf(&fmt[10], format, ap);
699     va_end(ap);
700     msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
701 
702     switch (debug) {
703 	case 0: break;
704 	case 1: if (severity > LOG_NOTICE) break;
705 	case 2: if (severity > LOG_INFO  ) break;
706 	default:
707 	    gettimeofday(&now,NULL);
708 	    t = now.tv_sec;
709 	    thyme = localtime(&t);
710 	    strftime(tbuf, sizeof(tbuf), "%X.%%03d ", thyme);
711 	    fprintf(stderr, tbuf, now.tv_usec / 1000);
712 	    fprintf(stderr, "%s", msg);
713 	    if (syserr == 0)
714 		fprintf(stderr, "\n");
715 	    else if (syserr < sys_nerr)
716 		fprintf(stderr, ": %s\n", sys_errlist[syserr]);
717 	    else
718 		fprintf(stderr, ": errno %d\n", syserr);
719     }
720 
721     if (severity <= LOG_NOTICE) {
722 	if (log_nmsgs++ < LOG_MAX_MSGS) {
723 	    if (syserr != 0) {
724 		errno = syserr;
725 		syslog(severity, "%s: %m", msg);
726 	    } else
727 		syslog(severity, "%s", msg);
728 	}
729 
730 	if (severity <= LOG_ERR) exit(1);
731     }
732 }
733 
734 #ifdef DEBUG_MFC
735 void
736 md_log(what, origin, mcastgrp)
737     int what;
738     u_int32_t origin, mcastgrp;
739 {
740     static FILE *f = NULL;
741     struct timeval tv;
742     u_int32_t buf[4];
743 
744     if (!f) {
745 	if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
746 	    log(LOG_ERR, errno, "open /tmp/mrouted.clog");
747 	}
748     }
749 
750     gettimeofday(&tv, NULL);
751     buf[0] = tv.tv_sec;
752     buf[1] = what;
753     buf[2] = origin;
754     buf[3] = mcastgrp;
755 
756     fwrite(buf, sizeof(u_int32_t), 4, f);
757 }
758 #endif
759