xref: /titanic_44/usr/src/cmd/cmd-inet/usr.sbin/in.routed/main.c (revision 24da5b34f49324ed742a340010ed5bd3d4e06625)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  *
5  * Copyright (c) 1983, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgment:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD: src/sbin/routed/main.c,v 1.14 2000/08/11 08:24:38 sheldonh Exp $
37  * char copyright[] = "@(#) Copyright (c) 1983, 1988, 1993\n"
38  * " The Regents of the University of California.  All rights reserved.\n";
39  */
40 
41 #pragma ident	"%Z%%M%	%I%	%E% SMI"
42 
43 #include "defs.h"
44 #include "pathnames.h"
45 #include <signal.h>
46 #include <fcntl.h>
47 #include <sys/file.h>
48 #include <userdefs.h>
49 #include <sys/stat.h>
50 
51 #define	IN_ROUTED_VERSION	"2.22"
52 
53 int		stopint;
54 boolean_t	supplier;	/* supply or broadcast updates */
55 boolean_t	supplier_set;
56 /* -S option. _B_TRUE=treat all RIP speakers as default routers. */
57 boolean_t	save_space = _B_FALSE;
58 
59 static boolean_t default_gateway;	/* _B_TRUE=advertise default */
60 static boolean_t background = _B_TRUE;
61 boolean_t	ridhosts;	/* _B_TRUE=reduce host routes */
62 boolean_t	mhome;		/* _B_TRUE=want multi-homed host route */
63 boolean_t	advertise_mhome;  /* _B_TRUE=must continue advertising it */
64 boolean_t	auth_ok = _B_TRUE; /* _B_TRUE=ignore auth if we don't care */
65 boolean_t	no_install;	/* _B_TRUE=don't install in kernel */
66 
67 struct timeval epoch;		/* when started */
68 struct timeval clk;
69 static struct timeval prev_clk;
70 static int usec_fudge;
71 struct timeval now;		/* current idea of time */
72 /* If a route's rts_time is <= to now_stale, the route is stale. */
73 time_t	now_stale;
74 /* If a route's rts_time is <= to now_expire, the route is expired */
75 time_t	now_expire;
76 /* If a route's rts_time is <= to now_garbage, the route needs to be deleted */
77 time_t	now_garbage;
78 
79 static struct timeval next_bcast;	/* next general broadcast */
80 struct timeval no_flash = {		/* inhibit flash update */
81 	EPOCH+SUPPLY_INTERVAL, 0
82 };
83 
84 /* When now reaches this time, it's time to call sync_kern() */
85 static struct timeval sync_kern_timer;
86 
87 static fd_set	fdbits;
88 static int	sock_max;
89 int		rip_sock = -1;	/* RIP socket */
90 boolean_t	rip_enabled;
91 static boolean_t	openlog_done;
92 
93 /*
94  * The interface to which rip_sock is currently pointing for
95  * output.
96  */
97 struct interface *rip_sock_interface;
98 
99 int	rt_sock;			/* routing socket */
100 
101 
102 static  int open_rip_sock();
103 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
104 static void	sigalrm(int);
105 static void	sigterm(int);
106 
107 static int
108 daemon(boolean_t nochdir, boolean_t noclose)
109 {
110 	int retv;
111 
112 	if ((retv = fork()) == -1)
113 		return (-1);
114 	if (retv != 0)
115 		_exit(EXIT_SUCCESS);
116 	if (setsid() == -1)
117 		return (-1);
118 	if ((retv = fork()) == -1)
119 		return (-1);
120 	if (retv != 0)
121 		_exit(EXIT_SUCCESS);
122 	if (!nochdir && chdir("/") == -1)
123 		return (-1);
124 	if (!noclose) {
125 		(void) close(0);
126 		(void) close(1);
127 		(void) close(2);
128 		if ((retv = open("/dev/null", O_RDWR)) != -1) {
129 			(void) dup2(retv, 1);
130 			(void) dup2(retv, 2);
131 		}
132 	}
133 	return (0);
134 }
135 
136 int
137 main(int argc, char *argv[])
138 {
139 	int n, off;
140 	char *p, *q;
141 	const char *cp;
142 	struct timeval select_timeout, result;
143 	fd_set ibits;
144 	in_addr_t p_net, p_mask;
145 	struct parm parm;
146 	char *tracename = NULL;
147 	boolean_t vflag = _B_FALSE;
148 	boolean_t version = _B_FALSE;
149 	int sigerr = 0;
150 	FILE *pidfp;
151 	mode_t pidmode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); /* 0644 */
152 
153 	(void) setlocale(LC_ALL, "");
154 
155 #if	!defined(TEXT_DOMAIN)   /* Should be defined by cc -D */
156 #define	TEXT_DOMAIN	"SYS_TEXT"
157 #endif	/* ! TEXT_DOMAIN */
158 
159 	(void) textdomain(TEXT_DOMAIN);
160 
161 	/*
162 	 * Some shells are badly broken and send SIGHUP to backgrounded
163 	 * processes.
164 	 */
165 	if (signal(SIGHUP, SIG_IGN) == SIG_ERR)
166 		sigerr = errno;
167 
168 	ftrace = stdout;
169 
170 	if (gettimeofday(&clk, 0) == -1) {
171 		logbad(_B_FALSE, "gettimeofday: %s", rip_strerror(errno));
172 	}
173 	prev_clk = clk;
174 	epoch = clk;
175 	epoch.tv_sec -= EPOCH;
176 	now.tv_sec = EPOCH;
177 	now_stale = EPOCH - STALE_TIME;
178 	now_expire = EPOCH - EXPIRE_TIME;
179 	now_garbage = EPOCH - GARBAGE_TIME;
180 	select_timeout.tv_sec = 0;
181 
182 	while ((n = getopt(argc, argv, "sSqdghmpAztVvnT:F:P:")) != -1) {
183 		switch (n) {
184 		case 'A':
185 			/*
186 			 * Ignore authentication if we do not care.
187 			 * Crazy as it is, that is what RFC 2453 requires.
188 			 */
189 			auth_ok = _B_FALSE;
190 			break;
191 
192 		case 't':
193 			if (new_tracelevel < 2)
194 				new_tracelevel = 2;
195 			background = _B_FALSE;
196 			break;
197 
198 		case 'd':	/* put in.routed in foreground */
199 			background = _B_FALSE;
200 			break;
201 
202 		case 'F':		/* minimal routes for SLIP */
203 			n = FAKE_METRIC;
204 			p = strchr(optarg, ',');
205 			if (p != NULL) {
206 				n = (int)strtoul(p+1, &q, 0);
207 				if (*q == '\0' && p+1 != q &&
208 				    n <= HOPCNT_INFINITY-1 && n >= 1)
209 					*p = '\0';
210 			}
211 			if (!getnet(optarg, &p_net, &p_mask)) {
212 				if (p != NULL)
213 					*p = ',';
214 				msglog(gettext("bad network; \"-F %s\""),
215 				    optarg);
216 				break;
217 			}
218 			(void) memset(&parm, 0, sizeof (parm));
219 			parm.parm_net = p_net;
220 			parm.parm_mask = p_mask;
221 			parm.parm_d_metric = n;
222 			cp = insert_parm(&parm);
223 			if (cp != NULL)
224 				msglog(gettext("bad -F: %s"), cp);
225 			break;
226 
227 		case 'g':
228 			(void) memset(&parm, 0, sizeof (parm));
229 			parm.parm_d_metric = 1;
230 			cp = insert_parm(&parm);
231 			if (cp != NULL)
232 				msglog(gettext("bad -g: %s"), cp);
233 			else
234 				default_gateway = _B_TRUE;
235 			break;
236 
237 		case 'h':		/* suppress extra host routes */
238 			ridhosts = _B_TRUE;
239 			break;
240 
241 		case 'm':		/* advertise host route */
242 			mhome = _B_TRUE;	/* on multi-homed hosts */
243 			break;
244 
245 		case 'n':	/* No-install mode */
246 			no_install = _B_TRUE;
247 			break;
248 
249 		case 'P':
250 			/* handle arbitrary parameters. */
251 			q = strdup(optarg);
252 			if (q == NULL)
253 				logbad(_B_FALSE, "strdup: %s",
254 				    rip_strerror(errno));
255 			cp = parse_parms(q, _B_FALSE);
256 			if (cp != NULL)
257 				msglog(gettext("%1$s in \"-P %2$s\""), cp,
258 				    optarg);
259 			free(q);
260 			break;
261 
262 		case 'q':
263 			supplier = _B_FALSE;
264 			supplier_set = _B_TRUE;
265 			break;
266 
267 		case 's':
268 			supplier = _B_TRUE;
269 			supplier_set = _B_TRUE;
270 			break;
271 
272 		case 'S':	/* save-space option */
273 			save_space = _B_TRUE;
274 			break;
275 
276 		case 'T':
277 			tracename = optarg;
278 			break;
279 
280 		case 'V':
281 			/* display version */
282 			version = _B_TRUE;
283 			msglog(gettext("version " IN_ROUTED_VERSION));
284 			break;
285 
286 		case 'v':
287 			/* display route changes to supplied logfile */
288 			new_tracelevel = 1;
289 			vflag = _B_TRUE;
290 			break;
291 
292 		case 'z':	/* increase debug-level */
293 			new_tracelevel++;
294 			break;
295 
296 		default:
297 			goto usage;
298 		}
299 	}
300 	argc -= optind;
301 	argv += optind;
302 
303 	if (tracename == NULL && argc >= 1) {
304 		tracename = *argv++;
305 		argc--;
306 	}
307 	if (tracename != NULL && tracename[0] == '\0')
308 		goto usage;
309 	if (vflag && tracename == NULL)
310 		goto usage;
311 	if (argc != 0) {
312 usage:
313 		(void) fprintf(stderr,
314 		    gettext("usage: in.routed [-AdghmnqsStVvz] "
315 			"[-T <tracefile>]\n"));
316 		(void) fprintf(stderr,
317 		    gettext("\t[-F <net>[/<mask>][,<metric>]] [-P <parms>]\n"));
318 		logbad(_B_FALSE, gettext("excess arguments"));
319 	}
320 	if (geteuid() != 0) {
321 		/*
322 		 * Regular users are allowed to run in.routed for the
323 		 * sole purpose of obtaining the version number.  In
324 		 * that case, exit(EXIT_SUCCESS) without complaining.
325 		 */
326 		if (version)
327 			exit(EXIT_SUCCESS);
328 		logbad(_B_FALSE, gettext("requires UID 0"));
329 	}
330 
331 	if (default_gateway) {
332 		if (supplier_set && !supplier) {
333 			msglog(gettext("-g and -q are incompatible"));
334 		} else {
335 			supplier = _B_TRUE;
336 			supplier_set = _B_TRUE;
337 		}
338 	}
339 
340 	if (signal(SIGALRM, sigalrm) == SIG_ERR)
341 		sigerr = errno;
342 	/* SIGHUP fatal during debugging */
343 	if (!background)
344 		if (signal(SIGHUP, sigterm) == SIG_ERR)
345 			sigerr = errno;
346 	if (signal(SIGTERM, sigterm) == SIG_ERR)
347 		sigerr = errno;
348 	if (signal(SIGINT, sigterm) == SIG_ERR)
349 		sigerr = errno;
350 	if (signal(SIGUSR1, sigtrace_more) == SIG_ERR)
351 		sigerr = errno;
352 	if (signal(SIGUSR2, sigtrace_less) == SIG_ERR)
353 		sigerr = errno;
354 	if (signal(SIGHUP, sigtrace_dump) == SIG_ERR)
355 		sigerr = errno;
356 
357 	if (sigerr)
358 		msglog("signal: %s", rip_strerror(sigerr));
359 
360 	/* get into the background */
361 	if (background && daemon(_B_FALSE, _B_FALSE) < 0)
362 		BADERR(_B_FALSE, "daemon()");
363 
364 	/* Store our process id, blow away any existing file if it exists. */
365 	if ((pidfp = fopen(PATH_PID, "w")) == NULL) {
366 		(void) fprintf(stderr,
367 		    gettext("in.routed: unable to open " PATH_PID ": %s\n"),
368 		    strerror(errno));
369 	} else {
370 		(void) fprintf(pidfp, "%ld\n", getpid());
371 		(void) fclose(pidfp);
372 		(void) chmod(PATH_PID, pidmode);
373 	}
374 
375 	srandom((int)(clk.tv_sec ^ clk.tv_usec ^ getpid()));
376 
377 	/* allocate the interface tables */
378 	iftbl_alloc();
379 
380 	/* prepare socket connected to the kernel. */
381 	rt_sock = socket(PF_ROUTE, SOCK_RAW, AF_INET);
382 	if (rt_sock < 0)
383 		BADERR(_B_TRUE, "rt_sock = socket()");
384 	if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
385 		logbad(_B_TRUE, "fcntl(rt_sock) O_NONBLOCK: %s",
386 		    rip_strerror(errno));
387 	off = 0;
388 	if (setsockopt(rt_sock, SOL_SOCKET, SO_USELOOPBACK,
389 	    &off, sizeof (off)) < 0)
390 		LOGERR("setsockopt(SO_USELOOPBACK,0)");
391 
392 	fix_select();
393 
394 
395 	if (tracename != NULL) {
396 		(void) strlcpy(inittracename, tracename,
397 		    sizeof (inittracename));
398 		set_tracefile(inittracename, "%s", -1);
399 	} else {
400 		tracelevel_msg("%s", -1);   /* turn on tracing to stdio */
401 	}
402 
403 	bufinit();
404 
405 	/* initialize radix tree */
406 	rtinit();
407 
408 	/*
409 	 * Pick a random part of the second for our output to minimize
410 	 * collisions.
411 	 *
412 	 * Start broadcasting after hearing from other routers, and
413 	 * at a random time so a bunch of systems do not get synchronized
414 	 * after a power failure.
415 	 *
416 	 * Since now is the number of seconds since epoch (this is initially
417 	 * EPOCH seconds), these times are really relative to now.
418 	 */
419 	intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
420 	age_timer.tv_usec = next_bcast.tv_usec;
421 	age_timer.tv_sec = EPOCH+MIN_WAITTIME;
422 	rdisc_timer = next_bcast;
423 	ifscan_timer.tv_usec = next_bcast.tv_usec;
424 
425 	/*
426 	 * Open the global rip socket.  From now on, this socket can be
427 	 * assumed to be open.  It will remain open until in.routed
428 	 * exits.
429 	 */
430 	rip_sock = open_rip_sock();
431 
432 	/*
433 	 * Collect an initial view of the world by checking the interface
434 	 * configuration and the kludge file.
435 	 *
436 	 * gwkludge() could call addroutefordefault(), resulting in a call to
437 	 * iflookup, and thus ifscan() to find the physical interfaces.
438 	 * ifscan() will attempt to use the rip_sock in order to join
439 	 * mcast groups, so gwkludge *must* be called after opening
440 	 * the rip_sock.
441 	 */
442 	gwkludge();
443 
444 	ifscan();
445 
446 	/* Ask for routes */
447 	rip_query();
448 	rdisc_sol();
449 
450 	/* Now turn off stdio if not tracing */
451 	if (new_tracelevel == 0)
452 		trace_close(background);
453 
454 	/* Loop until a fatal error occurs, listening and broadcasting. */
455 	for (;;) {
456 		prev_clk = clk;
457 		if (gettimeofday(&clk, 0) == -1) {
458 			logbad(_B_FALSE, "gettimeofday: %s",
459 			    rip_strerror(errno));
460 		}
461 		if (prev_clk.tv_sec == clk.tv_sec &&
462 		    prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
463 			/*
464 			 * Much of `in.routed` depends on time always advancing.
465 			 * On systems that do not guarantee that gettimeofday()
466 			 * produces unique timestamps even if called within
467 			 * a single tick, use trickery like that in classic
468 			 * BSD kernels.
469 			 */
470 			clk.tv_usec += ++usec_fudge;
471 
472 		} else {
473 			time_t dt;
474 
475 			usec_fudge = 0;
476 
477 			timevalsub(&result, &clk, &prev_clk);
478 			if (result.tv_sec < 0 || result.tv_sec >
479 			    select_timeout.tv_sec + 5) {
480 				/*
481 				 * Deal with time changes before other
482 				 * housekeeping to keep everything straight.
483 				 */
484 				dt = result.tv_sec;
485 				if (dt > 0)
486 					dt -= select_timeout.tv_sec;
487 				trace_act("time changed by %d sec", (int)dt);
488 				epoch.tv_sec += dt;
489 			}
490 		}
491 		timevalsub(&now, &clk, &epoch);
492 		now_stale = now.tv_sec - STALE_TIME;
493 		now_expire = now.tv_sec - EXPIRE_TIME;
494 		now_garbage = now.tv_sec - GARBAGE_TIME;
495 
496 		/* deal with signals that should affect tracing */
497 		set_tracelevel();
498 
499 		if (stopint != 0) {
500 			trace_off("exiting with signal %d", stopint);
501 			break;
502 		}
503 
504 		/* look for new or dead interfaces */
505 		timevalsub(&select_timeout, &ifscan_timer, &now);
506 		if (select_timeout.tv_sec <= 0) {
507 			select_timeout.tv_sec = 0;
508 			ifscan();
509 			rip_query();
510 			continue;
511 		}
512 
513 		/*
514 		 * Check the kernel table occassionally for mysteriously
515 		 * evaporated routes
516 		 */
517 		timevalsub(&result, &sync_kern_timer, &now);
518 		if (result.tv_sec <= 0) {
519 			sync_kern();
520 			sync_kern_timer.tv_sec = (now.tv_sec
521 			    + CHECK_QUIET_INTERVAL);
522 			continue;
523 		}
524 		if (timercmp(&result, &select_timeout, < /* */))
525 			select_timeout = result;
526 
527 		/* If it is time, then broadcast our routes. */
528 		if (should_supply(NULL) || advertise_mhome) {
529 			timevalsub(&result, &next_bcast, &now);
530 			if (result.tv_sec <= 0) {
531 				/*
532 				 * Synchronize the aging and broadcast
533 				 * timers to minimize awakenings
534 				 */
535 				age(0);
536 				age_peer_info();
537 
538 				rip_bcast(0);
539 
540 				/*
541 				 * It is desirable to send routing updates
542 				 * regularly.  So schedule the next update
543 				 * 30 seconds after the previous one was
544 				 * scheduled, instead of 30 seconds after
545 				 * the previous update was finished.
546 				 * Even if we just started after discovering
547 				 * a 2nd interface or were otherwise delayed,
548 				 * pick a 30-second aniversary of the
549 				 * original broadcast time.
550 				 */
551 				n = 1 + (0-result.tv_sec)/SUPPLY_INTERVAL;
552 				next_bcast.tv_sec += n*SUPPLY_INTERVAL;
553 
554 				continue;
555 			}
556 
557 			if (timercmp(&result, &select_timeout, < /* */))
558 				select_timeout = result;
559 		}
560 
561 		/*
562 		 * If we need a flash update, either do it now or
563 		 * set the delay to end when it is time.
564 		 *
565 		 * If we are within MIN_WAITTIME seconds of a full update,
566 		 * do not bother.
567 		 */
568 		if (need_flash && should_supply(NULL) &&
569 		    no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
570 			/* accurate to the millisecond */
571 			if (!timercmp(&no_flash, &now, > /* */))
572 				rip_bcast(1);
573 			timevalsub(&result, &no_flash, &now);
574 			if (timercmp(&result, &select_timeout, < /* */))
575 				select_timeout = result;
576 		}
577 
578 		/* trigger the main aging timer. */
579 		timevalsub(&result, &age_timer, &now);
580 		if (result.tv_sec <= 0) {
581 			age(0);
582 			continue;
583 		}
584 		if (timercmp(&result, &select_timeout, < /* */))
585 			select_timeout = result;
586 
587 		/* update the kernel routing table */
588 		timevalsub(&result, &need_kern, &now);
589 		if (result.tv_sec <= 0) {
590 			age(0);
591 			continue;
592 		}
593 		if (timercmp(&result, &select_timeout, < /* */))
594 			select_timeout = result;
595 
596 		/*
597 		 * take care of router discovery.  We compare timeval
598 		 * structures here to have millisecond granularity.
599 		 */
600 		if (!timercmp(&rdisc_timer, &now, > /* */)) {
601 			rdisc_age(0);
602 			continue;
603 		}
604 		timevalsub(&result, &rdisc_timer, &now);
605 		if (timercmp(&result, &select_timeout, < /* */))
606 			select_timeout = result;
607 
608 		/*
609 		 * Well-known bit of select(3c) silliness inherited
610 		 * from BSD: anything over 100 million seconds is
611 		 * considered an "error."  Reset that to zero.
612 		 */
613 		if (select_timeout.tv_sec > 100000000)
614 			select_timeout.tv_sec = 0;
615 
616 		/* wait for input or a timer to expire. */
617 		trace_flush();
618 		ibits = fdbits;
619 		n = select(sock_max, &ibits, 0, 0, &select_timeout);
620 		if (n <= 0) {
621 			if (n < 0 && errno != EINTR && errno != EAGAIN)
622 				BADERR(_B_TRUE, "select");
623 			continue;
624 		}
625 
626 		if (FD_ISSET(rt_sock, &ibits)) {
627 			read_rt();
628 			n--;
629 		}
630 		if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
631 			read_d();
632 			n--;
633 		}
634 		if (rdisc_mib_sock >= 0 && FD_ISSET(rdisc_mib_sock, &ibits)) {
635 			process_d_mib_sock();
636 			n--;
637 		}
638 		if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
639 			if (read_rip() == -1) {
640 				rip_enabled = _B_FALSE;
641 				trace_off("main rip socket failed");
642 				(void) close(rip_sock);
643 				rip_sock = -1;
644 				fix_select();
645 				break;
646 			}
647 			n--;
648 		}
649 	}
650 	rip_bcast(0);
651 	rdisc_adv(_B_FALSE);
652 	(void) unlink(PATH_PID);
653 	return (stopint | 128);
654 }
655 
656 
657 static void
658 sigalrm(int sig)
659 {
660 	/*
661 	 * Historically, SIGALRM would cause the daemon to check for
662 	 * new and broken interfaces.
663 	 */
664 	ifscan_timer.tv_sec = now.tv_sec;
665 	trace_act("SIGALRM");
666 	if (signal(sig, sigalrm) == SIG_ERR)
667 		msglog("signal: %s", rip_strerror(errno));
668 }
669 
670 
671 /* watch for fatal signals */
672 static void
673 sigterm(int sig)
674 {
675 	stopint = sig;
676 	if (signal(sig, SIG_DFL) == SIG_ERR)	/* catch it only once */
677 		msglog("signal: %s", rip_strerror(errno));
678 }
679 
680 
681 void
682 fix_select(void)
683 {
684 	(void) FD_ZERO(&fdbits);
685 	sock_max = 0;
686 
687 	FD_SET(rt_sock, &fdbits);
688 	if (sock_max <= rt_sock)
689 		sock_max = rt_sock+1;
690 	if (rip_sock >= 0) {
691 		FD_SET(rip_sock, &fdbits);
692 		if (sock_max <= rip_sock)
693 			sock_max = rip_sock+1;
694 	}
695 	if (rdisc_sock >= 0) {
696 		FD_SET(rdisc_sock, &fdbits);
697 		if (sock_max <= rdisc_sock)
698 			sock_max = rdisc_sock+1;
699 		FD_SET(rdisc_mib_sock, &fdbits);
700 		if (sock_max <= rdisc_mib_sock)
701 			sock_max = rdisc_mib_sock+1;
702 	}
703 }
704 
705 
706 void
707 fix_sock(int sock,
708     const char *name)
709 {
710 	int on;
711 #define	MIN_SOCKBUF (4*1024)
712 	static int rbuf;
713 
714 	if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
715 		logbad(_B_TRUE, "fcntl(%s) O_NONBLOCK: %s", name,
716 		    rip_strerror(errno));
717 	on = 1;
718 	if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on)) < 0)
719 		msglog("setsockopt(%s,SO_BROADCAST): %s",
720 		    name, rip_strerror(errno));
721 
722 	if (rbuf >= MIN_SOCKBUF) {
723 		if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
724 		    &rbuf, sizeof (rbuf)) < 0)
725 			msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
726 			    name, rbuf, rip_strerror(errno));
727 	} else {
728 		for (rbuf = 60*1024; ; rbuf -= 4096) {
729 			if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
730 			    &rbuf, sizeof (rbuf)) == 0) {
731 				trace_act("RCVBUF=%d", rbuf);
732 				break;
733 			}
734 			if (rbuf < MIN_SOCKBUF) {
735 				msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
736 				    name, rbuf, rip_strerror(errno));
737 				break;
738 			}
739 		}
740 	}
741 }
742 
743 
744 /*
745  * Open and return the global rip socket.  It is guaranteed to return
746  * a good file descriptor.
747  */
748 static int
749 open_rip_sock()
750 {
751 	struct sockaddr_in sin;
752 	unsigned char ttl;
753 	int s;
754 	int on = 1;
755 
756 
757 	if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
758 		BADERR(_B_TRUE, "rip_sock = socket()");
759 
760 	(void) memset(&sin, 0, sizeof (sin));
761 	sin.sin_family = AF_INET;
762 	sin.sin_port = htons(RIP_PORT);
763 	sin.sin_addr.s_addr = INADDR_ANY;
764 	if (bind(s, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
765 		BADERR(_B_FALSE, "bind(rip_sock)");
766 	}
767 	fix_sock(s, "rip_sock");
768 
769 	ttl = 1;
770 	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
771 	    &ttl, sizeof (ttl)) < 0)
772 		DBGERR(_B_TRUE, "rip_sock setsockopt(IP_MULTICAST_TTL)");
773 
774 	if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &on, sizeof (on)))
775 		BADERR(_B_FALSE, "setsockopt(IP_RECVIF)");
776 
777 	return (s);
778 }
779 
780 
781 /*
782  * Disable RIP.  Note that we don't close the global rip socket since
783  * it is used even when RIP is disabled to receive and answer certain
784  * queries.
785  */
786 void
787 rip_off(void)
788 {
789 	struct ip_mreq m;
790 	struct interface *ifp;
791 	char addrstr[INET_ADDRSTRLEN];
792 
793 	if (rip_enabled && !mhome) {
794 		trace_act("turn off RIP");
795 
796 		/*
797 		 * Unsubscribe from the 224.0.0.9  RIP multicast
798 		 * group address
799 		 */
800 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
801 			if ((ifp->int_if_flags & IFF_MULTICAST) &&
802 			    !IS_IFF_QUIET(ifp->int_if_flags) &&
803 			    !IS_RIP_IN_OFF(ifp->int_state) &&
804 			    !(ifp->int_state & IS_DUP)) {
805 				m.imr_multiaddr.s_addr =
806 				    htonl(INADDR_RIP_GROUP);
807 				m.imr_interface.s_addr =
808 				    (ifp->int_if_flags & IFF_POINTOPOINT) ?
809 				    ifp->int_dstaddr : ifp->int_addr;
810 				(void) strlcpy(addrstr,
811 				    inet_ntoa(m.imr_multiaddr),
812 				    sizeof (addrstr));
813 				if (setsockopt(rip_sock, IPPROTO_IP,
814 				    IP_DROP_MEMBERSHIP, &m,
815 				    sizeof (m)) < 0 &&
816 				    errno != EADDRNOTAVAIL && errno != ENOENT)
817 					writelog(LOG_WARNING,
818 					    "%s: setsockopt(IP_DROP_MEMBERSHIP "
819 					    "%s, %s): %s", ifp->int_name,
820 					    addrstr, inet_ntoa(m.imr_interface),
821 					    rip_strerror(errno));
822 			}
823 		}
824 		rip_enabled = _B_FALSE;
825 
826 		age(0);
827 	}
828 }
829 
830 
831 /* turn on RIP multicast input via an interface */
832 void
833 rip_mcast_on(struct interface *ifp)
834 {
835 	struct ip_mreq m;
836 
837 	if (!IS_RIP_IN_OFF(ifp->int_state) &&
838 	    (ifp->int_if_flags & IFF_MULTICAST) &&
839 	    !IS_IFF_QUIET(ifp->int_if_flags) &&
840 	    !(ifp->int_state & IS_DUP)) {
841 		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
842 		m.imr_interface.s_addr = (ifp->int_if_flags & IFF_POINTOPOINT) ?
843 		    ifp->int_dstaddr : ifp->int_addr;
844 		if ((setsockopt(rip_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
845 		    &m, sizeof (m)) < 0) && !(ifp->int_state & IS_BROKE))
846 			writelog(LOG_WARNING,
847 			    "Could not join 224.0.0.9 on interface %s: %s",
848 			    ifp->int_name, rip_strerror(errno));
849 	}
850 }
851 
852 /* turn off RIP multicast input via an interface */
853 void
854 rip_mcast_off(struct interface *ifp)
855 {
856 	struct ip_mreq m;
857 
858 	if ((ifp->int_if_flags & IFF_MULTICAST) &&
859 	    !IS_IFF_QUIET(ifp->int_if_flags) && rip_enabled) {
860 		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
861 		m.imr_interface.s_addr = (ifp->int_if_flags & IFF_POINTOPOINT) ?
862 		    ifp->int_dstaddr : ifp->int_addr;
863 		if ((setsockopt(rip_sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,
864 		    &m, sizeof (m)) < 0) && errno != EADDRNOTAVAIL &&
865 		    errno != ENOENT)
866 			writelog(LOG_WARNING,
867 			    "setsockopt(IP_DROP_MEMBERSHIP RIP) for %s: %s",
868 			    ifp->int_name, rip_strerror(errno));
869 	}
870 }
871 
872 /* enable RIP */
873 void
874 rip_on(struct interface *ifp)
875 {
876 	/*
877 	 * If RIP is already enabled, only start receiving
878 	 * multicasts for this interface.
879 	 */
880 	if (rip_enabled) {
881 		if (ifp != NULL)
882 			rip_mcast_on(ifp);
883 		return;
884 	}
885 
886 	/*
887 	 * If RIP is disabled and it makes sense to enable it, then enable
888 	 * it on all of the interfaces.  It makes sense if either router
889 	 * discovery is off, or if router discovery is on and at most one
890 	 * interface is doing RIP.
891 	 */
892 	if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
893 		trace_act("turn on RIP");
894 
895 		rip_enabled = _B_TRUE;
896 		rip_sock_interface = NULL;
897 
898 		/* Do not advertise anything until we have heard something */
899 		if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
900 			next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
901 
902 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
903 			ifp->int_query_time = NEVER;
904 			rip_mcast_on(ifp);
905 		}
906 		ifscan_timer.tv_sec = now.tv_sec;
907 	}
908 
909 	fix_select();
910 }
911 
912 
913 /* die if malloc(3) fails */
914 void *
915 rtmalloc(size_t size,
916     const char *msg)
917 {
918 	void *p = malloc(size);
919 	if (p == NULL)
920 		logbad(_B_TRUE, "malloc(%lu) failed in %s: %s", (ulong_t)size,
921 		    msg, rip_strerror(errno));
922 	return (p);
923 }
924 
925 
926 /* get a random instant in an interval */
927 void
928 intvl_random(struct timeval *tp,	/* put value here */
929     ulong_t lo,			/* value is after this second */
930     ulong_t hi)			/* and before this */
931 {
932 	tp->tv_sec = (time_t)(hi == lo ? lo : (lo + random() % ((hi - lo))));
933 	tp->tv_usec = random() % 1000000;
934 }
935 
936 
937 void
938 timevaladd(struct timeval *t1,
939     struct timeval *t2)
940 {
941 
942 	t1->tv_sec += t2->tv_sec;
943 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
944 		t1->tv_sec++;
945 		t1->tv_usec -= 1000000;
946 	}
947 }
948 
949 
950 /* t1 = t2 - t3 */
951 static void
952 timevalsub(struct timeval *t1,
953     struct timeval *t2,
954     struct timeval *t3)
955 {
956 	t1->tv_sec = t2->tv_sec - t3->tv_sec;
957 	if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
958 		t1->tv_sec--;
959 		t1->tv_usec += 1000000;
960 	}
961 }
962 
963 static void
964 do_openlog(void)
965 {
966 	openlog_done = _B_TRUE;
967 	openlog("in.routed", LOG_PID | LOG_ODELAY, LOG_DAEMON);
968 }
969 
970 /* put a LOG_ERR message into the system log */
971 void
972 msglog(const char *p, ...)
973 {
974 	va_list args;
975 
976 	trace_flush();
977 
978 	if (!openlog_done)
979 		do_openlog();
980 	va_start(args, p);
981 	vsyslog(LOG_ERR, p, args);
982 
983 	if (ftrace != 0) {
984 		if (ftrace == stdout)
985 			(void) fputs("in.routed: ", ftrace);
986 		(void) vfprintf(ftrace, p, args);
987 		(void) fputc('\n', ftrace);
988 	}
989 }
990 
991 
992 /*
993  * Put a message about a bad system into the system log if
994  * we have not complained about it recently.
995  *
996  * It is desirable to complain about all bad systems, but not too often.
997  * In the worst case, it is not practical to keep track of all bad systems.
998  * For example, there can be many systems with the wrong password.
999  */
1000 void
1001 msglim(struct msg_limit *lim, in_addr_t addr, const char *p, ...)
1002 {
1003 	va_list args;
1004 	int i;
1005 	struct msg_sub *ms1, *ms;
1006 	const char *p1;
1007 
1008 	va_start(args, p);
1009 
1010 	/*
1011 	 * look for the oldest slot in the table
1012 	 * or the slot for the bad router.
1013 	 */
1014 	ms = ms1 = lim->subs;
1015 	for (i = MSG_SUBJECT_N; ; i--, ms1++) {
1016 		if (i == 0) {
1017 			/* Reuse a slot at most once every 10 minutes. */
1018 			if (lim->reuse > now.tv_sec) {
1019 				ms = NULL;
1020 			} else {
1021 				lim->reuse = now.tv_sec + 10*60;
1022 			}
1023 			break;
1024 		}
1025 		if (ms->addr == addr) {
1026 			/*
1027 			 * Repeat a complaint about a given system at
1028 			 * most once an hour.
1029 			 */
1030 			if (ms->until > now.tv_sec)
1031 				ms = NULL;
1032 			break;
1033 		}
1034 		if (ms->until < ms1->until)
1035 			ms = ms1;
1036 	}
1037 	if (ms != NULL) {
1038 		ms->addr = addr;
1039 		ms->until = now.tv_sec + 60*60;	/* 60 minutes */
1040 
1041 		if (!openlog_done)
1042 			do_openlog();
1043 		trace_flush();
1044 		for (p1 = p; *p1 == ' '; p1++)
1045 			continue;
1046 		vsyslog(LOG_ERR, p1, args);
1047 	}
1048 
1049 	/* always display the message if tracing */
1050 	if (ftrace != 0) {
1051 		(void) vfprintf(ftrace, p, args);
1052 		(void) fputc('\n', ftrace);
1053 	}
1054 }
1055 
1056 
1057 void
1058 logbad(boolean_t dump, const char *p, ...)
1059 {
1060 	va_list args;
1061 
1062 	trace_flush();
1063 
1064 	if (!openlog_done)
1065 		do_openlog();
1066 	va_start(args, p);
1067 	vsyslog(LOG_ERR, p, args);
1068 
1069 	(void) fputs(gettext("in.routed: "), stderr);
1070 	(void) vfprintf(stderr, p, args);
1071 	(void) fputs(gettext("; giving up\n"), stderr);
1072 	(void) fflush(stderr);
1073 
1074 	if (dump)
1075 		abort();
1076 	exit(EXIT_FAILURE);
1077 }
1078 
1079 /* put a message into the system log */
1080 void
1081 writelog(int level, const char *p, ...)
1082 {
1083 	va_list args;
1084 
1085 	trace_flush();
1086 
1087 	if (!openlog_done)
1088 		do_openlog();
1089 	va_start(args, p);
1090 	vsyslog(level, p, args);
1091 
1092 	if (ftrace != 0) {
1093 		if (ftrace == stdout)
1094 			(void) fputs("in.routed: ", ftrace);
1095 		(void) vfprintf(ftrace, p, args);
1096 		(void) fputc('\n', ftrace);
1097 	}
1098 }
1099