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