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