xref: /freebsd/sbin/routed/main.c (revision 2546665afcaf0d53dc2c7058fee96354b3680f5a)
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include "defs.h"
33 #include "pathnames.h"
34 #ifdef sgi
35 #include "math.h"
36 #endif
37 #include <signal.h>
38 #include <fcntl.h>
39 #include <sys/file.h>
40 
41 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\n"
42 	    "The Regents of the University of California."
43 	    "  All rights reserved.\n");
44 #ifdef __NetBSD__
45 __RCSID("$NetBSD$");
46 #include <util.h>
47 #elif defined(__FreeBSD__)
48 __RCSID("$FreeBSD$");
49 #else
50 __RCSID("$Revision: 2.27 $");
51 #ident "$Revision: 2.27 $"
52 #endif
53 #ident "$FreeBSD$"
54 
55 pid_t	mypid;
56 
57 naddr	myaddr;				/* system address */
58 char	myname[MAXHOSTNAMELEN+1];
59 
60 int	verbose;
61 
62 int	supplier;			/* supply or broadcast updates */
63 int	supplier_set;
64 int	ipforwarding = 1;		/* kernel forwarding on */
65 
66 int	default_gateway;		/* 1=advertise default */
67 int	background = 1;
68 int	ridhosts;			/* 1=reduce host routes */
69 int	mhome;				/* 1=want multi-homed host route */
70 int	advertise_mhome;		/* 1=must continue advertising it */
71 int	auth_ok = 1;			/* 1=ignore auth if we do not care */
72 
73 struct timeval epoch;			/* when started */
74 struct timeval clk, prev_clk;
75 static int usec_fudge;
76 struct timeval now;			/* current idea of time */
77 time_t	now_stale;
78 time_t	now_expire;
79 time_t	now_garbage;
80 
81 struct timeval next_bcast;		/* next general broadcast */
82 struct timeval no_flash = {		/* inhibit flash update */
83 	EPOCH+SUPPLY_INTERVAL, 0
84 };
85 
86 struct timeval flush_kern_timer;
87 
88 fd_set	fdbits;
89 int	sock_max;
90 int	rip_sock = -1;			/* RIP socket */
91 struct interface *rip_sock_mcast;	/* current multicast interface */
92 int	rt_sock;			/* routing socket */
93 int	rt_sock_seqno;
94 
95 
96 static  int get_rip_sock(naddr, int);
97 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
98 
99 int
100 main(int argc,
101      char *argv[])
102 {
103 	int n, mib[4], off;
104 	size_t len;
105 	char *p, *q;
106 	const char *cp;
107 	struct timeval wtime, t2;
108 	time_t dt;
109 	fd_set ibits;
110 	naddr p_net, p_mask;
111 	struct interface *ifp;
112 	struct parm parm;
113 	char *tracename = 0;
114 
115 
116 	/* Some shells are badly broken and send SIGHUP to backgrounded
117 	 * processes.
118 	 */
119 	signal(SIGHUP, SIG_IGN);
120 
121 	openlog("routed", LOG_PID, LOG_DAEMON);
122 	ftrace = stdout;
123 
124 	gettimeofday(&clk, 0);
125 	prev_clk = clk;
126 	epoch = clk;
127 	epoch.tv_sec -= EPOCH;
128 	now.tv_sec = EPOCH;
129 	now_stale = EPOCH - STALE_TIME;
130 	now_expire = EPOCH - EXPIRE_TIME;
131 	now_garbage = EPOCH - GARBAGE_TIME;
132 	wtime.tv_sec = 0;
133 
134 	(void)gethostname(myname, sizeof(myname)-1);
135 	(void)gethost(myname, &myaddr);
136 
137 	while ((n = getopt(argc, argv, "sqdghmpAtvT:F:P:")) != -1) {
138 		switch (n) {
139 		case 's':
140 			supplier = 1;
141 			supplier_set = 1;
142 			break;
143 
144 		case 'q':
145 			supplier = 0;
146 			supplier_set = 1;
147 			break;
148 
149 		case 'd':
150 			background = 0;
151 			break;
152 
153 		case 'g':
154 			memset(&parm, 0, sizeof(parm));
155 			parm.parm_d_metric = 1;
156 			cp = check_parms(&parm);
157 			if (cp != 0)
158 				msglog("bad -g: %s", cp);
159 			else
160 				default_gateway = 1;
161 			break;
162 
163 		case 'h':		/* suppress extra host routes */
164 			ridhosts = 1;
165 			break;
166 
167 		case 'm':		/* advertise host route */
168 			mhome = 1;	/* on multi-homed hosts */
169 			break;
170 
171 		case 'A':
172 			/* Ignore authentication if we do not care.
173 			 * Crazy as it is, that is what RFC 1723 requires.
174 			 */
175 			auth_ok = 0;
176 			break;
177 
178 		case 't':
179 			new_tracelevel++;
180 			break;
181 
182 		case 'T':
183 			tracename = optarg;
184 			break;
185 
186 		case 'F':		/* minimal routes for SLIP */
187 			n = FAKE_METRIC;
188 			p = strchr(optarg,',');
189 			if (p && *p != '\0') {
190 				n = (int)strtoul(p+1, &q, 0);
191 				if (*q == '\0'
192 				    && n <= HOPCNT_INFINITY-1
193 				    && n >= 1)
194 					*p = '\0';
195 			}
196 			if (!getnet(optarg, &p_net, &p_mask)) {
197 				msglog("bad network; \"-F %s\"",
198 				       optarg);
199 				break;
200 			}
201 			memset(&parm, 0, sizeof(parm));
202 			parm.parm_net = p_net;
203 			parm.parm_mask = p_mask;
204 			parm.parm_d_metric = n;
205 			cp = check_parms(&parm);
206 			if (cp != 0)
207 				msglog("bad -F: %s", cp);
208 			break;
209 
210 		case 'P':
211 			/* handle arbitrary parameters.
212 			 */
213 			q = strdup(optarg);
214 			cp = parse_parms(q, 0);
215 			if (cp != 0)
216 				msglog("%s in \"-P %s\"", cp, optarg);
217 			free(q);
218 			break;
219 
220 		case 'v':
221 			/* display version */
222 			verbose++;
223 			msglog("version 2.25");
224 			break;
225 
226 		default:
227 			goto usage;
228 		}
229 	}
230 	argc -= optind;
231 	argv += optind;
232 
233 	if (tracename == 0 && argc >= 1) {
234 		tracename = *argv++;
235 		argc--;
236 	}
237 	if (tracename != 0 && tracename[0] == '\0')
238 		goto usage;
239 	if (argc != 0) {
240 usage:
241 		logbad(0, "usage: routed [-sqdghmpAtv] [-T tracefile]"
242 		       " [-F net[,metric]] [-P parms]");
243 	}
244 	if (geteuid() != 0) {
245 		if (verbose)
246 			exit(0);
247 		logbad(0, "requires UID 0");
248 	}
249 
250 	mib[0] = CTL_NET;
251 	mib[1] = PF_INET;
252 	mib[2] = IPPROTO_IP;
253 	mib[3] = IPCTL_FORWARDING;
254 	len = sizeof(ipforwarding);
255 	if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
256 		LOGERR("sysctl(IPCTL_FORWARDING)");
257 
258 	if (!ipforwarding) {
259 		if (supplier)
260 			msglog("-s incompatible with ipforwarding=0");
261 		if (default_gateway) {
262 			msglog("-g incompatible with ipforwarding=0");
263 			default_gateway = 0;
264 		}
265 		supplier = 0;
266 		supplier_set = 1;
267 	}
268 	if (default_gateway) {
269 		if (supplier_set && !supplier) {
270 			msglog("-g and -q incompatible");
271 		} else {
272 			supplier = 1;
273 			supplier_set = 1;
274 		}
275 	}
276 
277 
278 	signal(SIGALRM, sigalrm);
279 	if (!background)
280 		signal(SIGHUP, sigterm);    /* SIGHUP fatal during debugging */
281 	signal(SIGTERM, sigterm);
282 	signal(SIGINT, sigterm);
283 	signal(SIGUSR1, sigtrace_on);
284 	signal(SIGUSR2, sigtrace_off);
285 
286 	/* get into the background */
287 #ifdef sgi
288 	if (0 > _daemonize(background ? 0 : (_DF_NOCHDIR|_DF_NOFORK),
289 			   STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO))
290 		BADERR(0, "_daemonize()");
291 #else
292 	if (background && daemon(0, 1) < 0)
293 		BADERR(0,"daemon()");
294 #endif
295 
296 #if defined(__NetBSD__)
297 	pidfile(0);
298 #endif
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 rsin;
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(&rsin, 0, sizeof(rsin));
656 #ifdef _HAVE_SIN_LEN
657 	rsin.sin_len = sizeof(rsin);
658 #endif
659 	rsin.sin_family = AF_INET;
660 	rsin.sin_port = htons(RIP_PORT);
661 	rsin.sin_addr.s_addr = addr;
662 	if (bind(s, (struct sockaddr *)&rsin, sizeof(rsin)) < 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 #ifdef MCAST_IFINDEX
727 		m.imr_interface.s_addr = htonl(ifp->int_index);
728 #else
729 		m.imr_interface.s_addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
730 					  ? ifp->int_dstaddr
731 					  : ifp->int_addr);
732 #endif
733 		if (setsockopt(rip_sock,IPPROTO_IP, IP_ADD_MEMBERSHIP,
734 			       &m, sizeof(m)) < 0)
735 			LOGERR("setsockopt(IP_ADD_MEMBERSHIP RIP)");
736 	}
737 }
738 
739 
740 /* Prepare socket used for RIP.
741  */
742 void
743 rip_on(struct interface *ifp)
744 {
745 	/* If the main RIP socket is already alive, only start receiving
746 	 * multicasts for this interface.
747 	 */
748 	if (rip_sock >= 0) {
749 		if (ifp != 0)
750 			rip_mcast_on(ifp);
751 		return;
752 	}
753 
754 	/* If the main RIP socket is off and it makes sense to turn it on,
755 	 * then turn it on for all of the interfaces.
756 	 * It makes sense if either router discovery is off, or if
757 	 * router discover is on and at most one interface is doing RIP.
758 	 */
759 	if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
760 		trace_act("turn on RIP");
761 
762 		/* Close all of the query sockets so that we can open
763 		 * the main socket.  SO_REUSEPORT is not a solution,
764 		 * since that would let two daemons bind to the broadcast
765 		 * socket.
766 		 */
767 		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
768 			if (ifp->int_rip_sock >= 0) {
769 				(void)close(ifp->int_rip_sock);
770 				ifp->int_rip_sock = -1;
771 			}
772 		}
773 
774 		rip_sock = get_rip_sock(INADDR_ANY, 1);
775 		rip_sock_mcast = 0;
776 
777 		/* Do not advertise anything until we have heard something
778 		 */
779 		if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
780 			next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
781 
782 		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
783 			ifp->int_query_time = NEVER;
784 			rip_mcast_on(ifp);
785 		}
786 		ifinit_timer.tv_sec = now.tv_sec;
787 
788 	} else if (ifp != 0
789 		   && !(ifp->int_state & IS_REMOTE)
790 		   && ifp->int_rip_sock < 0) {
791 		/* RIP is off, so ensure there are sockets on which
792 		 * to listen for queries.
793 		 */
794 		ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
795 	}
796 
797 	fix_select();
798 }
799 
800 
801 /* die if malloc(3) fails
802  */
803 void *
804 rtmalloc(size_t size,
805 	 const char *msg)
806 {
807 	void *p = malloc(size);
808 	if (p == 0)
809 		logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
810 	return p;
811 }
812 
813 
814 /* get a random instant in an interval
815  */
816 void
817 intvl_random(struct timeval *tp,	/* put value here */
818 	     u_long lo,			/* value is after this second */
819 	     u_long hi)			/* and before this */
820 {
821 	tp->tv_sec = (time_t)(hi == lo
822 			      ? lo
823 			      : (lo + random() % ((hi - lo))));
824 	tp->tv_usec = random() % 1000000;
825 }
826 
827 
828 void
829 timevaladd(struct timeval *t1,
830 	   struct timeval *t2)
831 {
832 
833 	t1->tv_sec += t2->tv_sec;
834 	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
835 		t1->tv_sec++;
836 		t1->tv_usec -= 1000000;
837 	}
838 }
839 
840 
841 /* t1 = t2 - t3
842  */
843 static void
844 timevalsub(struct timeval *t1,
845 	   struct timeval *t2,
846 	   struct timeval *t3)
847 {
848 	t1->tv_sec = t2->tv_sec - t3->tv_sec;
849 	if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
850 		t1->tv_sec--;
851 		t1->tv_usec += 1000000;
852 	}
853 }
854 
855 
856 /* put a message into the system log
857  */
858 void
859 msglog(const char *p, ...)
860 {
861 	va_list args;
862 
863 	trace_flush();
864 
865 	va_start(args, p);
866 	vsyslog(LOG_ERR, p, args);
867 
868 	if (ftrace != 0) {
869 		if (ftrace == stdout)
870 			(void)fputs("routed: ", ftrace);
871 		(void)vfprintf(ftrace, p, args);
872 		(void)fputc('\n', ftrace);
873 	}
874 	va_end(args);
875 }
876 
877 
878 /* Put a message about a bad system into the system log if
879  * we have not complained about it recently.
880  *
881  * It is desirable to complain about all bad systems, but not too often.
882  * In the worst case, it is not practical to keep track of all bad systems.
883  * For example, there can be many systems with the wrong password.
884  */
885 void
886 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
887 {
888 	va_list args;
889 	int i;
890 	struct msg_sub *ms1, *ms;
891 	const char *p1;
892 
893 	va_start(args, p);
894 
895 	/* look for the oldest slot in the table
896 	 * or the slot for the bad router.
897 	 */
898 	ms = ms1 = lim->subs;
899 	for (i = MSG_SUBJECT_N; ; i--, ms1++) {
900 		if (i == 0) {
901 			/* Reuse a slot at most once every 10 minutes.
902 			 */
903 			if (lim->reuse > now.tv_sec) {
904 				ms = 0;
905 			} else {
906 				ms = ms1;
907 				lim->reuse = now.tv_sec + 10*60;
908 			}
909 			break;
910 		}
911 		if (ms->addr == addr) {
912 			/* Repeat a complaint about a given system at
913 			 * most once an hour.
914 			 */
915 			if (ms->until > now.tv_sec)
916 				ms = 0;
917 			break;
918 		}
919 		if (ms->until < ms1->until)
920 			ms = ms1;
921 	}
922 	if (ms != 0) {
923 		ms->addr = addr;
924 		ms->until = now.tv_sec + 60*60;	/* 60 minutes */
925 
926 		trace_flush();
927 		for (p1 = p; *p1 == ' '; p1++)
928 			continue;
929 		vsyslog(LOG_ERR, p1, args);
930 	}
931 
932 	/* always display the message if tracing */
933 	if (ftrace != 0) {
934 		(void)vfprintf(ftrace, p, args);
935 		(void)fputc('\n', ftrace);
936 	}
937 	va_end(args);
938 }
939 
940 
941 void
942 logbad(int dump, const char *p, ...)
943 {
944 	va_list args;
945 
946 	trace_flush();
947 
948 	va_start(args, p);
949 	vsyslog(LOG_ERR, p, args);
950 
951 	(void)fputs("routed: ", stderr);
952 	(void)vfprintf(stderr, p, args);
953 	(void)fputs("; giving up\n",stderr);
954 	(void)fflush(stderr);
955 	va_end(args);
956 
957 	if (dump)
958 		abort();
959 	exit(1);
960 }
961