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 <err.h>
25 #include <fcntl.h>
26 #include <util.h>
27
28 __RCSID("$Id: main.c,v 1.16 2005/06/16 19:41:23 robert Exp $");
29 __RCSID("$MirOS: src/usr.sbin/mrouted/main.c,v 1.5 2014/03/13 00:43:15 tg Exp $");
30
31 extern char *configfilename;
32 char versionstring[100];
33
34 void init_installvifs(void);
35
36 static char dumpfilename[] = _PATH_MROUTED_DUMP;
37 static char cachefilename[] = _PATH_MROUTED_CACHE;
38 static char genidfilename[] = _PATH_MROUTED_GENID;
39
40 int cache_lifetime = DEFAULT_CACHE_LIFETIME;
41 int max_prune_lifetime = DEFAULT_CACHE_LIFETIME * 2;
42
43 int debug = 0;
44 u_char pruning = 1; /* Enable pruning by default */
45
46 #define NHANDLERS 2
47
48 static struct ihandler {
49 int fd; /* File descriptor */
50 ihfunc_t func; /* Function to call with &fd_set */
51 } ihandlers[NHANDLERS];
52 static int nhandlers = 0;
53
54 /*
55 * Forward declarations.
56 */
57 static void fasttimer(int);
58 static void done(int);
59 static void dump(int);
60 static void fdump(int);
61 static void cdump(int);
62 static void restart(int);
63 static void timer(void);
64 static void cleanup(void);
65 static void resetlogging(void *);
66
67 int
register_input_handler(int fd,ihfunc_t func)68 register_input_handler(int fd, ihfunc_t func)
69 {
70 if (nhandlers >= NHANDLERS)
71 return -1;
72
73 ihandlers[nhandlers].fd = fd;
74 ihandlers[nhandlers++].func = func;
75
76 return 0;
77 }
78
79 int
main(int argc,char * argv[])80 main(int argc, char *argv[])
81 {
82 register int recvlen;
83 int dummy;
84 FILE *fp;
85 struct timeval tv;
86 u_int32_t prev_genid;
87 int vers;
88 fd_set rfds, readers;
89 int nfds, n, i, ch;
90 sigset_t mask, omask;
91 const char *errstr;
92
93 if (geteuid() != 0) {
94 fprintf(stderr, "must be root\n");
95 exit(1);
96 }
97 setlinebuf(stderr);
98
99 while ((ch = getopt(argc, argv, "c:d::p")) != -1) {
100 switch (ch) {
101 case 'c':
102 configfilename = optarg;
103 break;
104 case 'd':
105 if (!optarg)
106 debug = DEFAULT_DEBUG;
107 else {
108 debug = strtonum(optarg, 0, 3, &errstr);
109 if (errstr) {
110 warnx("debug level %s", errstr);
111 debug = DEFAULT_DEBUG;
112 }
113 }
114 break;
115 case 'p':
116 pruning = 0;
117 break;
118 default:
119 goto usage;
120 }
121 }
122 argc -= optind;
123 argv += optind;
124
125 if (argc > 0) {
126 usage: fprintf(stderr,
127 "usage: mrouted [-p] [-c configfile] [-d [debug_level]]\n");
128 exit(1);
129 }
130
131 if (debug == 0) {
132 /*
133 * Detach from the terminal
134 */
135 int t;
136
137 if (fork()) exit(0);
138 (void)close(0);
139 (void)close(1);
140 (void)close(2);
141 (void)open("/", 0);
142 (void)dup2(0, 1);
143 (void)dup2(0, 2);
144 #ifdef SYSV
145 (void)setpgrp();
146 #else
147 #ifdef TIOCNOTTY
148 t = open("/dev/tty", 2);
149 if (t >= 0) {
150 (void)ioctl(t, TIOCNOTTY, (char *)0);
151 (void)close(t);
152 }
153 #else
154 if (setsid() < 0)
155 perror("setsid");
156 #endif
157 #endif
158 }
159 else
160 fprintf(stderr, "debug level %u\n", debug);
161
162 #ifdef LOG_DAEMON
163 (void)openlog("mrouted", LOG_PID, LOG_DAEMON);
164 (void)setlogmask(LOG_UPTO(LOG_NOTICE));
165 #else
166 (void)openlog("mrouted", LOG_PID);
167 #endif
168 snprintf(versionstring, sizeof versionstring, "mrouted version %d.%d",
169 PROTOCOL_VERSION, MROUTED_VERSION);
170
171 logit(LOG_NOTICE, 0, "%s", versionstring);
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 memmove((char *)&rfds, (char *)&readers, 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
fasttimer(int i)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
timer(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
done(int i)420 done(int i)
421 {
422 logit(LOG_NOTICE, 0, "%s exiting", versionstring);
423 cleanup();
424 _exit(1);
425 }
426
427 static void
cleanup(void)428 cleanup(void)
429 {
430 static int 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
dump(int i)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
fdump(int i)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
cdump(int i)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
restart(int i)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
resetlogging(void * arg)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
logit(int severity,int syserr,char * format,...)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
md_logit(int what,u_int32_t origin,u_int32_t mcastgrp)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