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