xref: /freebsd/sbin/routed/main.c (revision 3193579b66fd7067f898dbc54bdea81a0e6f9bd0)
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgment:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD$
34  */
35 
36 #include "defs.h"
37 #include "pathnames.h"
38 #ifdef sgi
39 #include "math.h"
40 #endif
41 #include <signal.h>
42 #include <fcntl.h>
43 #include <sys/file.h>
44 
45 #if !defined(sgi) && !defined(__NetBSD__)
46 char copyright[] =
47 "@(#) Copyright (c) 1983, 1988, 1993\n\
48 	The Regents of the University of California.  All rights reserved.\n";
49 static char sccsid[] __attribute__((unused)) = "@(#)main.c	8.1 (Berkeley) 6/5/93";
50 #elif defined(__NetBSD__)
51 __RCSID("$NetBSD$");
52 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\n\
53 	The Regents of the University of California.  All rights reserved.\n");
54 #endif
55 #ident "$FreeBSD$"
56 
57 
58 pid_t	mypid;
59 
60 naddr	myaddr;				/* system address */
61 char	myname[MAXHOSTNAMELEN+1];
62 
63 int	verbose;
64 
65 int	supplier;			/* supply or broadcast updates */
66 int	supplier_set;
67 int	ipforwarding = 1;		/* kernel forwarding on */
68 
69 int	default_gateway;		/* 1=advertise default */
70 int	background = 1;
71 int	ridhosts;			/* 1=reduce host routes */
72 int	mhome;				/* 1=want multi-homed host route */
73 int	advertise_mhome;		/* 1=must continue advertising it */
74 int	auth_ok = 1;			/* 1=ignore auth if we do not care */
75 
76 struct timeval epoch;			/* when started */
77 struct timeval clk, prev_clk;
78 static int usec_fudge;
79 struct timeval now;			/* current idea of time */
80 time_t	now_stale;
81 time_t	now_expire;
82 time_t	now_garbage;
83 
84 struct timeval next_bcast;		/* next general broadcast */
85 struct timeval no_flash = {		/* inhibit flash update */
86 	EPOCH+SUPPLY_INTERVAL, 0
87 };
88 
89 struct timeval flush_kern_timer;
90 
91 fd_set	fdbits;
92 int	sock_max;
93 int	rip_sock = -1;			/* RIP socket */
94 struct interface *rip_sock_mcast;	/* current multicast interface */
95 int	rt_sock;			/* routing socket */
96 int	rt_sock_seqno;
97 
98 
99 static  int get_rip_sock(naddr, int);
100 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
101 
102 int
103 main(int argc,
104      char *argv[])
105 {
106 	int n, mib[4], off;
107 	size_t len;
108 	char *p, *q;
109 	const char *cp;
110 	struct timeval wtime, t2;
111 	time_t dt;
112 	fd_set ibits;
113 	naddr p_net, p_mask;
114 	struct interface *ifp;
115 	struct parm parm;
116 	char *tracename = 0;
117 
118 
119 	/* Some shells are badly broken and send SIGHUP to backgrounded
120 	 * processes.
121 	 */
122 	signal(SIGHUP, SIG_IGN);
123 
124 	openlog("routed", LOG_PID | LOG_ODELAY, LOG_DAEMON);
125 	ftrace = stdout;
126 
127 	gettimeofday(&clk, 0);
128 	prev_clk = clk;
129 	epoch = clk;
130 	epoch.tv_sec -= EPOCH;
131 	now.tv_sec = EPOCH;
132 	now_stale = EPOCH - STALE_TIME;
133 	now_expire = EPOCH - EXPIRE_TIME;
134 	now_garbage = EPOCH - GARBAGE_TIME;
135 	wtime.tv_sec = 0;
136 
137 	(void)gethostname(myname, sizeof(myname)-1);
138 	(void)gethost(myname, &myaddr);
139 
140 	while ((n = getopt(argc, argv, "sqdghmpAtvT:F:P:")) != -1) {
141 		switch (n) {
142 		case 's':
143 			supplier = 1;
144 			supplier_set = 1;
145 			break;
146 
147 		case 'q':
148 			supplier = 0;
149 			supplier_set = 1;
150 			break;
151 
152 		case 'd':
153 			background = 0;
154 			break;
155 
156 		case 'g':
157 			memset(&parm, 0, sizeof(parm));
158 			parm.parm_d_metric = 1;
159 			cp = check_parms(&parm);
160 			if (cp != 0)
161 				msglog("bad -g: %s", cp);
162 			else
163 				default_gateway = 1;
164 			break;
165 
166 		case 'h':		/* suppress extra host routes */
167 			ridhosts = 1;
168 			break;
169 
170 		case 'm':		/* advertise host route */
171 			mhome = 1;	/* on multi-homed hosts */
172 			break;
173 
174 		case 'A':
175 			/* Ignore authentication if we do not care.
176 			 * Crazy as it is, that is what RFC 1723 requires.
177 			 */
178 			auth_ok = 0;
179 			break;
180 
181 		case 't':
182 			new_tracelevel++;
183 			break;
184 
185 		case 'T':
186 			tracename = optarg;
187 			break;
188 
189 		case 'F':		/* minimal routes for SLIP */
190 			n = FAKE_METRIC;
191 			p = strchr(optarg,',');
192 			if (p && *p != '\0') {
193 				n = (int)strtoul(p+1, &q, 0);
194 				if (*q == '\0'
195 				    && n <= HOPCNT_INFINITY-1
196 				    && n >= 1)
197 					*p = '\0';
198 			}
199 			if (!getnet(optarg, &p_net, &p_mask)) {
200 				msglog("bad network; \"-F %s\"",
201 				       optarg);
202 				break;
203 			}
204 			memset(&parm, 0, sizeof(parm));
205 			parm.parm_net = p_net;
206 			parm.parm_mask = p_mask;
207 			parm.parm_d_metric = n;
208 			cp = check_parms(&parm);
209 			if (cp != 0)
210 				msglog("bad -F: %s", cp);
211 			break;
212 
213 		case 'P':
214 			/* handle arbitrary parameters.
215 			 */
216 			q = strdup(optarg);
217 			cp = parse_parms(q, 0);
218 			if (cp != 0)
219 				msglog("%s in \"-P %s\"", cp, optarg);
220 			free(q);
221 			break;
222 
223 		case 'v':
224 			/* display version */
225 			verbose++;
226 			msglog("version 2.22");
227 			break;
228 
229 		default:
230 			goto usage;
231 		}
232 	}
233 	argc -= optind;
234 	argv += optind;
235 
236 	if (tracename == 0 && argc >= 1) {
237 		tracename = *argv++;
238 		argc--;
239 	}
240 	if (tracename != 0 && tracename[0] == '\0')
241 		goto usage;
242 	if (argc != 0) {
243 usage:
244 		logbad(0, "usage: routed [-sqdghmpAtv] [-T tracefile]"
245 		       " [-F net[,metric]] [-P parms]");
246 	}
247 	if (geteuid() != 0) {
248 		if (verbose)
249 			exit(0);
250 		logbad(0, "requires UID 0");
251 	}
252 
253 	mib[0] = CTL_NET;
254 	mib[1] = PF_INET;
255 	mib[2] = IPPROTO_IP;
256 	mib[3] = IPCTL_FORWARDING;
257 	len = sizeof(ipforwarding);
258 	if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
259 		LOGERR("sysctl(IPCTL_FORWARDING)");
260 
261 	if (!ipforwarding) {
262 		if (supplier)
263 			msglog("-s incompatible with ipforwarding=0");
264 		if (default_gateway) {
265 			msglog("-g incompatible with ipforwarding=0");
266 			default_gateway = 0;
267 		}
268 		supplier = 0;
269 		supplier_set = 1;
270 	}
271 	if (default_gateway) {
272 		if (supplier_set && !supplier) {
273 			msglog("-g and -q incompatible");
274 		} else {
275 			supplier = 1;
276 			supplier_set = 1;
277 		}
278 	}
279 
280 
281 	signal(SIGALRM, sigalrm);
282 	if (!background)
283 		signal(SIGHUP, sigterm);    /* SIGHUP fatal during debugging */
284 	signal(SIGTERM, sigterm);
285 	signal(SIGINT, sigterm);
286 	signal(SIGUSR1, sigtrace_on);
287 	signal(SIGUSR2, sigtrace_off);
288 
289 	/* get into the background */
290 #ifdef sgi
291 	if (0 > _daemonize(background ? 0 : (_DF_NOCHDIR|_DF_NOFORK),
292 			   STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO))
293 		BADERR(0, "_daemonize()");
294 #else
295 	if (background && daemon(0, 1) < 0)
296 		BADERR(0,"daemon()");
297 #endif
298 
299 	mypid = getpid();
300 #ifdef __FreeBSD__
301 	srandomdev();
302 #else
303 	srandom((int)(clk.tv_sec ^ clk.tv_usec ^ mypid));
304 #endif
305 
306 	/* prepare socket connected to the kernel.
307 	 */
308 	rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
309 	if (rt_sock < 0)
310 		BADERR(1,"rt_sock = socket()");
311 	if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
312 		logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno));
313 	off = 0;
314 	if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
315 		       &off,sizeof(off)) < 0)
316 		LOGERR("setsockopt(SO_USELOOPBACK,0)");
317 
318 	fix_select();
319 
320 
321 	if (tracename != 0) {
322 		strncpy(inittracename, tracename, sizeof(inittracename)-1);
323 		set_tracefile(inittracename, "%s", -1);
324 	} else {
325 		tracelevel_msg("%s", -1);   /* turn on tracing to stdio */
326 	}
327 
328 	bufinit();
329 
330 	/* initialize radix tree */
331 	rtinit();
332 
333 	/* Pick a random part of the second for our output to minimize
334 	 * collisions.
335 	 *
336 	 * Start broadcasting after hearing from other routers, and
337 	 * at a random time so a bunch of systems do not get synchronized
338 	 * after a power failure.
339 	 */
340 	intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
341 	age_timer.tv_usec = next_bcast.tv_usec;
342 	age_timer.tv_sec = EPOCH+MIN_WAITTIME;
343 	rdisc_timer = next_bcast;
344 	ifinit_timer.tv_usec = next_bcast.tv_usec;
345 
346 	/* Collect an initial view of the world by checking the interface
347 	 * configuration and the kludge file.
348 	 */
349 	gwkludge();
350 	ifinit();
351 
352 	/* Ask for routes */
353 	rip_query();
354 	rdisc_sol();
355 
356 	/* Now turn off stdio if not tracing */
357 	if (new_tracelevel == 0)
358 		trace_close(background);
359 
360 	/* Loop forever, listening and broadcasting.
361 	 */
362 	for (;;) {
363 		prev_clk = clk;
364 		gettimeofday(&clk, 0);
365 		if (prev_clk.tv_sec == clk.tv_sec
366 		    && prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
367 			/* Much of `routed` depends on time always advancing.
368 			 * On systems that do not guarantee that gettimeofday()
369 			 * produces unique timestamps even if called within
370 			 * a single tick, use trickery like that in classic
371 			 * BSD kernels.
372 			 */
373 			clk.tv_usec += ++usec_fudge;
374 
375 		} else {
376 			usec_fudge = 0;
377 
378 			timevalsub(&t2, &clk, &prev_clk);
379 			if (t2.tv_sec < 0
380 			    || t2.tv_sec > wtime.tv_sec + 5) {
381 				/* Deal with time changes before other
382 				 * housekeeping to keep everything straight.
383 				 */
384 				dt = t2.tv_sec;
385 				if (dt > 0)
386 					dt -= wtime.tv_sec;
387 				trace_act("time changed by %d sec", (int)dt);
388 				epoch.tv_sec += dt;
389 			}
390 		}
391 		timevalsub(&now, &clk, &epoch);
392 		now_stale = now.tv_sec - STALE_TIME;
393 		now_expire = now.tv_sec - EXPIRE_TIME;
394 		now_garbage = now.tv_sec - GARBAGE_TIME;
395 
396 		/* deal with signals that should affect tracing */
397 		set_tracelevel();
398 
399 		if (stopint != 0) {
400 			rip_bcast(0);
401 			rdisc_adv();
402 			trace_off("exiting with signal %d", stopint);
403 			exit(stopint | 128);
404 		}
405 
406 		/* look for new or dead interfaces */
407 		timevalsub(&wtime, &ifinit_timer, &now);
408 		if (wtime.tv_sec <= 0) {
409 			wtime.tv_sec = 0;
410 			ifinit();
411 			rip_query();
412 			continue;
413 		}
414 
415 		/* Check the kernel table occassionally for mysteriously
416 		 * evaporated routes
417 		 */
418 		timevalsub(&t2, &flush_kern_timer, &now);
419 		if (t2.tv_sec <= 0) {
420 			flush_kern();
421 			flush_kern_timer.tv_sec = (now.tv_sec
422 						   + CHECK_QUIET_INTERVAL);
423 			continue;
424 		}
425 		if (timercmp(&t2, &wtime, <))
426 			wtime = t2;
427 
428 		/* If it is time, then broadcast our routes.
429 		 */
430 		if (supplier || advertise_mhome) {
431 			timevalsub(&t2, &next_bcast, &now);
432 			if (t2.tv_sec <= 0) {
433 				/* Synchronize the aging and broadcast
434 				 * timers to minimize awakenings
435 				 */
436 				age(0);
437 
438 				rip_bcast(0);
439 
440 				/* It is desirable to send routing updates
441 				 * regularly.  So schedule the next update
442 				 * 30 seconds after the previous one was
443 				 * scheduled, instead of 30 seconds after
444 				 * the previous update was finished.
445 				 * Even if we just started after discovering
446 				 * a 2nd interface or were otherwise delayed,
447 				 * pick a 30-second aniversary of the
448 				 * original broadcast time.
449 				 */
450 				n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
451 				next_bcast.tv_sec += n*SUPPLY_INTERVAL;
452 
453 				continue;
454 			}
455 
456 			if (timercmp(&t2, &wtime, <))
457 				wtime = t2;
458 		}
459 
460 		/* If we need a flash update, either do it now or
461 		 * set the delay to end when it is time.
462 		 *
463 		 * If we are within MIN_WAITTIME seconds of a full update,
464 		 * do not bother.
465 		 */
466 		if (need_flash
467 		    && supplier
468 		    && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
469 			/* accurate to the millisecond */
470 			if (!timercmp(&no_flash, &now, >))
471 				rip_bcast(1);
472 			timevalsub(&t2, &no_flash, &now);
473 			if (timercmp(&t2, &wtime, <))
474 				wtime = t2;
475 		}
476 
477 		/* trigger the main aging timer.
478 		 */
479 		timevalsub(&t2, &age_timer, &now);
480 		if (t2.tv_sec <= 0) {
481 			age(0);
482 			continue;
483 		}
484 		if (timercmp(&t2, &wtime, <))
485 			wtime = t2;
486 
487 		/* update the kernel routing table
488 		 */
489 		timevalsub(&t2, &need_kern, &now);
490 		if (t2.tv_sec <= 0) {
491 			age(0);
492 			continue;
493 		}
494 		if (timercmp(&t2, &wtime, <))
495 			wtime = t2;
496 
497 		/* take care of router discovery,
498 		 * but do it in the correct the millisecond
499 		 */
500 		if (!timercmp(&rdisc_timer, &now, >)) {
501 			rdisc_age(0);
502 			continue;
503 		}
504 		timevalsub(&t2, &rdisc_timer, &now);
505 		if (timercmp(&t2, &wtime, <))
506 			wtime = t2;
507 
508 
509 		/* wait for input or a timer to expire.
510 		 */
511 		trace_flush();
512 		ibits = fdbits;
513 		n = select(sock_max, &ibits, 0, 0, &wtime);
514 		if (n <= 0) {
515 			if (n < 0 && errno != EINTR && errno != EAGAIN)
516 				BADERR(1,"select");
517 			continue;
518 		}
519 
520 		if (FD_ISSET(rt_sock, &ibits)) {
521 			read_rt();
522 			n--;
523 		}
524 		if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
525 			read_d();
526 			n--;
527 		}
528 		if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
529 			read_rip(rip_sock, 0);
530 			n--;
531 		}
532 
533 		for (ifp = ifnet; n > 0 && 0 != ifp; ifp = ifp->int_next) {
534 			if (ifp->int_rip_sock >= 0
535 			    && FD_ISSET(ifp->int_rip_sock, &ibits)) {
536 				read_rip(ifp->int_rip_sock, ifp);
537 				n--;
538 			}
539 		}
540 	}
541 }
542 
543 
544 /* ARGSUSED */
545 void
546 sigalrm(int s UNUSED)
547 {
548 	/* Historically, SIGALRM would cause the daemon to check for
549 	 * new and broken interfaces.
550 	 */
551 	ifinit_timer.tv_sec = now.tv_sec;
552 	trace_act("SIGALRM");
553 }
554 
555 
556 /* watch for fatal signals */
557 void
558 sigterm(int sig)
559 {
560 	stopint = sig;
561 	(void)signal(sig, SIG_DFL);	/* catch it only once */
562 }
563 
564 
565 void
566 fix_select(void)
567 {
568 	struct interface *ifp;
569 
570 
571 	FD_ZERO(&fdbits);
572 	sock_max = 0;
573 
574 	FD_SET(rt_sock, &fdbits);
575 	if (sock_max <= rt_sock)
576 		sock_max = rt_sock+1;
577 	if (rip_sock >= 0) {
578 		FD_SET(rip_sock, &fdbits);
579 		if (sock_max <= rip_sock)
580 			sock_max = rip_sock+1;
581 	}
582 	for (ifp = ifnet; 0 != ifp; ifp = ifp->int_next) {
583 		if (ifp->int_rip_sock >= 0) {
584 			FD_SET(ifp->int_rip_sock, &fdbits);
585 			if (sock_max <= ifp->int_rip_sock)
586 				sock_max = ifp->int_rip_sock+1;
587 		}
588 	}
589 	if (rdisc_sock >= 0) {
590 		FD_SET(rdisc_sock, &fdbits);
591 		if (sock_max <= rdisc_sock)
592 			sock_max = rdisc_sock+1;
593 	}
594 }
595 
596 
597 void
598 fix_sock(int sock,
599 	 const char *name)
600 {
601 	int on;
602 #define MIN_SOCKBUF (4*1024)
603 	static int rbuf;
604 
605 	if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
606 		logbad(1, "fcntl(%s) O_NONBLOCK: %s",
607 		       name, strerror(errno));
608 	on = 1;
609 	if (setsockopt(sock, SOL_SOCKET,SO_BROADCAST, &on,sizeof(on)) < 0)
610 		msglog("setsockopt(%s,SO_BROADCAST): %s",
611 		       name, strerror(errno));
612 #ifdef USE_PASSIFNAME
613 	on = 1;
614 	if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
615 		msglog("setsockopt(%s,SO_PASSIFNAME): %s",
616 		       name, strerror(errno));
617 #endif
618 
619 	if (rbuf >= MIN_SOCKBUF) {
620 		if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
621 			       &rbuf, sizeof(rbuf)) < 0)
622 			msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
623 			       name, rbuf, strerror(errno));
624 	} else {
625 		for (rbuf = 60*1024; ; rbuf -= 4096) {
626 			if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
627 				       &rbuf, sizeof(rbuf)) == 0) {
628 				trace_act("RCVBUF=%d", rbuf);
629 				break;
630 			}
631 			if (rbuf < MIN_SOCKBUF) {
632 				msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
633 				       name, rbuf, strerror(errno));
634 				break;
635 			}
636 		}
637 	}
638 }
639 
640 
641 /* get a rip socket
642  */
643 static int				/* <0 or file descriptor */
644 get_rip_sock(naddr addr,
645 	     int serious)		/* 1=failure to bind is serious */
646 {
647 	struct sockaddr_in sin;
648 	unsigned char ttl;
649 	int s;
650 
651 
652 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
653 		BADERR(1,"rip_sock = socket()");
654 
655 	memset(&sin, 0, sizeof(sin));
656 #ifdef _HAVE_SIN_LEN
657 	sin.sin_len = sizeof(sin);
658 #endif
659 	sin.sin_family = AF_INET;
660 	sin.sin_port = htons(RIP_PORT);
661 	sin.sin_addr.s_addr = addr;
662 	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
663 		if (serious)
664 			BADERR(errno != EADDRINUSE, "bind(rip_sock)");
665 		return -1;
666 	}
667 	fix_sock(s,"rip_sock");
668 
669 	ttl = 1;
670 	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
671 		       &ttl, sizeof(ttl)) < 0)
672 		DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
673 
674 	return s;
675 }
676 
677 
678 /* turn off main RIP socket */
679 void
680 rip_off(void)
681 {
682 	struct interface *ifp;
683 	naddr addr;
684 
685 
686 	if (rip_sock >= 0 && !mhome) {
687 		trace_act("turn off RIP");
688 
689 		(void)close(rip_sock);
690 		rip_sock = -1;
691 
692 		/* get non-broadcast sockets to listen to queries.
693 		 */
694 		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
695 			if (ifp->int_state & IS_REMOTE)
696 				continue;
697 			if (ifp->int_rip_sock < 0) {
698 				addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
699 					? ifp->int_dstaddr
700 					: ifp->int_addr);
701 				ifp->int_rip_sock = get_rip_sock(addr, 0);
702 			}
703 		}
704 
705 		fix_select();
706 
707 		age(0);
708 	}
709 }
710 
711 
712 /* turn on RIP multicast input via an interface
713  */
714 static void
715 rip_mcast_on(struct interface *ifp)
716 {
717 	struct ip_mreq m;
718 
719 	if (!IS_RIP_IN_OFF(ifp->int_state)
720 	    && (ifp->int_if_flags & IFF_MULTICAST)
721 #ifdef MCAST_PPP_BUG
722 	    && !(ifp->int_if_flags & IFF_POINTOPOINT)
723 #endif
724 	    && !(ifp->int_state & IS_ALIAS)) {
725 		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
726 		m.imr_interface.s_addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
727 					  ? ifp->int_dstaddr
728 					  : ifp->int_addr);
729 		if (setsockopt(rip_sock,IPPROTO_IP, IP_ADD_MEMBERSHIP,
730 			       &m, sizeof(m)) < 0)
731 			LOGERR("setsockopt(IP_ADD_MEMBERSHIP RIP)");
732 	}
733 }
734 
735 
736 /* Prepare socket used for RIP.
737  */
738 void
739 rip_on(struct interface *ifp)
740 {
741 	/* If the main RIP socket is already alive, only start receiving
742 	 * multicasts for this interface.
743 	 */
744 	if (rip_sock >= 0) {
745 		if (ifp != 0)
746 			rip_mcast_on(ifp);
747 		return;
748 	}
749 
750 	/* If the main RIP socket is off and it makes sense to turn it on,
751 	 * then turn it on for all of the interfaces.
752 	 * It makes sense if either router discovery is off, or if
753 	 * router discover is on and at most one interface is doing RIP.
754 	 */
755 	if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
756 		trace_act("turn on RIP");
757 
758 		/* Close all of the query sockets so that we can open
759 		 * the main socket.  SO_REUSEPORT is not a solution,
760 		 * since that would let two daemons bind to the broadcast
761 		 * socket.
762 		 */
763 		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
764 			if (ifp->int_rip_sock >= 0) {
765 				(void)close(ifp->int_rip_sock);
766 				ifp->int_rip_sock = -1;
767 			}
768 		}
769 
770 		rip_sock = get_rip_sock(INADDR_ANY, 1);
771 		rip_sock_mcast = 0;
772 
773 		/* Do not advertise anything until we have heard something
774 		 */
775 		if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
776 			next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
777 
778 		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
779 			ifp->int_query_time = NEVER;
780 			rip_mcast_on(ifp);
781 		}
782 		ifinit_timer.tv_sec = now.tv_sec;
783 
784 	} else if (ifp != 0
785 		   && !(ifp->int_state & IS_REMOTE)
786 		   && ifp->int_rip_sock < 0) {
787 		/* RIP is off, so ensure there are sockets on which
788 		 * to listen for queries.
789 		 */
790 		ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
791 	}
792 
793 	fix_select();
794 }
795 
796 
797 /* die if malloc(3) fails
798  */
799 void *
800 rtmalloc(size_t size,
801 	 const char *msg)
802 {
803 	void *p = malloc(size);
804 	if (p == 0)
805 		logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
806 	return p;
807 }
808 
809 
810 /* get a random instant in an interval
811  */
812 void
813 intvl_random(struct timeval *tp,	/* put value here */
814 	     u_long lo,			/* value is after this second */
815 	     u_long hi)			/* and before this */
816 {
817 	tp->tv_sec = (time_t)(hi == lo
818 			      ? lo
819 			      : (lo + random() % ((hi - lo))));
820 	tp->tv_usec = random() % 1000000;
821 }
822 
823 
824 void
825 timevaladd(struct timeval *t1,
826 	   struct timeval *t2)
827 {
828 
829 	t1->tv_sec += t2->tv_sec;
830 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
831 		t1->tv_sec++;
832 		t1->tv_usec -= 1000000;
833 	}
834 }
835 
836 
837 /* t1 = t2 - t3
838  */
839 static void
840 timevalsub(struct timeval *t1,
841 	   struct timeval *t2,
842 	   struct timeval *t3)
843 {
844 	t1->tv_sec = t2->tv_sec - t3->tv_sec;
845 	if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
846 		t1->tv_sec--;
847 		t1->tv_usec += 1000000;
848 	}
849 }
850 
851 
852 /* put a message into the system log
853  */
854 void
855 msglog(const char *p, ...)
856 {
857 	va_list args;
858 
859 	trace_flush();
860 
861 	va_start(args, p);
862 	vsyslog(LOG_ERR, p, args);
863 
864 	if (ftrace != 0) {
865 		if (ftrace == stdout)
866 			(void)fputs("routed: ", ftrace);
867 		(void)vfprintf(ftrace, p, args);
868 		(void)fputc('\n', ftrace);
869 	}
870 }
871 
872 
873 /* Put a message about a bad system into the system log if
874  * we have not complained about it recently.
875  *
876  * It is desirable to complain about all bad systems, but not too often.
877  * In the worst case, it is not practical to keep track of all bad systems.
878  * For example, there can be many systems with the wrong password.
879  */
880 void
881 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
882 {
883 	va_list args;
884 	int i;
885 	struct msg_sub *ms1, *ms;
886 	const char *p1;
887 
888 	va_start(args, p);
889 
890 	/* look for the oldest slot in the table
891 	 * or the slot for the bad router.
892 	 */
893 	ms = ms1 = lim->subs;
894 	for (i = MSG_SUBJECT_N; ; i--, ms1++) {
895 		if (i == 0) {
896 			/* Reuse a slot at most once every 10 minutes.
897 			 */
898 			if (lim->reuse > now.tv_sec) {
899 				ms = 0;
900 			} else {
901 				ms = ms1;
902 				lim->reuse = now.tv_sec + 10*60;
903 			}
904 			break;
905 		}
906 		if (ms->addr == addr) {
907 			/* Repeat a complaint about a given system at
908 			 * most once an hour.
909 			 */
910 			if (ms->until > now.tv_sec)
911 				ms = 0;
912 			break;
913 		}
914 		if (ms->until < ms1->until)
915 			ms = ms1;
916 	}
917 	if (ms != 0) {
918 		ms->addr = addr;
919 		ms->until = now.tv_sec + 60*60;	/* 60 minutes */
920 
921 		trace_flush();
922 		for (p1 = p; *p1 == ' '; p1++)
923 			continue;
924 		vsyslog(LOG_ERR, p1, args);
925 	}
926 
927 	/* always display the message if tracing */
928 	if (ftrace != 0) {
929 		(void)vfprintf(ftrace, p, args);
930 		(void)fputc('\n', ftrace);
931 	}
932 }
933 
934 
935 void
936 logbad(int dump, const char *p, ...)
937 {
938 	va_list args;
939 
940 	trace_flush();
941 
942 	va_start(args, p);
943 	vsyslog(LOG_ERR, p, args);
944 
945 	(void)fputs("routed: ", stderr);
946 	(void)vfprintf(stderr, p, args);
947 	(void)fputs("; giving up\n",stderr);
948 	(void)fflush(stderr);
949 
950 	if (dump)
951 		abort();
952 	exit(1);
953 }
954