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