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