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