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