main.c revision 110670
192494Ssobomax/*
292494Ssobomax * Copyright (c) 1983, 1988, 1993
392494Ssobomax *	The Regents of the University of California.  All rights reserved.
492494Ssobomax *
592494Ssobomax * Redistribution and use in source and binary forms, with or without
692494Ssobomax * modification, are permitted provided that the following conditions
792494Ssobomax * are met:
892494Ssobomax * 1. Redistributions of source code must retain the above copyright
992494Ssobomax *    notice, this list of conditions and the following disclaimer.
1092494Ssobomax * 2. Redistributions in binary form must reproduce the above copyright
1192494Ssobomax *    notice, this list of conditions and the following disclaimer in the
1292494Ssobomax *    documentation and/or other materials provided with the distribution.
1392494Ssobomax * 3. All advertising materials mentioning features or use of this software
1492494Ssobomax *    must display the following acknowledgment:
1592494Ssobomax *	This product includes software developed by the University of
1692494Ssobomax *	California, Berkeley and its contributors.
1792494Ssobomax * 4. Neither the name of the University nor the names of its contributors
1892494Ssobomax *    may be used to endorse or promote products derived from this software
1992494Ssobomax *    without specific prior written permission.
2092494Ssobomax *
2192494Ssobomax * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2292494Ssobomax * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2392494Ssobomax * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2492494Ssobomax * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2592494Ssobomax * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2692494Ssobomax * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2792494Ssobomax * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2892494Ssobomax * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2992494Ssobomax * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3092494Ssobomax * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3192494Ssobomax * SUCH DAMAGE.
3292494Ssobomax *
3392494Ssobomax * $FreeBSD: head/sbin/routed/main.c 110670 2003-02-11 02:31:53Z ache $
3492494Ssobomax */
3592494Ssobomax
3692494Ssobomax#include "defs.h"
3792494Ssobomax#include "pathnames.h"
3892494Ssobomax#ifdef sgi
3992494Ssobomax#include "math.h"
4092494Ssobomax#endif
4192494Ssobomax#include <signal.h>
4292494Ssobomax#include <fcntl.h>
4392494Ssobomax#include <sys/file.h>
4492494Ssobomax
4592494Ssobomax#if !defined(sgi) && !defined(__NetBSD__)
4692494Ssobomaxchar copyright[] =
47124572Sjhb"@(#) Copyright (c) 1983, 1988, 1993\n\
4892494Ssobomax	The Regents of the University of California.  All rights reserved.\n";
4992494Ssobomaxstatic char sccsid[] __attribute__((unused)) = "@(#)main.c	8.1 (Berkeley) 6/5/93";
5092494Ssobomax#elif defined(__NetBSD__)
5192494Ssobomax__RCSID("$NetBSD$");
5292494Ssobomax__COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\n\
5392494Ssobomax	The Regents of the University of California.  All rights reserved.\n");
5492494Ssobomax#endif
5592494Ssobomax#ident "$FreeBSD: head/sbin/routed/main.c 110670 2003-02-11 02:31:53Z ache $"
5692494Ssobomax
5792494Ssobomax
5892494Ssobomaxpid_t	mypid;
5992494Ssobomax
6092494Ssobomaxnaddr	myaddr;				/* system address */
6192494Ssobomaxchar	myname[MAXHOSTNAMELEN+1];
6292494Ssobomax
6392494Ssobomaxint	verbose;
6492494Ssobomax
6592494Ssobomaxint	supplier;			/* supply or broadcast updates */
6692494Ssobomaxint	supplier_set;
6792494Ssobomaxint	ipforwarding = 1;		/* kernel forwarding on */
68124571Sjhb
6992494Ssobomaxint	default_gateway;		/* 1=advertise default */
70124571Sjhbint	background = 1;
7192494Ssobomaxint	ridhosts;			/* 1=reduce host routes */
7292494Ssobomaxint	mhome;				/* 1=want multi-homed host route */
7392494Ssobomaxint	advertise_mhome;		/* 1=must continue advertising it */
7492494Ssobomaxint	auth_ok = 1;			/* 1=ignore auth if we do not care */
7592494Ssobomax
7692494Ssobomaxstruct timeval epoch;			/* when started */
77124571Sjhbstruct timeval clk, prev_clk;
78124571Sjhbstatic int usec_fudge;
7992494Ssobomaxstruct timeval now;			/* current idea of time */
8092494Ssobomaxtime_t	now_stale;
8192494Ssobomaxtime_t	now_expire;
82124572Sjhbtime_t	now_garbage;
83124572Sjhb
84124572Sjhbstruct timeval next_bcast;		/* next general broadcast */
85124572Sjhbstruct timeval no_flash = {		/* inhibit flash update */
86124572Sjhb	EPOCH+SUPPLY_INTERVAL, 0
87124572Sjhb};
88124572Sjhb
89124572Sjhbstruct timeval flush_kern_timer;
90124572Sjhb
91124572Sjhbfd_set	fdbits;
92124572Sjhbint	sock_max;
93124572Sjhbint	rip_sock = -1;			/* RIP socket */
94124572Sjhbstruct interface *rip_sock_mcast;	/* current multicast interface */
95124572Sjhbint	rt_sock;			/* routing socket */
96124572Sjhbint	rt_sock_seqno;
97124572Sjhb
98124572Sjhb
99124572Sjhbstatic  int get_rip_sock(naddr, int);
100124572Sjhbstatic void timevalsub(struct timeval *, struct timeval *, struct timeval *);
101124572Sjhb
102124572Sjhbint
103124572Sjhbmain(int argc,
10492494Ssobomax     char *argv[])
10592494Ssobomax{
10692494Ssobomax	int n, mib[4], off;
10792494Ssobomax	size_t len;
10892494Ssobomax	char *p, *q;
10992494Ssobomax	const char *cp;
11092494Ssobomax	struct timeval wtime, t2;
11192494Ssobomax	time_t dt;
11292494Ssobomax	fd_set ibits;
11392494Ssobomax	naddr p_net, p_mask;
11492494Ssobomax	struct interface *ifp;
11592494Ssobomax	struct parm parm;
11692494Ssobomax	char *tracename = 0;
11792494Ssobomax
11892494Ssobomax
11992494Ssobomax	/* Some shells are badly broken and send SIGHUP to backgrounded
12092494Ssobomax	 * processes.
12192494Ssobomax	 */
12292494Ssobomax	signal(SIGHUP, SIG_IGN);
12392494Ssobomax
12492494Ssobomax	openlog("routed", LOG_PID | LOG_ODELAY, LOG_DAEMON);
12592494Ssobomax	ftrace = stdout;
12692494Ssobomax
12792494Ssobomax	gettimeofday(&clk, 0);
12892494Ssobomax	prev_clk = clk;
12992494Ssobomax	epoch = clk;
13092494Ssobomax	epoch.tv_sec -= EPOCH;
13192494Ssobomax	now.tv_sec = EPOCH;
13292494Ssobomax	now_stale = EPOCH - STALE_TIME;
13392494Ssobomax	now_expire = EPOCH - EXPIRE_TIME;
13492494Ssobomax	now_garbage = EPOCH - GARBAGE_TIME;
13592494Ssobomax	wtime.tv_sec = 0;
13692494Ssobomax
13792494Ssobomax	(void)gethostname(myname, sizeof(myname)-1);
13892494Ssobomax	(void)gethost(myname, &myaddr);
13992494Ssobomax
14092494Ssobomax	while ((n = getopt(argc, argv, "sqdghmpAtvT:F:P:")) != -1) {
14192494Ssobomax		switch (n) {
14292494Ssobomax		case 's':
14392494Ssobomax			supplier = 1;
14492494Ssobomax			supplier_set = 1;
14592494Ssobomax			break;
14692494Ssobomax
14792494Ssobomax		case 'q':
14892494Ssobomax			supplier = 0;
14992494Ssobomax			supplier_set = 1;
15092494Ssobomax			break;
15192494Ssobomax
15292494Ssobomax		case 'd':
15392494Ssobomax			background = 0;
15492494Ssobomax			break;
15592494Ssobomax
15692494Ssobomax		case 'g':
15792494Ssobomax			memset(&parm, 0, sizeof(parm));
15892494Ssobomax			parm.parm_d_metric = 1;
15992494Ssobomax			cp = check_parms(&parm);
16092494Ssobomax			if (cp != 0)
16192494Ssobomax				msglog("bad -g: %s", cp);
16292494Ssobomax			else
16392494Ssobomax				default_gateway = 1;
16492494Ssobomax			break;
165124572Sjhb
16692494Ssobomax		case 'h':		/* suppress extra host routes */
16792494Ssobomax			ridhosts = 1;
16892494Ssobomax			break;
169124572Sjhb
170124572Sjhb		case 'm':		/* advertise host route */
171124572Sjhb			mhome = 1;	/* on multi-homed hosts */
172124572Sjhb			break;
173124572Sjhb
17492494Ssobomax		case 'A':
17592494Ssobomax			/* Ignore authentication if we do not care.
17692494Ssobomax			 * Crazy as it is, that is what RFC 1723 requires.
17792494Ssobomax			 */
17892494Ssobomax			auth_ok = 0;
17992494Ssobomax			break;
18092494Ssobomax
18192494Ssobomax		case 't':
18292494Ssobomax			new_tracelevel++;
18392494Ssobomax			break;
18492494Ssobomax
18592494Ssobomax		case 'T':
18692494Ssobomax			tracename = optarg;
18792494Ssobomax			break;
18892494Ssobomax
18992494Ssobomax		case 'F':		/* minimal routes for SLIP */
19092494Ssobomax			n = FAKE_METRIC;
19192494Ssobomax			p = strchr(optarg,',');
19292494Ssobomax			if (p && *p != '\0') {
19392494Ssobomax				n = (int)strtoul(p+1, &q, 0);
19492494Ssobomax				if (*q == '\0'
19592494Ssobomax				    && n <= HOPCNT_INFINITY-1
19692494Ssobomax				    && n >= 1)
19792494Ssobomax					*p = '\0';
19892494Ssobomax			}
19992494Ssobomax			if (!getnet(optarg, &p_net, &p_mask)) {
20092494Ssobomax				msglog("bad network; \"-F %s\"",
20192494Ssobomax				       optarg);
20292494Ssobomax				break;
20392494Ssobomax			}
20492494Ssobomax			memset(&parm, 0, sizeof(parm));
20592494Ssobomax			parm.parm_net = p_net;
20692494Ssobomax			parm.parm_mask = p_mask;
20792494Ssobomax			parm.parm_d_metric = n;
20892494Ssobomax			cp = check_parms(&parm);
20992494Ssobomax			if (cp != 0)
21092494Ssobomax				msglog("bad -F: %s", cp);
21192494Ssobomax			break;
21292494Ssobomax
21392494Ssobomax		case 'P':
21492494Ssobomax			/* handle arbitrary parameters.
21592494Ssobomax			 */
21692494Ssobomax			q = strdup(optarg);
21792494Ssobomax			cp = parse_parms(q, 0);
21892494Ssobomax			if (cp != 0)
21992494Ssobomax				msglog("%s in \"-P %s\"", cp, optarg);
22092494Ssobomax			free(q);
221124572Sjhb			break;
222124572Sjhb
22392494Ssobomax		case 'v':
22492494Ssobomax			/* display version */
22592494Ssobomax			verbose++;
22692494Ssobomax			msglog("version 2.22");
22792494Ssobomax			break;
22892494Ssobomax
22992494Ssobomax		default:
23092494Ssobomax			goto usage;
23192494Ssobomax		}
23292494Ssobomax	}
23392494Ssobomax	argc -= optind;
23492494Ssobomax	argv += optind;
23592494Ssobomax
23692494Ssobomax	if (tracename == 0 && argc >= 1) {
23792494Ssobomax		tracename = *argv++;
23892494Ssobomax		argc--;
23992494Ssobomax	}
24092494Ssobomax	if (tracename != 0 && tracename[0] == '\0')
24192494Ssobomax		goto usage;
24292494Ssobomax	if (argc != 0) {
24392494Ssobomaxusage:
24492494Ssobomax		logbad(0, "usage: routed [-sqdghmpAtv] [-T tracefile]"
24592494Ssobomax		       " [-F net[,metric]] [-P parms]");
24692494Ssobomax	}
24792494Ssobomax	if (geteuid() != 0) {
24892494Ssobomax		if (verbose)
24992494Ssobomax			exit(0);
25092494Ssobomax		logbad(0, "requires UID 0");
25192494Ssobomax	}
25292494Ssobomax
253124811Sjhb	mib[0] = CTL_NET;
254124811Sjhb	mib[1] = PF_INET;
255124811Sjhb	mib[2] = IPPROTO_IP;
25692494Ssobomax	mib[3] = IPCTL_FORWARDING;
25792494Ssobomax	len = sizeof(ipforwarding);
25892494Ssobomax	if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
25992494Ssobomax		LOGERR("sysctl(IPCTL_FORWARDING)");
26092494Ssobomax
26192494Ssobomax	if (!ipforwarding) {
26292494Ssobomax		if (supplier)
26392494Ssobomax			msglog("-s incompatible with ipforwarding=0");
26492494Ssobomax		if (default_gateway) {
26592494Ssobomax			msglog("-g incompatible with ipforwarding=0");
26692494Ssobomax			default_gateway = 0;
267124811Sjhb		}
268124811Sjhb		supplier = 0;
26992494Ssobomax		supplier_set = 1;
270124811Sjhb	}
27192494Ssobomax	if (default_gateway) {
27292494Ssobomax		if (supplier_set && !supplier) {
27392494Ssobomax			msglog("-g and -q incompatible");
27492494Ssobomax		} else {
27592494Ssobomax			supplier = 1;
27692494Ssobomax			supplier_set = 1;
27792494Ssobomax		}
27892494Ssobomax	}
27992494Ssobomax
28092494Ssobomax
28192494Ssobomax	signal(SIGALRM, sigalrm);
28292494Ssobomax	if (!background)
28392494Ssobomax		signal(SIGHUP, sigterm);    /* SIGHUP fatal during debugging */
28492494Ssobomax	signal(SIGTERM, sigterm);
28592494Ssobomax	signal(SIGINT, sigterm);
28692494Ssobomax	signal(SIGUSR1, sigtrace_on);
28792494Ssobomax	signal(SIGUSR2, sigtrace_off);
28892494Ssobomax
28992494Ssobomax	/* get into the background */
29092494Ssobomax#ifdef sgi
291124811Sjhb	if (0 > _daemonize(background ? 0 : (_DF_NOCHDIR|_DF_NOFORK),
292124811Sjhb			   STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO))
29392494Ssobomax		BADERR(0, "_daemonize()");
294124811Sjhb#else
29592494Ssobomax	if (background && daemon(0, 1) < 0)
29692494Ssobomax		BADERR(0,"daemon()");
29792494Ssobomax#endif
29892494Ssobomax
29992494Ssobomax	mypid = getpid();
30092494Ssobomax#ifdef __FreeBSD__
30192494Ssobomax	srandomdev();
30292494Ssobomax#else
30392494Ssobomax	srandom((int)(clk.tv_sec ^ clk.tv_usec ^ mypid));
30492494Ssobomax#endif
30592494Ssobomax
30692494Ssobomax	/* prepare socket connected to the kernel.
30792494Ssobomax	 */
30892494Ssobomax	rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
30992494Ssobomax	if (rt_sock < 0)
31092494Ssobomax		BADERR(1,"rt_sock = socket()");
31192494Ssobomax	if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
31292494Ssobomax		logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno));
313	off = 0;
314	if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
315		       &off,sizeof(off)) < 0)
316		LOGERR("setsockopt(SO_USELOOPBACK,0)");
317
318	fix_select();
319
320
321	if (tracename != 0) {
322		strncpy(inittracename, tracename, sizeof(inittracename)-1);
323		set_tracefile(inittracename, "%s", -1);
324	} else {
325		tracelevel_msg("%s", -1);   /* turn on tracing to stdio */
326	}
327
328	bufinit();
329
330	/* initialize radix tree */
331	rtinit();
332
333	/* Pick a random part of the second for our output to minimize
334	 * collisions.
335	 *
336	 * Start broadcasting after hearing from other routers, and
337	 * at a random time so a bunch of systems do not get synchronized
338	 * after a power failure.
339	 */
340	intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
341	age_timer.tv_usec = next_bcast.tv_usec;
342	age_timer.tv_sec = EPOCH+MIN_WAITTIME;
343	rdisc_timer = next_bcast;
344	ifinit_timer.tv_usec = next_bcast.tv_usec;
345
346	/* Collect an initial view of the world by checking the interface
347	 * configuration and the kludge file.
348	 */
349	gwkludge();
350	ifinit();
351
352	/* Ask for routes */
353	rip_query();
354	rdisc_sol();
355
356	/* Now turn off stdio if not tracing */
357	if (new_tracelevel == 0)
358		trace_close(background);
359
360	/* Loop forever, listening and broadcasting.
361	 */
362	for (;;) {
363		prev_clk = clk;
364		gettimeofday(&clk, 0);
365		if (prev_clk.tv_sec == clk.tv_sec
366		    && prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
367			/* Much of `routed` depends on time always advancing.
368			 * On systems that do not guarantee that gettimeofday()
369			 * produces unique timestamps even if called within
370			 * a single tick, use trickery like that in classic
371			 * BSD kernels.
372			 */
373			clk.tv_usec += ++usec_fudge;
374
375		} else {
376			usec_fudge = 0;
377
378			timevalsub(&t2, &clk, &prev_clk);
379			if (t2.tv_sec < 0
380			    || t2.tv_sec > wtime.tv_sec + 5) {
381				/* Deal with time changes before other
382				 * housekeeping to keep everything straight.
383				 */
384				dt = t2.tv_sec;
385				if (dt > 0)
386					dt -= wtime.tv_sec;
387				trace_act("time changed by %d sec", (int)dt);
388				epoch.tv_sec += dt;
389			}
390		}
391		timevalsub(&now, &clk, &epoch);
392		now_stale = now.tv_sec - STALE_TIME;
393		now_expire = now.tv_sec - EXPIRE_TIME;
394		now_garbage = now.tv_sec - GARBAGE_TIME;
395
396		/* deal with signals that should affect tracing */
397		set_tracelevel();
398
399		if (stopint != 0) {
400			rip_bcast(0);
401			rdisc_adv();
402			trace_off("exiting with signal %d", stopint);
403			exit(stopint | 128);
404		}
405
406		/* look for new or dead interfaces */
407		timevalsub(&wtime, &ifinit_timer, &now);
408		if (wtime.tv_sec <= 0) {
409			wtime.tv_sec = 0;
410			ifinit();
411			rip_query();
412			continue;
413		}
414
415		/* Check the kernel table occassionally for mysteriously
416		 * evaporated routes
417		 */
418		timevalsub(&t2, &flush_kern_timer, &now);
419		if (t2.tv_sec <= 0) {
420			flush_kern();
421			flush_kern_timer.tv_sec = (now.tv_sec
422						   + CHECK_QUIET_INTERVAL);
423			continue;
424		}
425		if (timercmp(&t2, &wtime, <))
426			wtime = t2;
427
428		/* If it is time, then broadcast our routes.
429		 */
430		if (supplier || advertise_mhome) {
431			timevalsub(&t2, &next_bcast, &now);
432			if (t2.tv_sec <= 0) {
433				/* Synchronize the aging and broadcast
434				 * timers to minimize awakenings
435				 */
436				age(0);
437
438				rip_bcast(0);
439
440				/* It is desirable to send routing updates
441				 * regularly.  So schedule the next update
442				 * 30 seconds after the previous one was
443				 * scheduled, instead of 30 seconds after
444				 * the previous update was finished.
445				 * Even if we just started after discovering
446				 * a 2nd interface or were otherwise delayed,
447				 * pick a 30-second aniversary of the
448				 * original broadcast time.
449				 */
450				n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
451				next_bcast.tv_sec += n*SUPPLY_INTERVAL;
452
453				continue;
454			}
455
456			if (timercmp(&t2, &wtime, <))
457				wtime = t2;
458		}
459
460		/* If we need a flash update, either do it now or
461		 * set the delay to end when it is time.
462		 *
463		 * If we are within MIN_WAITTIME seconds of a full update,
464		 * do not bother.
465		 */
466		if (need_flash
467		    && supplier
468		    && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
469			/* accurate to the millisecond */
470			if (!timercmp(&no_flash, &now, >))
471				rip_bcast(1);
472			timevalsub(&t2, &no_flash, &now);
473			if (timercmp(&t2, &wtime, <))
474				wtime = t2;
475		}
476
477		/* trigger the main aging timer.
478		 */
479		timevalsub(&t2, &age_timer, &now);
480		if (t2.tv_sec <= 0) {
481			age(0);
482			continue;
483		}
484		if (timercmp(&t2, &wtime, <))
485			wtime = t2;
486
487		/* update the kernel routing table
488		 */
489		timevalsub(&t2, &need_kern, &now);
490		if (t2.tv_sec <= 0) {
491			age(0);
492			continue;
493		}
494		if (timercmp(&t2, &wtime, <))
495			wtime = t2;
496
497		/* take care of router discovery,
498		 * but do it in the correct the millisecond
499		 */
500		if (!timercmp(&rdisc_timer, &now, >)) {
501			rdisc_age(0);
502			continue;
503		}
504		timevalsub(&t2, &rdisc_timer, &now);
505		if (timercmp(&t2, &wtime, <))
506			wtime = t2;
507
508
509		/* wait for input or a timer to expire.
510		 */
511		trace_flush();
512		ibits = fdbits;
513		n = select(sock_max, &ibits, 0, 0, &wtime);
514		if (n <= 0) {
515			if (n < 0 && errno != EINTR && errno != EAGAIN)
516				BADERR(1,"select");
517			continue;
518		}
519
520		if (FD_ISSET(rt_sock, &ibits)) {
521			read_rt();
522			n--;
523		}
524		if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
525			read_d();
526			n--;
527		}
528		if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
529			read_rip(rip_sock, 0);
530			n--;
531		}
532
533		for (ifp = ifnet; n > 0 && 0 != ifp; ifp = ifp->int_next) {
534			if (ifp->int_rip_sock >= 0
535			    && FD_ISSET(ifp->int_rip_sock, &ibits)) {
536				read_rip(ifp->int_rip_sock, ifp);
537				n--;
538			}
539		}
540	}
541}
542
543
544/* ARGSUSED */
545void
546sigalrm(int s UNUSED)
547{
548	/* Historically, SIGALRM would cause the daemon to check for
549	 * new and broken interfaces.
550	 */
551	ifinit_timer.tv_sec = now.tv_sec;
552	trace_act("SIGALRM");
553}
554
555
556/* watch for fatal signals */
557void
558sigterm(int sig)
559{
560	stopint = sig;
561	(void)signal(sig, SIG_DFL);	/* catch it only once */
562}
563
564
565void
566fix_select(void)
567{
568	struct interface *ifp;
569
570
571	FD_ZERO(&fdbits);
572	sock_max = 0;
573
574	FD_SET(rt_sock, &fdbits);
575	if (sock_max <= rt_sock)
576		sock_max = rt_sock+1;
577	if (rip_sock >= 0) {
578		FD_SET(rip_sock, &fdbits);
579		if (sock_max <= rip_sock)
580			sock_max = rip_sock+1;
581	}
582	for (ifp = ifnet; 0 != ifp; ifp = ifp->int_next) {
583		if (ifp->int_rip_sock >= 0) {
584			FD_SET(ifp->int_rip_sock, &fdbits);
585			if (sock_max <= ifp->int_rip_sock)
586				sock_max = ifp->int_rip_sock+1;
587		}
588	}
589	if (rdisc_sock >= 0) {
590		FD_SET(rdisc_sock, &fdbits);
591		if (sock_max <= rdisc_sock)
592			sock_max = rdisc_sock+1;
593	}
594}
595
596
597void
598fix_sock(int sock,
599	 const char *name)
600{
601	int on;
602#define MIN_SOCKBUF (4*1024)
603	static int rbuf;
604
605	if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
606		logbad(1, "fcntl(%s) O_NONBLOCK: %s",
607		       name, strerror(errno));
608	on = 1;
609	if (setsockopt(sock, SOL_SOCKET,SO_BROADCAST, &on,sizeof(on)) < 0)
610		msglog("setsockopt(%s,SO_BROADCAST): %s",
611		       name, strerror(errno));
612#ifdef USE_PASSIFNAME
613	on = 1;
614	if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
615		msglog("setsockopt(%s,SO_PASSIFNAME): %s",
616		       name, strerror(errno));
617#endif
618
619	if (rbuf >= MIN_SOCKBUF) {
620		if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
621			       &rbuf, sizeof(rbuf)) < 0)
622			msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
623			       name, rbuf, strerror(errno));
624	} else {
625		for (rbuf = 60*1024; ; rbuf -= 4096) {
626			if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
627				       &rbuf, sizeof(rbuf)) == 0) {
628				trace_act("RCVBUF=%d", rbuf);
629				break;
630			}
631			if (rbuf < MIN_SOCKBUF) {
632				msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
633				       name, rbuf, strerror(errno));
634				break;
635			}
636		}
637	}
638}
639
640
641/* get a rip socket
642 */
643static int				/* <0 or file descriptor */
644get_rip_sock(naddr addr,
645	     int serious)		/* 1=failure to bind is serious */
646{
647	struct sockaddr_in sin;
648	unsigned char ttl;
649	int s;
650
651
652	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
653		BADERR(1,"rip_sock = socket()");
654
655	memset(&sin, 0, sizeof(sin));
656#ifdef _HAVE_SIN_LEN
657	sin.sin_len = sizeof(sin);
658#endif
659	sin.sin_family = AF_INET;
660	sin.sin_port = htons(RIP_PORT);
661	sin.sin_addr.s_addr = addr;
662	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
663		if (serious)
664			BADERR(errno != EADDRINUSE, "bind(rip_sock)");
665		return -1;
666	}
667	fix_sock(s,"rip_sock");
668
669	ttl = 1;
670	if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
671		       &ttl, sizeof(ttl)) < 0)
672		DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
673
674	return s;
675}
676
677
678/* turn off main RIP socket */
679void
680rip_off(void)
681{
682	struct interface *ifp;
683	naddr addr;
684
685
686	if (rip_sock >= 0 && !mhome) {
687		trace_act("turn off RIP");
688
689		(void)close(rip_sock);
690		rip_sock = -1;
691
692		/* get non-broadcast sockets to listen to queries.
693		 */
694		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
695			if (ifp->int_state & IS_REMOTE)
696				continue;
697			if (ifp->int_rip_sock < 0) {
698				addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
699					? ifp->int_dstaddr
700					: ifp->int_addr);
701				ifp->int_rip_sock = get_rip_sock(addr, 0);
702			}
703		}
704
705		fix_select();
706
707		age(0);
708	}
709}
710
711
712/* turn on RIP multicast input via an interface
713 */
714static void
715rip_mcast_on(struct interface *ifp)
716{
717	struct ip_mreq m;
718
719	if (!IS_RIP_IN_OFF(ifp->int_state)
720	    && (ifp->int_if_flags & IFF_MULTICAST)
721#ifdef MCAST_PPP_BUG
722	    && !(ifp->int_if_flags & IFF_POINTOPOINT)
723#endif
724	    && !(ifp->int_state & IS_ALIAS)) {
725		m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
726		m.imr_interface.s_addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
727					  ? ifp->int_dstaddr
728					  : ifp->int_addr);
729		if (setsockopt(rip_sock,IPPROTO_IP, IP_ADD_MEMBERSHIP,
730			       &m, sizeof(m)) < 0)
731			LOGERR("setsockopt(IP_ADD_MEMBERSHIP RIP)");
732	}
733}
734
735
736/* Prepare socket used for RIP.
737 */
738void
739rip_on(struct interface *ifp)
740{
741	/* If the main RIP socket is already alive, only start receiving
742	 * multicasts for this interface.
743	 */
744	if (rip_sock >= 0) {
745		if (ifp != 0)
746			rip_mcast_on(ifp);
747		return;
748	}
749
750	/* If the main RIP socket is off and it makes sense to turn it on,
751	 * then turn it on for all of the interfaces.
752	 * It makes sense if either router discovery is off, or if
753	 * router discover is on and at most one interface is doing RIP.
754	 */
755	if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
756		trace_act("turn on RIP");
757
758		/* Close all of the query sockets so that we can open
759		 * the main socket.  SO_REUSEPORT is not a solution,
760		 * since that would let two daemons bind to the broadcast
761		 * socket.
762		 */
763		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
764			if (ifp->int_rip_sock >= 0) {
765				(void)close(ifp->int_rip_sock);
766				ifp->int_rip_sock = -1;
767			}
768		}
769
770		rip_sock = get_rip_sock(INADDR_ANY, 1);
771		rip_sock_mcast = 0;
772
773		/* Do not advertise anything until we have heard something
774		 */
775		if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
776			next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
777
778		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
779			ifp->int_query_time = NEVER;
780			rip_mcast_on(ifp);
781		}
782		ifinit_timer.tv_sec = now.tv_sec;
783
784	} else if (ifp != 0
785		   && !(ifp->int_state & IS_REMOTE)
786		   && ifp->int_rip_sock < 0) {
787		/* RIP is off, so ensure there are sockets on which
788		 * to listen for queries.
789		 */
790		ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
791	}
792
793	fix_select();
794}
795
796
797/* die if malloc(3) fails
798 */
799void *
800rtmalloc(size_t size,
801	 const char *msg)
802{
803	void *p = malloc(size);
804	if (p == 0)
805		logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
806	return p;
807}
808
809
810/* get a random instant in an interval
811 */
812void
813intvl_random(struct timeval *tp,	/* put value here */
814	     u_long lo,			/* value is after this second */
815	     u_long hi)			/* and before this */
816{
817	tp->tv_sec = (time_t)(hi == lo
818			      ? lo
819			      : (lo + random() % ((hi - lo))));
820	tp->tv_usec = random() % 1000000;
821}
822
823
824void
825timevaladd(struct timeval *t1,
826	   struct timeval *t2)
827{
828
829	t1->tv_sec += t2->tv_sec;
830	if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
831		t1->tv_sec++;
832		t1->tv_usec -= 1000000;
833	}
834}
835
836
837/* t1 = t2 - t3
838 */
839static void
840timevalsub(struct timeval *t1,
841	   struct timeval *t2,
842	   struct timeval *t3)
843{
844	t1->tv_sec = t2->tv_sec - t3->tv_sec;
845	if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
846		t1->tv_sec--;
847		t1->tv_usec += 1000000;
848	}
849}
850
851
852/* put a message into the system log
853 */
854void
855msglog(const char *p, ...)
856{
857	va_list args;
858
859	trace_flush();
860
861	va_start(args, p);
862	vsyslog(LOG_ERR, p, args);
863
864	if (ftrace != 0) {
865		if (ftrace == stdout)
866			(void)fputs("routed: ", ftrace);
867		(void)vfprintf(ftrace, p, args);
868		(void)fputc('\n', ftrace);
869	}
870}
871
872
873/* Put a message about a bad system into the system log if
874 * we have not complained about it recently.
875 *
876 * It is desirable to complain about all bad systems, but not too often.
877 * In the worst case, it is not practical to keep track of all bad systems.
878 * For example, there can be many systems with the wrong password.
879 */
880void
881msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
882{
883	va_list args;
884	int i;
885	struct msg_sub *ms1, *ms;
886	const char *p1;
887
888	va_start(args, p);
889
890	/* look for the oldest slot in the table
891	 * or the slot for the bad router.
892	 */
893	ms = ms1 = lim->subs;
894	for (i = MSG_SUBJECT_N; ; i--, ms1++) {
895		if (i == 0) {
896			/* Reuse a slot at most once every 10 minutes.
897			 */
898			if (lim->reuse > now.tv_sec) {
899				ms = 0;
900			} else {
901				ms = ms1;
902				lim->reuse = now.tv_sec + 10*60;
903			}
904			break;
905		}
906		if (ms->addr == addr) {
907			/* Repeat a complaint about a given system at
908			 * most once an hour.
909			 */
910			if (ms->until > now.tv_sec)
911				ms = 0;
912			break;
913		}
914		if (ms->until < ms1->until)
915			ms = ms1;
916	}
917	if (ms != 0) {
918		ms->addr = addr;
919		ms->until = now.tv_sec + 60*60;	/* 60 minutes */
920
921		trace_flush();
922		for (p1 = p; *p1 == ' '; p1++)
923			continue;
924		vsyslog(LOG_ERR, p1, args);
925	}
926
927	/* always display the message if tracing */
928	if (ftrace != 0) {
929		(void)vfprintf(ftrace, p, args);
930		(void)fputc('\n', ftrace);
931	}
932}
933
934
935void
936logbad(int dump, const char *p, ...)
937{
938	va_list args;
939
940	trace_flush();
941
942	va_start(args, p);
943	vsyslog(LOG_ERR, p, args);
944
945	(void)fputs("routed: ", stderr);
946	(void)vfprintf(stderr, p, args);
947	(void)fputs("; giving up\n",stderr);
948	(void)fflush(stderr);
949
950	if (dump)
951		abort();
952	exit(1);
953}
954