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