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