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