xref: /illumos-gate/usr/src/cmd/cmd-inet/usr.sbin/in.routed/main.c (revision 7c478bd95313f5f23a4c958a745db2134aa03244)
1 /*
2  * Copyright 2004 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 (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
635 			if (read_rip() == -1) {
636 				rip_enabled = _B_FALSE;
637 				trace_off("main rip socket failed");
638 				(void) close(rip_sock);
639 				rip_sock = -1;
640 				fix_select();
641 				break;
642 			}
643 			n--;
644 		}
645 	}
646 	rip_bcast(0);
647 	rdisc_adv(_B_FALSE);
648 	(void) unlink(PATH_PID);
649 	return (stopint | 128);
650 }
651 
652 
653 static void
654 sigalrm(int sig)
655 {
656 	/*
657 	 * Historically, SIGALRM would cause the daemon to check for
658 	 * new and broken interfaces.
659 	 */
660 	ifscan_timer.tv_sec = now.tv_sec;
661 	trace_act("SIGALRM");
662 	if (signal(sig, sigalrm) == SIG_ERR)
663 		msglog("signal: %s", rip_strerror(errno));
664 }
665 
666 
667 /* watch for fatal signals */
668 static void
669 sigterm(int sig)
670 {
671 	stopint = sig;
672 	if (signal(sig, SIG_DFL) == SIG_ERR)	/* catch it only once */
673 		msglog("signal: %s", rip_strerror(errno));
674 }
675 
676 
677 void
678 fix_select(void)
679 {
680 	(void) FD_ZERO(&fdbits);
681 	sock_max = 0;
682 
683 	FD_SET(rt_sock, &fdbits);
684 	if (sock_max <= rt_sock)
685 		sock_max = rt_sock+1;
686 	if (rip_sock >= 0) {
687 		FD_SET(rip_sock, &fdbits);
688 		if (sock_max <= rip_sock)
689 			sock_max = rip_sock+1;
690 	}
691 	if (rdisc_sock >= 0) {
692 		FD_SET(rdisc_sock, &fdbits);
693 		if (sock_max <= rdisc_sock)
694 			sock_max = rdisc_sock+1;
695 	}
696 }
697 
698 
699 void
700 fix_sock(int sock,
701     const char *name)
702 {
703 	int on;
704 #define	MIN_SOCKBUF (4*1024)
705 	static int rbuf;
706 
707 	if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
708 		logbad(_B_TRUE, "fcntl(%s) O_NONBLOCK: %s", name,
709 		    rip_strerror(errno));
710 	on = 1;
711 	if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on)) < 0)
712 		msglog("setsockopt(%s,SO_BROADCAST): %s",
713 		    name, rip_strerror(errno));
714 
715 	if (rbuf >= MIN_SOCKBUF) {
716 		if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
717 		    &rbuf, sizeof (rbuf)) < 0)
718 			msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
719 			    name, rbuf, rip_strerror(errno));
720 	} else {
721 		for (rbuf = 60*1024; ; rbuf -= 4096) {
722 			if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
723 			    &rbuf, sizeof (rbuf)) == 0) {
724 				trace_act("RCVBUF=%d", rbuf);
725 				break;
726 			}
727 			if (rbuf < MIN_SOCKBUF) {
728 				msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
729 				    name, rbuf, rip_strerror(errno));
730 				break;
731 			}
732 		}
733 	}
734 }
735 
736 
737 /*
738  * Open and return the global rip socket.  It is guaranteed to return
739  * a good file descriptor.
740  */
741 static int
742 open_rip_sock()
743 {
744 	struct sockaddr_in sin;
745 	unsigned char ttl;
746 	int s;
747 	int on = 1;
748 
749 
750 	if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
751 		BADERR(_B_TRUE, "rip_sock = socket()");
752 
753 	(void) memset(&sin, 0, sizeof (sin));
754 	sin.sin_family = AF_INET;
755 	sin.sin_port = htons(RIP_PORT);
756 	sin.sin_addr.s_addr = INADDR_ANY;
757 	if (bind(s, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
758 		BADERR(_B_FALSE, "bind(rip_sock)");
759 	}
760 	fix_sock(s, "rip_sock");
761 
762 	ttl = 1;
763 	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
764 	    &ttl, sizeof (ttl)) < 0)
765 		DBGERR(_B_TRUE, "rip_sock setsockopt(IP_MULTICAST_TTL)");
766 
767 	if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &on, sizeof (on)))
768 		BADERR(_B_FALSE, "setsockopt(IP_RECVIF)");
769 
770 	return (s);
771 }
772 
773 
774 /*
775  * Disable RIP.  Note that we don't close the global rip socket since
776  * it is used even when RIP is disabled to receive and answer certain
777  * queries.
778  */
779 void
780 rip_off(void)
781 {
782 	struct ip_mreq m;
783 	struct interface *ifp;
784 	char addrstr[INET_ADDRSTRLEN];
785 
786 	if (rip_enabled && !mhome) {
787 		trace_act("turn off RIP");
788 
789 		/*
790 		 * Unsubscribe from the 224.0.0.9  RIP multicast
791 		 * group address
792 		 */
793 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
794 			if ((ifp->int_if_flags & IFF_MULTICAST) &&
795 			    !IS_IFF_QUIET(ifp->int_if_flags) &&
796 			    !IS_RIP_IN_OFF(ifp->int_state) &&
797 			    !(ifp->int_state & IS_DUP)) {
798 				m.imr_multiaddr.s_addr =
799 				    htonl(INADDR_RIP_GROUP);
800 				m.imr_interface.s_addr =
801 				    (ifp->int_if_flags & IFF_POINTOPOINT) ?
802 				    ifp->int_dstaddr : ifp->int_addr;
803 				(void) strlcpy(addrstr,
804 				    inet_ntoa(m.imr_multiaddr),
805 				    sizeof (addrstr));
806 				if (setsockopt(rip_sock, IPPROTO_IP,
807 				    IP_DROP_MEMBERSHIP, &m,
808 				    sizeof (m)) < 0 &&
809 				    errno != EADDRNOTAVAIL && errno != ENOENT)
810 					writelog(LOG_WARNING,
811 					    "%s: setsockopt(IP_DROP_MEMBERSHIP "
812 					    "%s, %s): %s", ifp->int_name,
813 					    addrstr, inet_ntoa(m.imr_interface),
814 					    rip_strerror(errno));
815 			}
816 		}
817 		rip_enabled = _B_FALSE;
818 
819 		age(0);
820 	}
821 }
822 
823 
824 /* turn on RIP multicast input via an interface */
825 void
826 rip_mcast_on(struct interface *ifp)
827 {
828 	struct ip_mreq m;
829 
830 	if (!IS_RIP_IN_OFF(ifp->int_state) &&
831 	    (ifp->int_if_flags & IFF_MULTICAST) &&
832 	    !IS_IFF_QUIET(ifp->int_if_flags) &&
833 	    !(ifp->int_state & IS_DUP)) {
834 		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
835 		m.imr_interface.s_addr = (ifp->int_if_flags & IFF_POINTOPOINT) ?
836 		    ifp->int_dstaddr : ifp->int_addr;
837 		if ((setsockopt(rip_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
838 		    &m, sizeof (m)) < 0) && !(ifp->int_state & IS_BROKE))
839 			writelog(LOG_WARNING,
840 			    "Could not join 224.0.0.9 on interface %s: %s",
841 			    ifp->int_name, rip_strerror(errno));
842 	}
843 }
844 
845 /* turn off RIP multicast input via an interface */
846 void
847 rip_mcast_off(struct interface *ifp)
848 {
849 	struct ip_mreq m;
850 
851 	if ((ifp->int_if_flags & IFF_MULTICAST) &&
852 	    !IS_IFF_QUIET(ifp->int_if_flags) && rip_enabled) {
853 		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
854 		m.imr_interface.s_addr = (ifp->int_if_flags & IFF_POINTOPOINT) ?
855 		    ifp->int_dstaddr : ifp->int_addr;
856 		if ((setsockopt(rip_sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,
857 		    &m, sizeof (m)) < 0) && errno != EADDRNOTAVAIL &&
858 		    errno != ENOENT)
859 			writelog(LOG_WARNING,
860 			    "setsockopt(IP_DROP_MEMBERSHIP RIP) for %s: %s",
861 			    ifp->int_name, rip_strerror(errno));
862 	}
863 }
864 
865 /* enable RIP */
866 void
867 rip_on(struct interface *ifp)
868 {
869 	/*
870 	 * If RIP is already enabled, only start receiving
871 	 * multicasts for this interface.
872 	 */
873 	if (rip_enabled) {
874 		if (ifp != NULL)
875 			rip_mcast_on(ifp);
876 		return;
877 	}
878 
879 	/*
880 	 * If RIP is disabled and it makes sense to enable it, then enable
881 	 * it on all of the interfaces.  It makes sense if either router
882 	 * discovery is off, or if router discovery is on and at most one
883 	 * interface is doing RIP.
884 	 */
885 	if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
886 		trace_act("turn on RIP");
887 
888 		rip_enabled = _B_TRUE;
889 		rip_sock_interface = NULL;
890 
891 		/* Do not advertise anything until we have heard something */
892 		if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
893 			next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
894 
895 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
896 			ifp->int_query_time = NEVER;
897 			rip_mcast_on(ifp);
898 		}
899 		ifscan_timer.tv_sec = now.tv_sec;
900 	}
901 
902 	fix_select();
903 }
904 
905 
906 /* die if malloc(3) fails */
907 void *
908 rtmalloc(size_t size,
909     const char *msg)
910 {
911 	void *p = malloc(size);
912 	if (p == NULL)
913 		logbad(_B_TRUE, "malloc(%lu) failed in %s: %s", (ulong_t)size,
914 		    msg, rip_strerror(errno));
915 	return (p);
916 }
917 
918 
919 /* get a random instant in an interval */
920 void
921 intvl_random(struct timeval *tp,	/* put value here */
922     ulong_t lo,			/* value is after this second */
923     ulong_t hi)			/* and before this */
924 {
925 	tp->tv_sec = (time_t)(hi == lo ? lo : (lo + random() % ((hi - lo))));
926 	tp->tv_usec = random() % 1000000;
927 }
928 
929 
930 void
931 timevaladd(struct timeval *t1,
932     struct timeval *t2)
933 {
934 
935 	t1->tv_sec += t2->tv_sec;
936 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
937 		t1->tv_sec++;
938 		t1->tv_usec -= 1000000;
939 	}
940 }
941 
942 
943 /* t1 = t2 - t3 */
944 static void
945 timevalsub(struct timeval *t1,
946     struct timeval *t2,
947     struct timeval *t3)
948 {
949 	t1->tv_sec = t2->tv_sec - t3->tv_sec;
950 	if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
951 		t1->tv_sec--;
952 		t1->tv_usec += 1000000;
953 	}
954 }
955 
956 static void
957 do_openlog(void)
958 {
959 	openlog_done = _B_TRUE;
960 	openlog("in.routed", LOG_PID | LOG_ODELAY, LOG_DAEMON);
961 }
962 
963 /* put a LOG_ERR message into the system log */
964 void
965 msglog(const char *p, ...)
966 {
967 	va_list args;
968 
969 	trace_flush();
970 
971 	if (!openlog_done)
972 		do_openlog();
973 	va_start(args, p);
974 	vsyslog(LOG_ERR, p, args);
975 
976 	if (ftrace != 0) {
977 		if (ftrace == stdout)
978 			(void) fputs("in.routed: ", ftrace);
979 		(void) vfprintf(ftrace, p, args);
980 		(void) fputc('\n', ftrace);
981 	}
982 }
983 
984 
985 /*
986  * Put a message about a bad system into the system log if
987  * we have not complained about it recently.
988  *
989  * It is desirable to complain about all bad systems, but not too often.
990  * In the worst case, it is not practical to keep track of all bad systems.
991  * For example, there can be many systems with the wrong password.
992  */
993 void
994 msglim(struct msg_limit *lim, in_addr_t addr, const char *p, ...)
995 {
996 	va_list args;
997 	int i;
998 	struct msg_sub *ms1, *ms;
999 	const char *p1;
1000 
1001 	va_start(args, p);
1002 
1003 	/*
1004 	 * look for the oldest slot in the table
1005 	 * or the slot for the bad router.
1006 	 */
1007 	ms = ms1 = lim->subs;
1008 	for (i = MSG_SUBJECT_N; ; i--, ms1++) {
1009 		if (i == 0) {
1010 			/* Reuse a slot at most once every 10 minutes. */
1011 			if (lim->reuse > now.tv_sec) {
1012 				ms = NULL;
1013 			} else {
1014 				lim->reuse = now.tv_sec + 10*60;
1015 			}
1016 			break;
1017 		}
1018 		if (ms->addr == addr) {
1019 			/*
1020 			 * Repeat a complaint about a given system at
1021 			 * most once an hour.
1022 			 */
1023 			if (ms->until > now.tv_sec)
1024 				ms = NULL;
1025 			break;
1026 		}
1027 		if (ms->until < ms1->until)
1028 			ms = ms1;
1029 	}
1030 	if (ms != NULL) {
1031 		ms->addr = addr;
1032 		ms->until = now.tv_sec + 60*60;	/* 60 minutes */
1033 
1034 		if (!openlog_done)
1035 			do_openlog();
1036 		trace_flush();
1037 		for (p1 = p; *p1 == ' '; p1++)
1038 			continue;
1039 		vsyslog(LOG_ERR, p1, args);
1040 	}
1041 
1042 	/* always display the message if tracing */
1043 	if (ftrace != 0) {
1044 		(void) vfprintf(ftrace, p, args);
1045 		(void) fputc('\n', ftrace);
1046 	}
1047 }
1048 
1049 
1050 void
1051 logbad(boolean_t dump, const char *p, ...)
1052 {
1053 	va_list args;
1054 
1055 	trace_flush();
1056 
1057 	if (!openlog_done)
1058 		do_openlog();
1059 	va_start(args, p);
1060 	vsyslog(LOG_ERR, p, args);
1061 
1062 	(void) fputs(gettext("in.routed: "), stderr);
1063 	(void) vfprintf(stderr, p, args);
1064 	(void) fputs(gettext("; giving up\n"), stderr);
1065 	(void) fflush(stderr);
1066 
1067 	if (dump)
1068 		abort();
1069 	exit(EXIT_FAILURE);
1070 }
1071 
1072 /* put a message into the system log */
1073 void
1074 writelog(int level, const char *p, ...)
1075 {
1076 	va_list args;
1077 
1078 	trace_flush();
1079 
1080 	if (!openlog_done)
1081 		do_openlog();
1082 	va_start(args, p);
1083 	vsyslog(level, p, args);
1084 
1085 	if (ftrace != 0) {
1086 		if (ftrace == stdout)
1087 			(void) fputs("in.routed: ", ftrace);
1088 		(void) vfprintf(ftrace, p, args);
1089 		(void) fputc('\n', ftrace);
1090 	}
1091 }
1092