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