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