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