main.c revision 1.15 1 /* $NetBSD: main.c,v 1.15 2002/07/14 16:30:42 wiz 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.15 2002/07/14 16:30:42 wiz 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 FD_SET(igmp_socket, &readers);
261 nfds = igmp_socket + 1;
262 for (i = 0; i < nhandlers; i++) {
263 FD_SET(ihandlers[i].fd, &readers);
264 if (ihandlers[i].fd >= nfds)
265 nfds = ihandlers[i].fd + 1;
266 }
267
268 /*
269 * Install the vifs in the kernel as late as possible in the
270 * initialization sequence.
271 */
272 init_installvifs();
273
274 if (debug >= 2) dump(0);
275
276 /* Start up the log rate-limiter */
277 resetlogging(NULL);
278
279 (void)alarm(1); /* schedule first timer interrupt */
280
281 /*
282 * Main receive loop.
283 */
284 dummy = 0;
285 for(;;) {
286 #ifdef SYSV
287 sigset_t block, oblock;
288 #endif
289 bcopy((char *)&readers, (char *)&rfds, sizeof(rfds));
290 #ifdef SNMP
291 gettimeofday(nvp, 0);
292 if (nvp->tv_sec > svp->tv_sec
293 || (nvp->tv_sec == svp->tv_sec && nvp->tv_usec > svp->tv_usec)){
294 alarmTimer(nvp);
295 eventTimer(nvp);
296 if (nvp->tv_usec < 500000L){
297 svp->tv_usec = nvp->tv_usec + 500000L;
298 svp->tv_sec = nvp->tv_sec;
299 } else {
300 svp->tv_usec = nvp->tv_usec - 500000L;
301 svp->tv_sec = nvp->tv_sec + 1;
302 }
303 }
304
305 tvp = &timeout;
306 tvp->tv_sec = 0;
307 tvp->tv_usec = 500000L;
308
309 block = 0;
310 snmp_select_info(&nfds, &rfds, tvp, &block);
311 if (block == 1)
312 tvp = NULL; /* block without timeout */
313 if ((n = select(nfds, &rfds, NULL, NULL, tvp)) < 0)
314 #else
315 if ((n = select(nfds, &rfds, NULL, NULL, NULL)) < 0)
316 #endif
317 {
318 if (errno != EINTR) /* SIGALRM is expected */
319 log(LOG_WARNING, errno, "select failed");
320 continue;
321 }
322
323 if (FD_ISSET(igmp_socket, &rfds)) {
324 recvlen = recvfrom(igmp_socket, recv_buf, RECV_BUF_SIZE,
325 0, NULL, &dummy);
326 if (recvlen < 0) {
327 if (errno != EINTR) log(LOG_ERR, errno, "recvfrom");
328 continue;
329 }
330 #ifdef SYSV
331 (void)sigemptyset(&block);
332 (void)sigaddset(&block, SIGALRM);
333 if (sigprocmask(SIG_BLOCK, &block, &oblock) < 0)
334 log(LOG_ERR, errno, "sigprocmask");
335 #else
336 omask = sigblock(sigmask(SIGALRM));
337 #endif
338 accept_igmp(recvlen);
339 #ifdef SYSV
340 (void)sigprocmask(SIG_SETMASK, &oblock, (sigset_t *)NULL);
341 #else
342 (void)sigsetmask(omask);
343 #endif
344 }
345
346 for (i = 0; i < nhandlers; i++) {
347 if (FD_ISSET(ihandlers[i].fd, &rfds)) {
348 (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
349 }
350 }
351
352 #ifdef SNMP
353 snmp_read(&rfds);
354 snmp_timeout(); /* poll */
355 #endif
356 }
357 }
358
359
360 /*
361 * routine invoked every second. Its main goal is to cycle through
362 * the routing table and send partial updates to all neighbors at a
363 * rate that will cause the entire table to be sent in ROUTE_REPORT_INTERVAL
364 * seconds. Also, every TIMER_INTERVAL seconds it calls timer() to
365 * do all the other time-based processing.
366 */
367 static void
368 fasttimer(int i)
369 {
370 static unsigned int tlast;
371 static unsigned int nsent;
372 unsigned int t = tlast + 1;
373 int n;
374
375 /*
376 * if we're in the last second, send everything that's left.
377 * otherwise send at least the fraction we should have sent by now.
378 */
379 if (t >= ROUTE_REPORT_INTERVAL) {
380 int nleft = nroutes - nsent;
381 while (nleft > 0) {
382 if ((n = report_next_chunk()) <= 0)
383 break;
384 nleft -= n;
385 }
386 tlast = 0;
387 nsent = 0;
388 } else {
389 unsigned int ncum = nroutes * t / ROUTE_REPORT_INTERVAL;
390 while (nsent < ncum) {
391 if ((n = report_next_chunk()) <= 0)
392 break;
393 nsent += n;
394 }
395 tlast = t;
396 }
397 if ((t % TIMER_INTERVAL) == 0)
398 timer();
399
400 age_callout_queue();/* Advance the timer for the callout queue
401 for groups */
402 alarm(1);
403 }
404
405 /*
406 * The 'virtual_time' variable is initialized to a value that will cause the
407 * first invocation of timer() to send a probe or route report to all vifs
408 * and send group membership queries to all subnets for which this router is
409 * querier. This first invocation occurs approximately TIMER_INTERVAL seconds
410 * after the router starts up. Note that probes for neighbors and queries
411 * for group memberships are also sent at start-up time, as part of initial-
412 * ization. This repetition after a short interval is desirable for quickly
413 * building up topology and membership information in the presence of possible
414 * packet loss.
415 *
416 * 'virtual_time' advances at a rate that is only a crude approximation of
417 * real time, because it does not take into account any time spent processing,
418 * and because the timer intervals are sometimes shrunk by a random amount to
419 * avoid unwanted synchronization with other routers.
420 */
421
422 static u_long virtual_time = 0;
423
424
425 /*
426 * Timer routine. Performs periodic neighbor probing, route reporting, and
427 * group querying duties, and drives various timers in routing entries and
428 * virtual interface data structures.
429 */
430 static void
431 timer(void)
432 {
433 age_routes(); /* Advance the timers in the route entries */
434 age_vifs(); /* Advance the timers for neighbors */
435 age_table_entry(); /* Advance the timers for the cache entries */
436
437 if (virtual_time % GROUP_QUERY_INTERVAL == 0) {
438 /*
439 * Time to query the local group memberships on all subnets
440 * for which this router is the elected querier.
441 */
442 query_groups();
443 }
444
445 if (virtual_time % NEIGHBOR_PROBE_INTERVAL == 0) {
446 /*
447 * Time to send a probe on all vifs from which no neighbors have
448 * been heard. Also, check if any inoperative interfaces have now
449 * come up. (If they have, they will also be probed as part of
450 * their initialization.)
451 */
452 probe_for_neighbors();
453
454 if (vifs_down)
455 check_vif_state();
456 }
457
458 delay_change_reports = FALSE;
459 if (routes_changed) {
460 /*
461 * Some routes have changed since the last timer interrupt, but
462 * have not been reported yet. Report the changed routes to all
463 * neighbors.
464 */
465 report_to_all_neighbors(CHANGED_ROUTES);
466 }
467
468 #ifdef SNMP
469 sync_timer();
470 #endif
471
472 /*
473 * Advance virtual time
474 */
475 virtual_time += TIMER_INTERVAL;
476 }
477
478
479 /*
480 * On termination, let everyone know we're going away.
481 */
482 static void
483 done(int i)
484 {
485 log(LOG_NOTICE, 0, "%s exiting", versionstring);
486 cleanup();
487 _exit(1);
488 }
489
490 static void
491 cleanup(void)
492 {
493 static int in_cleanup = 0;
494
495 if (!in_cleanup) {
496 in_cleanup++;
497 #ifdef RSRR
498 rsrr_clean();
499 #endif /* RSRR */
500 expire_all_routes();
501 report_to_all_neighbors(ALL_ROUTES);
502 k_stop_dvmrp();
503 }
504 }
505
506
507 /*
508 * Dump internal data structures to stderr.
509 */
510 static void
511 dump(int i)
512 {
513 dump_vifs(stderr);
514 dump_routes(stderr);
515 }
516
517
518 /*
519 * Dump internal data structures to a file.
520 */
521 static void
522 fdump(int i)
523 {
524 FILE *fp;
525
526 fp = fopen(dumpfilename, "w");
527 if (fp != NULL) {
528 dump_vifs(fp);
529 dump_routes(fp);
530 (void) fclose(fp);
531 }
532 }
533
534
535 /*
536 * Dump local cache contents to a file.
537 */
538 static void
539 cdump(int i)
540 {
541 FILE *fp;
542
543 fp = fopen(cachefilename, "w");
544 if (fp != NULL) {
545 dump_cache(fp);
546 (void) fclose(fp);
547 }
548 }
549
550
551 /*
552 * Restart mrouted
553 */
554 static void
555 restart(int i)
556 {
557 int omask;
558 #ifdef SYSV
559 sigset_t block, oblock;
560 #endif
561
562 log(LOG_NOTICE, 0, "%s restart", versionstring);
563
564 /*
565 * reset all the entries
566 */
567 #ifdef SYSV
568 (void)sigemptyset(&block);
569 (void)sigaddset(&block, SIGALRM);
570 if (sigprocmask(SIG_BLOCK, &block, &oblock) < 0)
571 log(LOG_ERR, errno, "sigprocmask");
572 #else
573 omask = sigblock(sigmask(SIGALRM));
574 #endif
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 #ifdef SYSV
596 (void)sigprocmask(SIG_SETMASK, &oblock, (sigset_t *)NULL);
597 #else
598 (void)sigsetmask(omask);
599 #endif
600 }
601
602 #define LOG_MAX_MSGS 20 /* if > 20/minute then shut up for a while */
603 #define LOG_SHUT_UP 600 /* shut up for 10 minutes */
604 static int log_nmsgs = 0;
605
606 static void
607 resetlogging(void *arg)
608 {
609 int nxttime = 60;
610 void *narg = NULL;
611
612 if (arg == NULL && log_nmsgs > LOG_MAX_MSGS) {
613 nxttime = LOG_SHUT_UP;
614 narg = (void *)&log_nmsgs; /* just need some valid void * */
615 syslog(LOG_WARNING, "logging too fast, shutting up for %d minutes",
616 LOG_SHUT_UP / 60);
617 } else {
618 log_nmsgs = 0;
619 }
620
621 timer_setTimer(nxttime, resetlogging, narg);
622 }
623
624 /*
625 * Log errors and other messages to the system log daemon and to stderr,
626 * according to the severity of the message and the current debug level.
627 * For errors of severity LOG_ERR or worse, terminate the program.
628 */
629 void
630 log(int severity, int syserr, const char *format, ...)
631 {
632 va_list ap;
633 static char fmt[211] = "warning - ";
634 char *msg;
635 char tbuf[20];
636 struct timeval now;
637 struct tm *thyme;
638 time_t t;
639
640 va_start(ap, format);
641 vsprintf(&fmt[10], format, ap);
642 va_end(ap);
643 msg = (severity == LOG_WARNING) ? fmt : &fmt[10];
644
645 switch (debug) {
646 case 0: break;
647 case 1: if (severity > LOG_NOTICE) break;
648 case 2: if (severity > LOG_INFO ) break;
649 default:
650 gettimeofday(&now,NULL);
651 t = now.tv_sec;
652 thyme = localtime(&t);
653 strftime(tbuf, sizeof(tbuf), "%X", thyme);
654 fprintf(stderr, "%s.%03ld %s", tbuf, (long)now.tv_usec / 1000,
655 msg);
656 if (syserr == 0)
657 fprintf(stderr, "\n");
658 else
659 fprintf(stderr, ": %s\n", strerror(syserr));
660 }
661
662 if (severity <= LOG_NOTICE) {
663 if (log_nmsgs++ < LOG_MAX_MSGS) {
664 if (syserr != 0) {
665 errno = syserr;
666 syslog(severity, "%s: %m", msg);
667 } else
668 syslog(severity, "%s", msg);
669 }
670
671 if (severity <= LOG_ERR) exit(1);
672 }
673 }
674
675 #ifdef DEBUG_MFC
676 void
677 md_log(int what, u_int32_t origin, u_int32_t mcastgrp)
678 {
679 static FILE *f = NULL;
680 struct timeval tv;
681 u_int32_t buf[4];
682
683 if (!f) {
684 if ((f = fopen("/tmp/mrouted.clog", "w")) == NULL) {
685 log(LOG_ERR, errno, "open /tmp/mrouted.clog");
686 }
687 }
688
689 gettimeofday(&tv, NULL);
690 buf[0] = tv.tv_sec;
691 buf[1] = what;
692 buf[2] = origin;
693 buf[3] = mcastgrp;
694
695 fwrite(buf, sizeof(u_int32_t), 4, f);
696 }
697 #endif
698