xref: /openbsd-src/usr.sbin/mrouted/main.c (revision 8445c53715e7030056b779e8ab40efb7820981f2)
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.6 2001/09/04 23:35:59 millert 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     int dummy;
102     FILE *fp;
103     struct timeval tv;
104     u_int32_t prev_genid;
105     int vers;
106     fd_set rfds, readers;
107     int nfds, n, i;
108     sigset_t mask, omask;
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 	bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
318 #ifdef SNMP
319    gettimeofday(nvp, 0);
320    if (nvp->tv_sec > svp->tv_sec
321        || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
322        alarmTimer(nvp);
323        eventTimer(nvp);
324        if (nvp->tv_usec < 500000L){
325       svp->tv_usec = nvp->tv_usec + 500000L;
326       svp->tv_sec = nvp->tv_sec;
327        } else {
328       svp->tv_usec = nvp->tv_usec - 500000L;
329       svp->tv_sec = nvp->tv_sec + 1;
330        }
331    }
332 
333 	tvp =  &timeout;
334 	tvp->tv_sec = 0;
335 	tvp->tv_usec = 500000L;
336 
337 	block = 0;
338 	snmp_select_info(&nfds, &rfds, tvp, &block);
339 	if (block == 1)
340 		tvp = NULL; /* block without timeout */
341 	if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
342 #else
343 	if ((n = select(nfds, &rfds, NULL, NULL, NULL)) < 0)
344 #endif
345    {
346             if (errno != EINTR) /* SIGALRM is expected */
347                 log(LOG_WARNING, errno, "select failed");
348             continue;
349         }
350 
351 	if (FD_ISSET(igmp_socket, &rfds)) {
352 	    recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
353 			       0, NULL, &dummy);
354 	    if (recvlen < 0) {
355 		if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
356 		continue;
357 	    }
358 	    (void)sigemptyset(&mask);
359 	    (void)sigaddset(&mask, SIGALRM);
360 	    if (sigprocmask(SIG_BLOCK, &mask, &omask) < 0)
361 		    log(LOG_ERR, errno, "sigprocmask");
362 	    accept_igmp(recvlen);
363 	    (void)sigprocmask(SIG_SETMASK, &omask, NULL);
364         }
365 
366 	for (i = 0; i < nhandlers; i++) {
367 	    if (FD_ISSET(ihandlers[i].fd, &rfds)) {
368 		(*ihandlers[i].func)(ihandlers[i].fd, &rfds);
369 	    }
370 	}
371 
372 #ifdef SNMP
373 	snmp_read(&rfds);
374 	snmp_timeout(); /* poll */
375 #endif
376     }
377 }
378 
379 
380 /*
381  * routine invoked every second.  Its main goal is to cycle through
382  * the routing table and send partial updates to all neighbors at a
383  * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
384  * seconds.  Also, every TIMER_INTERVAL seconds it calls timer() to
385  * do all the other time-based processing.
386  */
387 static void
388 fasttimer(i)
389     int i;
390 {
391     static unsigned int tlast;
392     static unsigned int nsent;
393     register unsigned int t = tlast + 1;
394     register int n;
395 
396     /*
397      * if we're in the last second, send everything that's left.
398      * otherwise send at least the fraction we should have sent by now.
399      */
400     if (t >= ROUTE_REPORT_INTERVAL) {
401 	register int nleft = nroutes - nsent;
402 	while (nleft > 0) {
403 	    if ((n = report_next_chunk()) <= 0)
404 		break;
405 	    nleft -= n;
406 	}
407 	tlast = 0;
408 	nsent = 0;
409     } else {
410 	register unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
411 	while (nsent < ncum) {
412 	    if ((n = report_next_chunk()) <= 0)
413 		break;
414 	    nsent += n;
415 	}
416 	tlast = t;
417     }
418     if ((t % TIMER_INTERVAL) == 0)
419 	timer();
420 
421     age_callout_queue();/* Advance the timer for the callout queue
422 				for groups */
423     alarm(1);
424 }
425 
426 /*
427  * The 'virtual_time' variable is initialized to a value that will cause the
428  * first invocation of timer() to send a probe or route report to all vifs
429  * and send group membership queries to all subnets for which this router is
430  * querier.  This first invocation occurs approximately TIMER_INTERVAL seconds
431  * after the router starts up.   Note that probes for neighbors and queries
432  * for group memberships are also sent at start-up time, as part of initial-
433  * ization.  This repetition after a short interval is desirable for quickly
434  * building up topology and membership information in the presence of possible
435  * packet loss.
436  *
437  * 'virtual_time' advances at a rate that is only a crude approximation of
438  * real time, because it does not take into account any time spent processing,
439  * and because the timer intervals are sometimes shrunk by a random amount to
440  * avoid unwanted synchronization with other routers.
441  */
442 
443 static u_long virtual_time = 0;
444 
445 
446 /*
447  * Timer routine.  Performs periodic neighbor probing, route reporting, and
448  * group querying duties, and drives various timers in routing entries and
449  * virtual interface data structures.
450  */
451 static void
452 timer()
453 {
454     age_routes();	/* Advance the timers in the route entries     */
455     age_vifs();		/* Advance the timers for neighbors */
456     age_table_entry();	/* Advance the timers for the cache entries */
457 
458     if (virtual_time % GROUP_QUERY_INTERVAL == 0) {
459 	/*
460 	 * Time to query the local group memberships on all subnets
461 	 * for which this router is the elected querier.
462 	 */
463 	query_groups();
464     }
465 
466     if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
467 	/*
468 	 * Time to send a probe on all vifs from which no neighbors have
469 	 * been heard.  Also, check if any inoperative interfaces have now
470 	 * come up.  (If they have, they will also be probed as part of
471 	 * their initialization.)
472 	 */
473 	probe_for_neighbors();
474 
475 	if (vifs_down)
476 	    check_vif_state();
477     }
478 
479     delay_change_reports = FALSE;
480     if (routes_changed) {
481 	/*
482 	 * Some routes have changed since the last timer interrupt, but
483 	 * have not been reported yet.  Report the changed routes to all
484 	 * neighbors.
485 	 */
486 	report_to_all_neighbors(CHANGED_ROUTES);
487     }
488 
489 #ifdef SNMP
490     sync_timer();
491 #endif
492 
493     /*
494      * Advance virtual time
495      */
496     virtual_time += TIMER_INTERVAL;
497 }
498 
499 
500 /*
501  * On termination, let everyone know we're going away.
502  */
503 static void
504 done(i)
505     int i;
506 {
507     log(LOG_NOTICE, 0, "%s exiting", versionstring);
508     cleanup();
509     _exit(1);
510 }
511 
512 static void
513 cleanup()
514 {
515     static in_cleanup = 0;
516 
517     if (!in_cleanup) {
518 	in_cleanup++;
519 #ifdef RSRR
520 	rsrr_clean();
521 #endif /* RSRR */
522 	expire_all_routes();
523 	report_to_all_neighbors(ALL_ROUTES);
524 	k_stop_dvmrp();
525     }
526 }
527 
528 
529 /*
530  * Dump internal data structures to stderr.
531  */
532 static void
533 dump(i)
534     int i;
535 {
536     dump_vifs(stderr);
537     dump_routes(stderr);
538 }
539 
540 
541 /*
542  * Dump internal data structures to a file.
543  */
544 static void
545 fdump(i)
546     int i;
547 {
548     FILE *fp;
549 
550     fp = fopen(dumpfilename, "w");
551     if (fp != NULL) {
552 	dump_vifs(fp);
553 	dump_routes(fp);
554 	(void) fclose(fp);
555     }
556 }
557 
558 
559 /*
560  * Dump local cache contents to a file.
561  */
562 static void
563 cdump(i)
564     int i;
565 {
566     FILE *fp;
567 
568     fp = fopen(cachefilename, "w");
569     if (fp != NULL) {
570 	dump_cache(fp);
571 	(void) fclose(fp);
572     }
573 }
574 
575 
576 /*
577  * Restart mrouted
578  */
579 static void
580 restart(i)
581     int i;
582 {
583     sigset_t mask, omask;
584 
585     log(LOG_NOTICE, 0, "%s restart", versionstring);
586 
587     /*
588      * reset all the entries
589      */
590     (void)sigemptyset(&mask);
591     (void)sigaddset(&mask, SIGALRM);
592     if (sigprocmask(SIG_BLOCK, &mask, &omask) < 0)
593 	log(LOG_ERR, errno, "sigprocmask");
594     free_all_prunes();
595     free_all_routes();
596     stop_all_vifs();
597     k_stop_dvmrp();
598     close(igmp_socket);
599     close(udp_socket);
600 
601     /*
602      * start processing again
603      */
604     dvmrp_genid++;
605     pruning = 1;
606 
607     init_igmp();
608     init_routes();
609     init_ktable();
610     init_vifs();
611     k_init_dvmrp();		/* enable DVMRP routing in kernel */
612     init_installvifs();
613 
614     (void)sigprocmask(SIG_SETMASK, &omask, NULL);
615 }
616 
617 #define LOG_MAX_MSGS	20	/* if > 20/minute then shut up for a while */
618 #define LOG_SHUT_UP	600	/* shut up for 10 minutes */
619 static int log_nmsgs = 0;
620 
621 static void
622 resetlogging(arg)
623     void *arg;
624 {
625     int nxttime = 60;
626     void *narg = NULL;
627 
628     if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
629 	nxttime = LOG_SHUT_UP;
630 	narg = (void *)&log_nmsgs;	/* just need some valid void * */
631 	syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
632 			LOG_SHUT_UP / 60);
633     } else {
634 	log_nmsgs = 0;
635     }
636 
637     timer_setTimer(nxttime, resetlogging, narg);
638 }
639 
640 /*
641  * Log errors and other messages to the system log daemon and to stderr,
642  * according to the severity of the message and the current debug level.
643  * For errors of severity LOG_ERR or worse, terminate the program.
644  */
645 #ifdef __STDC__
646 void
647 log(int severity, int syserr, char *format, ...)
648 {
649     va_list ap;
650     static char fmt[211] = "warning - ";
651     char *msg;
652     char tbuf[20];
653     struct timeval now;
654     struct tm *thyme;
655     time_t t;
656 
657     va_start(ap, format);
658 #else
659 /*VARARGS3*/
660 void
661 log(severity, syserr, format, va_alist)
662     int severity, syserr;
663     char *format;
664     va_dcl
665 {
666     va_list ap;
667     static char fmt[211] = "warning - ";
668     char *msg;
669     char tbuf[20];
670     struct timeval now;
671     struct tm *thyme;
672     time_t t;
673 
674     va_start(ap);
675 #endif
676     vsprintf(&fmt[10], format, ap);
677     va_end(ap);
678     msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
679 
680     switch (debug) {
681 	case 0: break;
682 	case 1: if (severity > LOG_NOTICE) break;
683 	case 2: if (severity > LOG_INFO  ) break;
684 	default:
685 	    gettimeofday(&now,NULL);
686 	    t = now.tv_sec;
687 	    thyme = localtime(&t);
688 	    strftime(tbuf, sizeof(tbuf), "%X.%%03d ", thyme);
689 	    fprintf(stderr, tbuf, now.tv_usec / 1000);
690 	    fprintf(stderr, "%s", msg);
691 	    if (syserr == 0)
692 		fprintf(stderr, "\n");
693 	    else if (syserr < sys_nerr)
694 		fprintf(stderr, ": %s\n", sys_errlist[syserr]);
695 	    else
696 		fprintf(stderr, ": errno %d\n", syserr);
697     }
698 
699     if (severity <= LOG_NOTICE) {
700 	if (log_nmsgs++ < LOG_MAX_MSGS) {
701 	    if (syserr != 0) {
702 		errno = syserr;
703 		syslog(severity, "%s: %m", msg);
704 	    } else
705 		syslog(severity, "%s", msg);
706 	}
707 
708 	if (severity <= LOG_ERR) exit(1);
709     }
710 }
711 
712 #ifdef DEBUG_MFC
713 void
714 md_log(what, origin, mcastgrp)
715     int what;
716     u_int32_t origin, mcastgrp;
717 {
718     static FILE *f = NULL;
719     struct timeval tv;
720     u_int32_t buf[4];
721 
722     if (!f) {
723 	if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
724 	    log(LOG_ERR, errno, "open /tmp/mrouted.clog");
725 	}
726     }
727 
728     gettimeofday(&tv, NULL);
729     buf[0] = tv.tv_sec;
730     buf[1] = what;
731     buf[2] = origin;
732     buf[3] = mcastgrp;
733 
734     fwrite(buf, sizeof(u_int32_t), 4, f);
735 }
736 #endif
737