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