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