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