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