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