table.c revision 128073
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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * $FreeBSD: head/sbin/routed/table.c 128073 2004-04-09 19:58:40Z markm $
30 */
31
32#include "defs.h"
33
34#ifdef __NetBSD__
35__RCSID("$NetBSD$");
36#elif defined(__FreeBSD__)
37__RCSID("$FreeBSD: head/sbin/routed/table.c 128073 2004-04-09 19:58:40Z markm $");
38#else
39__RCSID("$Revision: 2.27 $");
40#ident "$Revision: 2.27 $"
41#endif
42#ident "$FreeBSD: head/sbin/routed/table.c 128073 2004-04-09 19:58:40Z markm $"
43
44static struct rt_spare *rts_better(struct rt_entry *);
45static struct rt_spare rts_empty = {0,0,0,HOPCNT_INFINITY,0,0,0};
46static void  set_need_flash(void);
47#ifdef _HAVE_SIN_LEN
48static void masktrim(struct sockaddr_in *ap);
49#else
50static void masktrim(struct sockaddr_in_new *ap);
51#endif
52
53
54struct radix_node_head *rhead;		/* root of the radix tree */
55
56int	need_flash = 1;			/* flash update needed
57					 * start =1 to suppress the 1st
58					 */
59
60struct timeval age_timer;		/* next check of old routes */
61struct timeval need_kern = {		/* need to update kernel table */
62	EPOCH+MIN_WAITTIME-1, 0
63};
64
65int	stopint;
66
67int	total_routes;
68
69/* zap any old routes through this gateway */
70naddr	age_bad_gate;
71
72
73/* It is desirable to "aggregate" routes, to combine differing routes of
74 * the same metric and next hop into a common route with a smaller netmask
75 * or to suppress redundant routes, routes that add no information to
76 * routes with smaller netmasks.
77 *
78 * A route is redundant if and only if any and all routes with smaller
79 * but matching netmasks and nets are the same.  Since routes are
80 * kept sorted in the radix tree, redundant routes always come second.
81 *
82 * There are two kinds of aggregations.  First, two routes of the same bit
83 * mask and differing only in the least significant bit of the network
84 * number can be combined into a single route with a coarser mask.
85 *
86 * Second, a route can be suppressed in favor of another route with a more
87 * coarse mask provided no incompatible routes with intermediate masks
88 * are present.  The second kind of aggregation involves suppressing routes.
89 * A route must not be suppressed if an incompatible route exists with
90 * an intermediate mask, since the suppressed route would be covered
91 * by the intermediate.
92 *
93 * This code relies on the radix tree walk encountering routes
94 * sorted first by address, with the smallest address first.
95 */
96
97struct ag_info ag_slots[NUM_AG_SLOTS], *ag_avail, *ag_corsest, *ag_finest;
98
99/* #define DEBUG_AG */
100#ifdef DEBUG_AG
101#define CHECK_AG() {int acnt = 0; struct ag_info *cag;		\
102	for (cag = ag_avail; cag != 0; cag = cag->ag_fine)	\
103		acnt++;						\
104	for (cag = ag_corsest; cag != 0; cag = cag->ag_fine)	\
105		acnt++;						\
106	if (acnt != NUM_AG_SLOTS) {				\
107		(void)fflush(stderr);				\
108		abort();					\
109	}							\
110}
111#else
112#define CHECK_AG()
113#endif
114
115
116/* Output the contents of an aggregation table slot.
117 *	This function must always be immediately followed with the deletion
118 *	of the target slot.
119 */
120static void
121ag_out(struct ag_info *ag,
122	 void (*out)(struct ag_info *))
123{
124	struct ag_info *ag_cors;
125	naddr bit;
126
127
128	/* Forget it if this route should not be output for split-horizon. */
129	if (ag->ag_state & AGS_SPLIT_HZ)
130		return;
131
132	/* If we output both the even and odd twins, then the immediate parent,
133	 * if it is present, is redundant, unless the parent manages to
134	 * aggregate into something coarser.
135	 * On successive calls, this code detects the even and odd twins,
136	 * and marks the parent.
137	 *
138	 * Note that the order in which the radix tree code emits routes
139	 * ensures that the twins are seen before the parent is emitted.
140	 */
141	ag_cors = ag->ag_cors;
142	if (ag_cors != 0
143	    && ag_cors->ag_mask == ag->ag_mask<<1
144	    && ag_cors->ag_dst_h == (ag->ag_dst_h & ag_cors->ag_mask)) {
145		ag_cors->ag_state |= ((ag_cors->ag_dst_h == ag->ag_dst_h)
146				      ? AGS_REDUN0
147				      : AGS_REDUN1);
148	}
149
150	/* Skip it if this route is itself redundant.
151	 *
152	 * It is ok to change the contents of the slot here, since it is
153	 * always deleted next.
154	 */
155	if (ag->ag_state & AGS_REDUN0) {
156		if (ag->ag_state & AGS_REDUN1)
157			return;		/* quit if fully redundant */
158		/* make it finer if it is half-redundant */
159		bit = (-ag->ag_mask) >> 1;
160		ag->ag_dst_h |= bit;
161		ag->ag_mask |= bit;
162
163	} else if (ag->ag_state & AGS_REDUN1) {
164		/* make it finer if it is half-redundant */
165		bit = (-ag->ag_mask) >> 1;
166		ag->ag_mask |= bit;
167	}
168	out(ag);
169}
170
171
172static void
173ag_del(struct ag_info *ag)
174{
175	CHECK_AG();
176
177	if (ag->ag_cors == 0)
178		ag_corsest = ag->ag_fine;
179	else
180		ag->ag_cors->ag_fine = ag->ag_fine;
181
182	if (ag->ag_fine == 0)
183		ag_finest = ag->ag_cors;
184	else
185		ag->ag_fine->ag_cors = ag->ag_cors;
186
187	ag->ag_fine = ag_avail;
188	ag_avail = ag;
189
190	CHECK_AG();
191}
192
193
194/* Flush routes waiting for aggregation.
195 *	This must not suppress a route unless it is known that among all
196 *	routes with coarser masks that match it, the one with the longest
197 *	mask is appropriate.  This is ensured by scanning the routes
198 *	in lexical order, and with the most restrictive mask first
199 *	among routes to the same destination.
200 */
201void
202ag_flush(naddr lim_dst_h,		/* flush routes to here */
203	 naddr lim_mask,		/* matching this mask */
204	 void (*out)(struct ag_info *))
205{
206	struct ag_info *ag, *ag_cors;
207	naddr dst_h;
208
209
210	for (ag = ag_finest;
211	     ag != 0 && ag->ag_mask >= lim_mask;
212	     ag = ag_cors) {
213		ag_cors = ag->ag_cors;
214
215		/* work on only the specified routes */
216		dst_h = ag->ag_dst_h;
217		if ((dst_h & lim_mask) != lim_dst_h)
218			continue;
219
220		if (!(ag->ag_state & AGS_SUPPRESS))
221			ag_out(ag, out);
222
223		else for ( ; ; ag_cors = ag_cors->ag_cors) {
224			/* Look for a route that can suppress the
225			 * current route */
226			if (ag_cors == 0) {
227				/* failed, so output it and look for
228				 * another route to work on
229				 */
230				ag_out(ag, out);
231				break;
232			}
233
234			if ((dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h) {
235				/* We found a route with a coarser mask that
236				 * aggregates the current target.
237				 *
238				 * If it has a different next hop, it
239				 * cannot replace the target, so output
240				 * the target.
241				 */
242				if (ag->ag_gate != ag_cors->ag_gate
243				    && !(ag->ag_state & AGS_FINE_GATE)
244				    && !(ag_cors->ag_state & AGS_CORS_GATE)) {
245					ag_out(ag, out);
246					break;
247				}
248
249				/* If the coarse route has a good enough
250				 * metric, it suppresses the target.
251				 * If the suppressed target was redundant,
252				 * then mark the suppressor redundant.
253				 */
254				if (ag_cors->ag_pref <= ag->ag_pref) {
255				    if (AG_IS_REDUN(ag->ag_state)
256					&& ag_cors->ag_mask==ag->ag_mask<<1) {
257					if (ag_cors->ag_dst_h == dst_h)
258					    ag_cors->ag_state |= AGS_REDUN0;
259					else
260					    ag_cors->ag_state |= AGS_REDUN1;
261				    }
262				    if (ag->ag_tag != ag_cors->ag_tag)
263					    ag_cors->ag_tag = 0;
264				    if (ag->ag_nhop != ag_cors->ag_nhop)
265					    ag_cors->ag_nhop = 0;
266				    break;
267				}
268			}
269		}
270
271		/* That route has either been output or suppressed */
272		ag_cors = ag->ag_cors;
273		ag_del(ag);
274	}
275
276	CHECK_AG();
277}
278
279
280/* Try to aggregate a route with previous routes.
281 */
282void
283ag_check(naddr	dst,
284	 naddr	mask,
285	 naddr	gate,
286	 naddr	nhop,
287	 char	metric,
288	 char	pref,
289	 u_int	new_seqno,
290	 u_short tag,
291	 u_short state,
292	 void (*out)(struct ag_info *))	/* output using this */
293{
294	struct ag_info *ag, *nag, *ag_cors;
295	naddr xaddr;
296	int x;
297
298	dst = ntohl(dst);
299
300	/* Punt non-contiguous subnet masks.
301	 *
302	 * (X & -X) contains a single bit if and only if X is a power of 2.
303	 * (X + (X & -X)) == 0 if and only if X is a power of 2.
304	 */
305	if ((mask & -mask) + mask != 0) {
306		struct ag_info nc_ag;
307
308		nc_ag.ag_dst_h = dst;
309		nc_ag.ag_mask = mask;
310		nc_ag.ag_gate = gate;
311		nc_ag.ag_nhop = nhop;
312		nc_ag.ag_metric = metric;
313		nc_ag.ag_pref = pref;
314		nc_ag.ag_tag = tag;
315		nc_ag.ag_state = state;
316		nc_ag.ag_seqno = new_seqno;
317		out(&nc_ag);
318		return;
319	}
320
321	/* Search for the right slot in the aggregation table.
322	 */
323	ag_cors = 0;
324	ag = ag_corsest;
325	while (ag != 0) {
326		if (ag->ag_mask >= mask)
327			break;
328
329		/* Suppress old routes (i.e. combine with compatible routes
330		 * with coarser masks) as we look for the right slot in the
331		 * aggregation table for the new route.
332		 * A route to an address less than the current destination
333		 * will not be affected by the current route or any route
334		 * seen hereafter.  That means it is safe to suppress it.
335		 * This check keeps poor routes (e.g. with large hop counts)
336		 * from preventing suppression of finer routes.
337		 */
338		if (ag_cors != 0
339		    && ag->ag_dst_h < dst
340		    && (ag->ag_state & AGS_SUPPRESS)
341		    && ag_cors->ag_pref <= ag->ag_pref
342		    && (ag->ag_dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h
343		    && (ag_cors->ag_gate == ag->ag_gate
344			|| (ag->ag_state & AGS_FINE_GATE)
345			|| (ag_cors->ag_state & AGS_CORS_GATE))) {
346			/*  If the suppressed target was redundant,
347			 * then mark the suppressor redundant.
348			 */
349			if (AG_IS_REDUN(ag->ag_state)
350			    && ag_cors->ag_mask == ag->ag_mask<<1) {
351				if (ag_cors->ag_dst_h == dst)
352					ag_cors->ag_state |= AGS_REDUN0;
353				else
354					ag_cors->ag_state |= AGS_REDUN1;
355			}
356			if (ag->ag_tag != ag_cors->ag_tag)
357				ag_cors->ag_tag = 0;
358			if (ag->ag_nhop != ag_cors->ag_nhop)
359				ag_cors->ag_nhop = 0;
360			ag_del(ag);
361			CHECK_AG();
362		} else {
363			ag_cors = ag;
364		}
365		ag = ag_cors->ag_fine;
366	}
367
368	/* If we find the even/odd twin of the new route, and if the
369	 * masks and so forth are equal, we can aggregate them.
370	 * We can probably promote one of the pair.
371	 *
372	 * Since the routes are encountered in lexical order,
373	 * the new route must be odd.  However, the second or later
374	 * times around this loop, it could be the even twin promoted
375	 * from the even/odd pair of twins of the finer route.
376	 */
377	while (ag != 0
378	       && ag->ag_mask == mask
379	       && ((ag->ag_dst_h ^ dst) & (mask<<1)) == 0) {
380
381		/* Here we know the target route and the route in the current
382		 * slot have the same netmasks and differ by at most the
383		 * last bit.  They are either for the same destination, or
384		 * for an even/odd pair of destinations.
385		 */
386		if (ag->ag_dst_h == dst) {
387			/* We have two routes to the same destination.
388			 * Routes are encountered in lexical order, so a
389			 * route is never promoted until the parent route is
390			 * already present.  So we know that the new route is
391			 * a promoted (or aggregated) pair and the route
392			 * already in the slot is the explicit route.
393			 *
394			 * Prefer the best route if their metrics differ,
395			 * or the aggregated one if not, following a sort
396			 * of longest-match rule.
397			 */
398			if (pref <= ag->ag_pref) {
399				ag->ag_gate = gate;
400				ag->ag_nhop = nhop;
401				ag->ag_tag = tag;
402				ag->ag_metric = metric;
403				ag->ag_pref = pref;
404				if (ag->ag_seqno < new_seqno)
405					ag->ag_seqno = new_seqno;
406				x = ag->ag_state;
407				ag->ag_state = state;
408				state = x;
409			}
410
411			/* Some bits are set if they are set on either route,
412			 * except when the route is for an interface.
413			 */
414			if (!(ag->ag_state & AGS_IF))
415				ag->ag_state |= (state & (AGS_AGGREGATE_EITHER
416							| AGS_REDUN0
417							| AGS_REDUN1));
418			return;
419		}
420
421		/* If one of the routes can be promoted and the other can
422		 * be suppressed, it may be possible to combine them or
423		 * worthwhile to promote one.
424		 *
425		 * Any route that can be promoted is always
426		 * marked to be eligible to be suppressed.
427		 */
428		if (!((state & AGS_AGGREGATE)
429		      && (ag->ag_state & AGS_SUPPRESS))
430		    && !((ag->ag_state & AGS_AGGREGATE)
431			 && (state & AGS_SUPPRESS)))
432			break;
433
434		/* A pair of even/odd twin routes can be combined
435		 * if either is redundant, or if they are via the
436		 * same gateway and have the same metric.
437		 */
438		if (AG_IS_REDUN(ag->ag_state)
439		    || AG_IS_REDUN(state)
440		    || (ag->ag_gate == gate
441			&& ag->ag_pref == pref
442			&& (state & ag->ag_state & AGS_AGGREGATE) != 0)) {
443
444			/* We have both the even and odd pairs.
445			 * Since the routes are encountered in order,
446			 * the route in the slot must be the even twin.
447			 *
448			 * Combine and promote (aggregate) the pair of routes.
449			 */
450			if (new_seqno < ag->ag_seqno)
451				new_seqno = ag->ag_seqno;
452			if (!AG_IS_REDUN(state))
453				state &= ~AGS_REDUN1;
454			if (AG_IS_REDUN(ag->ag_state))
455				state |= AGS_REDUN0;
456			else
457				state &= ~AGS_REDUN0;
458			state |= (ag->ag_state & AGS_AGGREGATE_EITHER);
459			if (ag->ag_tag != tag)
460				tag = 0;
461			if (ag->ag_nhop != nhop)
462				nhop = 0;
463
464			/* Get rid of the even twin that was already
465			 * in the slot.
466			 */
467			ag_del(ag);
468
469		} else if (ag->ag_pref >= pref
470			   && (ag->ag_state & AGS_AGGREGATE)) {
471			/* If we cannot combine the pair, maybe the route
472			 * with the worse metric can be promoted.
473			 *
474			 * Promote the old, even twin, by giving its slot
475			 * in the table to the new, odd twin.
476			 */
477			ag->ag_dst_h = dst;
478
479			xaddr = ag->ag_gate;
480			ag->ag_gate = gate;
481			gate = xaddr;
482
483			xaddr = ag->ag_nhop;
484			ag->ag_nhop = nhop;
485			nhop = xaddr;
486
487			x = ag->ag_tag;
488			ag->ag_tag = tag;
489			tag = x;
490
491			/* The promoted route is even-redundant only if the
492			 * even twin was fully redundant.  It is not
493			 * odd-redundant because the odd-twin will still be
494			 * in the table.
495			 */
496			x = ag->ag_state;
497			if (!AG_IS_REDUN(x))
498				x &= ~AGS_REDUN0;
499			x &= ~AGS_REDUN1;
500			ag->ag_state = state;
501			state = x;
502
503			x = ag->ag_metric;
504			ag->ag_metric = metric;
505			metric = x;
506
507			x = ag->ag_pref;
508			ag->ag_pref = pref;
509			pref = x;
510
511			/* take the newest sequence number */
512			if (new_seqno <= ag->ag_seqno)
513				new_seqno = ag->ag_seqno;
514			else
515				ag->ag_seqno = new_seqno;
516
517		} else {
518			if (!(state & AGS_AGGREGATE))
519				break;	/* cannot promote either twin */
520
521			/* Promote the new, odd twin by shaving its
522			 * mask and address.
523			 * The promoted route is odd-redundant only if the
524			 * odd twin was fully redundant.  It is not
525			 * even-redundant because the even twin is still in
526			 * the table.
527			 */
528			if (!AG_IS_REDUN(state))
529				state &= ~AGS_REDUN1;
530			state &= ~AGS_REDUN0;
531			if (new_seqno < ag->ag_seqno)
532				new_seqno = ag->ag_seqno;
533			else
534				ag->ag_seqno = new_seqno;
535		}
536
537		mask <<= 1;
538		dst &= mask;
539
540		if (ag_cors == 0) {
541			ag = ag_corsest;
542			break;
543		}
544		ag = ag_cors;
545		ag_cors = ag->ag_cors;
546	}
547
548	/* When we can no longer promote and combine routes,
549	 * flush the old route in the target slot.  Also flush
550	 * any finer routes that we know will never be aggregated by
551	 * the new route.
552	 *
553	 * In case we moved toward coarser masks,
554	 * get back where we belong
555	 */
556	if (ag != 0
557	    && ag->ag_mask < mask) {
558		ag_cors = ag;
559		ag = ag->ag_fine;
560	}
561
562	/* Empty the target slot
563	 */
564	if (ag != 0 && ag->ag_mask == mask) {
565		ag_flush(ag->ag_dst_h, ag->ag_mask, out);
566		ag = (ag_cors == 0) ? ag_corsest : ag_cors->ag_fine;
567	}
568
569#ifdef DEBUG_AG
570	(void)fflush(stderr);
571	if (ag == 0 && ag_cors != ag_finest)
572		abort();
573	if (ag_cors == 0 && ag != ag_corsest)
574		abort();
575	if (ag != 0 && ag->ag_cors != ag_cors)
576		abort();
577	if (ag_cors != 0 && ag_cors->ag_fine != ag)
578		abort();
579	CHECK_AG();
580#endif
581
582	/* Save the new route on the end of the table.
583	 */
584	nag = ag_avail;
585	ag_avail = nag->ag_fine;
586
587	nag->ag_dst_h = dst;
588	nag->ag_mask = mask;
589	nag->ag_gate = gate;
590	nag->ag_nhop = nhop;
591	nag->ag_metric = metric;
592	nag->ag_pref = pref;
593	nag->ag_tag = tag;
594	nag->ag_state = state;
595	nag->ag_seqno = new_seqno;
596
597	nag->ag_fine = ag;
598	if (ag != 0)
599		ag->ag_cors = nag;
600	else
601		ag_finest = nag;
602	nag->ag_cors = ag_cors;
603	if (ag_cors == 0)
604		ag_corsest = nag;
605	else
606		ag_cors->ag_fine = nag;
607	CHECK_AG();
608}
609
610
611#define	NAME0_LEN 14
612static const char *
613rtm_type_name(u_char type)
614{
615	static const char *rtm_types[] = {
616		"RTM_ADD",
617		"RTM_DELETE",
618		"RTM_CHANGE",
619		"RTM_GET",
620		"RTM_LOSING",
621		"RTM_REDIRECT",
622		"RTM_MISS",
623		"RTM_LOCK",
624		"RTM_OLDADD",
625		"RTM_OLDDEL",
626		"RTM_RESOLVE",
627		"RTM_NEWADDR",
628		"RTM_DELADDR",
629#ifdef RTM_OIFINFO
630		"RTM_OIFINFO",
631#endif
632		"RTM_IFINFO",
633		"RTM_NEWMADDR",
634		"RTM_DELMADDR"
635	};
636#define NEW_RTM_PAT "RTM type %#x"
637	static char name0[sizeof(NEW_RTM_PAT)+2];
638
639
640	if (type > sizeof(rtm_types)/sizeof(rtm_types[0])
641	    || type == 0) {
642		snprintf(name0, sizeof(name0), NEW_RTM_PAT, type);
643		return name0;
644	} else {
645		return rtm_types[type-1];
646	}
647#undef NEW_RTM_PAT
648}
649
650
651/* Trim a mask in a sockaddr
652 *	Produce a length of 0 for an address of 0.
653 *	Otherwise produce the index of the first zero byte.
654 */
655void
656#ifdef _HAVE_SIN_LEN
657masktrim(struct sockaddr_in *ap)
658#else
659masktrim(struct sockaddr_in_new *ap)
660#endif
661{
662	char *cp;
663
664	if (ap->sin_addr.s_addr == 0) {
665		ap->sin_len = 0;
666		return;
667	}
668	cp = (char *)(&ap->sin_addr.s_addr+1);
669	while (*--cp == 0)
670		continue;
671	ap->sin_len = cp - (char*)ap + 1;
672}
673
674
675/* Tell the kernel to add, delete or change a route
676 */
677static void
678rtioctl(int action,			/* RTM_DELETE, etc */
679	naddr dst,
680	naddr gate,
681	naddr mask,
682	int metric,
683	int flags)
684{
685	struct {
686		struct rt_msghdr w_rtm;
687		struct sockaddr_in w_dst;
688		struct sockaddr_in w_gate;
689#ifdef _HAVE_SA_LEN
690		struct sockaddr_in w_mask;
691#else
692		struct sockaddr_in_new w_mask;
693#endif
694	} w;
695	long cc;
696#   define PAT " %-10s %s metric=%d flags=%#x"
697#   define ARGS rtm_type_name(action), rtname(dst,mask,gate), metric, flags
698
699again:
700	memset(&w, 0, sizeof(w));
701	w.w_rtm.rtm_msglen = sizeof(w);
702	w.w_rtm.rtm_version = RTM_VERSION;
703	w.w_rtm.rtm_type = action;
704	w.w_rtm.rtm_flags = flags;
705	w.w_rtm.rtm_seq = ++rt_sock_seqno;
706	w.w_rtm.rtm_addrs = RTA_DST|RTA_GATEWAY;
707	if (metric != 0 || action == RTM_CHANGE) {
708		w.w_rtm.rtm_rmx.rmx_hopcount = metric;
709		w.w_rtm.rtm_inits |= RTV_HOPCOUNT;
710	}
711	w.w_dst.sin_family = AF_INET;
712	w.w_dst.sin_addr.s_addr = dst;
713	w.w_gate.sin_family = AF_INET;
714	w.w_gate.sin_addr.s_addr = gate;
715#ifdef _HAVE_SA_LEN
716	w.w_dst.sin_len = sizeof(w.w_dst);
717	w.w_gate.sin_len = sizeof(w.w_gate);
718#endif
719	if (mask == HOST_MASK) {
720		w.w_rtm.rtm_flags |= RTF_HOST;
721		w.w_rtm.rtm_msglen -= sizeof(w.w_mask);
722	} else {
723		w.w_rtm.rtm_addrs |= RTA_NETMASK;
724		w.w_mask.sin_addr.s_addr = htonl(mask);
725#ifdef _HAVE_SA_LEN
726		masktrim(&w.w_mask);
727		if (w.w_mask.sin_len == 0)
728			w.w_mask.sin_len = sizeof(long);
729		w.w_rtm.rtm_msglen -= (sizeof(w.w_mask) - w.w_mask.sin_len);
730#endif
731	}
732
733#ifndef NO_INSTALL
734	cc = write(rt_sock, &w, w.w_rtm.rtm_msglen);
735	if (cc < 0) {
736		if (errno == ESRCH
737		    && (action == RTM_CHANGE || action == RTM_DELETE)) {
738			trace_act("route disappeared before" PAT, ARGS);
739			if (action == RTM_CHANGE) {
740				action = RTM_ADD;
741				goto again;
742			}
743			return;
744		}
745		msglog("write(rt_sock)" PAT ": %s", ARGS, strerror(errno));
746		return;
747	} else if (cc != w.w_rtm.rtm_msglen) {
748		msglog("write(rt_sock) wrote %ld instead of %d for" PAT,
749		       cc, w.w_rtm.rtm_msglen, ARGS);
750		return;
751	}
752#endif
753	if (TRACEKERNEL)
754		trace_misc("write kernel" PAT, ARGS);
755#undef PAT
756#undef ARGS
757}
758
759
760#define KHASH_SIZE 71			/* should be prime */
761#define KHASH(a,m) khash_bins[((a) ^ (m)) % KHASH_SIZE]
762static struct khash {
763	struct khash *k_next;
764	naddr	k_dst;
765	naddr	k_mask;
766	naddr	k_gate;
767	short	k_metric;
768	u_short	k_state;
769#define	    KS_NEW	0x001
770#define	    KS_DELETE	0x002		/* need to delete the route */
771#define	    KS_ADD	0x004		/* add to the kernel */
772#define	    KS_CHANGE	0x008		/* tell kernel to change the route */
773#define	    KS_DEL_ADD	0x010		/* delete & add to change the kernel */
774#define	    KS_STATIC	0x020		/* Static flag in kernel */
775#define	    KS_GATEWAY	0x040		/* G flag in kernel */
776#define	    KS_DYNAMIC	0x080		/* result of redirect */
777#define	    KS_DELETED	0x100		/* already deleted from kernel */
778#define	    KS_CHECK	0x200
779	time_t	k_keep;
780#define	    K_KEEP_LIM	30
781	time_t	k_redirect_time;	/* when redirected route 1st seen */
782} *khash_bins[KHASH_SIZE];
783
784
785static struct khash*
786kern_find(naddr dst, naddr mask, struct khash ***ppk)
787{
788	struct khash *k, **pk;
789
790	for (pk = &KHASH(dst,mask); (k = *pk) != 0; pk = &k->k_next) {
791		if (k->k_dst == dst && k->k_mask == mask)
792			break;
793	}
794	if (ppk != 0)
795		*ppk = pk;
796	return k;
797}
798
799
800static struct khash*
801kern_add(naddr dst, naddr mask)
802{
803	struct khash *k, **pk;
804
805	k = kern_find(dst, mask, &pk);
806	if (k != 0)
807		return k;
808
809	k = (struct khash *)rtmalloc(sizeof(*k), "kern_add");
810
811	memset(k, 0, sizeof(*k));
812	k->k_dst = dst;
813	k->k_mask = mask;
814	k->k_state = KS_NEW;
815	k->k_keep = now.tv_sec;
816	*pk = k;
817
818	return k;
819}
820
821
822/* If a kernel route has a non-zero metric, check that it is still in the
823 *	daemon table, and not deleted by interfaces coming and going.
824 */
825static void
826kern_check_static(struct khash *k,
827		  struct interface *ifp)
828{
829	struct rt_entry *rt;
830	struct rt_spare new;
831
832	if (k->k_metric == 0)
833		return;
834
835	memset(&new, 0, sizeof(new));
836	new.rts_ifp = ifp;
837	new.rts_gate = k->k_gate;
838	new.rts_router = (ifp != 0) ? ifp->int_addr : loopaddr;
839	new.rts_metric = k->k_metric;
840	new.rts_time = now.tv_sec;
841
842	rt = rtget(k->k_dst, k->k_mask);
843	if (rt != 0) {
844		if (!(rt->rt_state & RS_STATIC))
845			rtchange(rt, rt->rt_state | RS_STATIC, &new, 0);
846	} else {
847		rtadd(k->k_dst, k->k_mask, RS_STATIC, &new);
848	}
849}
850
851
852/* operate on a kernel entry
853 */
854static void
855kern_ioctl(struct khash *k,
856	   int action,			/* RTM_DELETE, etc */
857	   int flags)
858
859{
860	switch (action) {
861	case RTM_DELETE:
862		k->k_state &= ~KS_DYNAMIC;
863		if (k->k_state & KS_DELETED)
864			return;
865		k->k_state |= KS_DELETED;
866		break;
867	case RTM_ADD:
868		k->k_state &= ~KS_DELETED;
869		break;
870	case RTM_CHANGE:
871		if (k->k_state & KS_DELETED) {
872			action = RTM_ADD;
873			k->k_state &= ~KS_DELETED;
874		}
875		break;
876	}
877
878	rtioctl(action, k->k_dst, k->k_gate, k->k_mask, k->k_metric, flags);
879}
880
881
882/* add a route the kernel told us
883 */
884static void
885rtm_add(struct rt_msghdr *rtm,
886	struct rt_addrinfo *info,
887	time_t keep)
888{
889	struct khash *k;
890	struct interface *ifp;
891	naddr mask;
892
893
894	if (rtm->rtm_flags & RTF_HOST) {
895		mask = HOST_MASK;
896	} else if (INFO_MASK(info) != 0) {
897		mask = ntohl(S_ADDR(INFO_MASK(info)));
898	} else {
899		msglog("ignore %s without mask", rtm_type_name(rtm->rtm_type));
900		return;
901	}
902
903	k = kern_add(S_ADDR(INFO_DST(info)), mask);
904	if (k->k_state & KS_NEW)
905		k->k_keep = now.tv_sec+keep;
906	if (INFO_GATE(info) == 0) {
907		trace_act("note %s without gateway",
908			  rtm_type_name(rtm->rtm_type));
909		k->k_metric = HOPCNT_INFINITY;
910	} else if (INFO_GATE(info)->sa_family != AF_INET) {
911		trace_act("note %s with gateway AF=%d",
912			  rtm_type_name(rtm->rtm_type),
913			  INFO_GATE(info)->sa_family);
914		k->k_metric = HOPCNT_INFINITY;
915	} else {
916		k->k_gate = S_ADDR(INFO_GATE(info));
917		k->k_metric = rtm->rtm_rmx.rmx_hopcount;
918		if (k->k_metric < 0)
919			k->k_metric = 0;
920		else if (k->k_metric > HOPCNT_INFINITY-1)
921			k->k_metric = HOPCNT_INFINITY-1;
922	}
923	k->k_state &= ~(KS_DELETE | KS_ADD | KS_CHANGE | KS_DEL_ADD
924			| KS_DELETED | KS_GATEWAY | KS_STATIC
925			| KS_NEW | KS_CHECK);
926	if (rtm->rtm_flags & RTF_GATEWAY)
927		k->k_state |= KS_GATEWAY;
928	if (rtm->rtm_flags & RTF_STATIC)
929		k->k_state |= KS_STATIC;
930
931	if (0 != (rtm->rtm_flags & (RTF_DYNAMIC | RTF_MODIFIED))) {
932		if (INFO_AUTHOR(info) != 0
933		    && INFO_AUTHOR(info)->sa_family == AF_INET)
934			ifp = iflookup(S_ADDR(INFO_AUTHOR(info)));
935		else
936			ifp = 0;
937		if (supplier
938		    && (ifp == 0 || !(ifp->int_state & IS_REDIRECT_OK))) {
939			/* Routers are not supposed to listen to redirects,
940			 * so delete it if it came via an unknown interface
941			 * or the interface does not have special permission.
942			 */
943			k->k_state &= ~KS_DYNAMIC;
944			k->k_state |= KS_DELETE;
945			LIM_SEC(need_kern, 0);
946			trace_act("mark for deletion redirected %s --> %s"
947				  " via %s",
948				  addrname(k->k_dst, k->k_mask, 0),
949				  naddr_ntoa(k->k_gate),
950				  ifp ? ifp->int_name : "unknown interface");
951		} else {
952			k->k_state |= KS_DYNAMIC;
953			k->k_redirect_time = now.tv_sec;
954			trace_act("accept redirected %s --> %s via %s",
955				  addrname(k->k_dst, k->k_mask, 0),
956				  naddr_ntoa(k->k_gate),
957				  ifp ? ifp->int_name : "unknown interface");
958		}
959		return;
960	}
961
962	/* If it is not a static route, quit until the next comparison
963	 * between the kernel and daemon tables, when it will be deleted.
964	 */
965	if (!(k->k_state & KS_STATIC)) {
966		k->k_state |= KS_DELETE;
967		LIM_SEC(need_kern, k->k_keep);
968		return;
969	}
970
971	/* Put static routes with real metrics into the daemon table so
972	 * they can be advertised.
973	 *
974	 * Find the interface toward the gateway.
975	 */
976	ifp = iflookup(k->k_gate);
977	if (ifp == 0)
978		msglog("static route %s --> %s impossibly lacks ifp",
979		       addrname(S_ADDR(INFO_DST(info)), mask, 0),
980		       naddr_ntoa(k->k_gate));
981
982	kern_check_static(k, ifp);
983}
984
985
986/* deal with packet loss
987 */
988static void
989rtm_lose(struct rt_msghdr *rtm,
990	 struct rt_addrinfo *info)
991{
992	if (INFO_GATE(info) == 0
993	    || INFO_GATE(info)->sa_family != AF_INET) {
994		trace_act("ignore %s without gateway",
995			  rtm_type_name(rtm->rtm_type));
996		return;
997	}
998
999	if (rdisc_ok)
1000		rdisc_age(S_ADDR(INFO_GATE(info)));
1001	age(S_ADDR(INFO_GATE(info)));
1002}
1003
1004
1005/* Make the gateway slot of an info structure point to something
1006 * useful.  If it is not already useful, but it specifies an interface,
1007 * then fill in the sockaddr_in provided and point it there.
1008 */
1009static int
1010get_info_gate(struct sockaddr **sap,
1011	      struct sockaddr_in *rsin)
1012{
1013	struct sockaddr_dl *sdl = (struct sockaddr_dl *)*sap;
1014	struct interface *ifp;
1015
1016	if (sdl == 0)
1017		return 0;
1018	if ((sdl)->sdl_family == AF_INET)
1019		return 1;
1020	if ((sdl)->sdl_family != AF_LINK)
1021		return 0;
1022
1023	ifp = ifwithindex(sdl->sdl_index, 1);
1024	if (ifp == 0)
1025		return 0;
1026
1027	rsin->sin_addr.s_addr = ifp->int_addr;
1028#ifdef _HAVE_SA_LEN
1029	rsin->sin_len = sizeof(*rsin);
1030#endif
1031	rsin->sin_family = AF_INET;
1032	*sap = (struct sockaddr*)rsin;
1033
1034	return 1;
1035}
1036
1037
1038/* Clean the kernel table by copying it to the daemon image.
1039 * Eventually the daemon will delete any extra routes.
1040 */
1041void
1042flush_kern(void)
1043{
1044	static char *sysctl_buf;
1045	static size_t sysctl_buf_size = 0;
1046	size_t needed;
1047	int mib[6];
1048	char *next, *lim;
1049	struct rt_msghdr *rtm;
1050	struct sockaddr_in gate_sin;
1051	struct rt_addrinfo info;
1052	int i;
1053	struct khash *k;
1054
1055
1056	for (i = 0; i < KHASH_SIZE; i++) {
1057		for (k = khash_bins[i]; k != 0; k = k->k_next) {
1058			k->k_state |= KS_CHECK;
1059		}
1060	}
1061
1062	mib[0] = CTL_NET;
1063	mib[1] = PF_ROUTE;
1064	mib[2] = 0;		/* protocol */
1065	mib[3] = 0;		/* wildcard address family */
1066	mib[4] = NET_RT_DUMP;
1067	mib[5] = 0;		/* no flags */
1068	for (;;) {
1069		if ((needed = sysctl_buf_size) != 0) {
1070			if (sysctl(mib, 6, sysctl_buf,&needed, 0, 0) >= 0)
1071				break;
1072			if (errno != ENOMEM && errno != EFAULT)
1073				BADERR(1,"flush_kern: sysctl(RT_DUMP)");
1074			free(sysctl_buf);
1075			needed = 0;
1076		}
1077		if (sysctl(mib, 6, 0, &needed, 0, 0) < 0)
1078			BADERR(1,"flush_kern: sysctl(RT_DUMP) estimate");
1079		/* Kludge around the habit of some systems, such as
1080		 * BSD/OS 3.1, to not admit how many routes are in the
1081		 * kernel, or at least to be quite wrong.
1082		 */
1083		needed += 50*(sizeof(*rtm)+5*sizeof(struct sockaddr));
1084		sysctl_buf = rtmalloc(sysctl_buf_size = needed,
1085				      "flush_kern sysctl(RT_DUMP)");
1086	}
1087
1088	lim = sysctl_buf + needed;
1089	for (next = sysctl_buf; next < lim; next += rtm->rtm_msglen) {
1090		rtm = (struct rt_msghdr *)next;
1091		if (rtm->rtm_msglen == 0) {
1092			msglog("zero length kernel route at "
1093			       " %#lx in buffer %#lx before %#lx",
1094			       (u_long)rtm, (u_long)sysctl_buf, (u_long)lim);
1095			break;
1096		}
1097
1098		rt_xaddrs(&info,
1099			  (struct sockaddr *)(rtm+1),
1100			  (struct sockaddr *)(next + rtm->rtm_msglen),
1101			  rtm->rtm_addrs);
1102
1103		if (INFO_DST(&info) == 0
1104		    || INFO_DST(&info)->sa_family != AF_INET)
1105			continue;
1106
1107		/* ignore ARP table entries on systems with a merged route
1108		 * and ARP table.
1109		 */
1110		if (rtm->rtm_flags & RTF_LLINFO)
1111			continue;
1112
1113#if defined(RTF_CLONED) && defined(__bsdi__)
1114		/* ignore cloned routes
1115		 */
1116		if (rtm->rtm_flags & RTF_CLONED)
1117			continue;
1118#endif
1119
1120		/* ignore multicast addresses
1121		 */
1122		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info)))))
1123			continue;
1124
1125		if (!get_info_gate(&INFO_GATE(&info), &gate_sin))
1126			continue;
1127
1128		/* Note static routes and interface routes, and also
1129		 * preload the image of the kernel table so that
1130		 * we can later clean it, as well as avoid making
1131		 * unneeded changes.  Keep the old kernel routes for a
1132		 * few seconds to allow a RIP or router-discovery
1133		 * response to be heard.
1134		 */
1135		rtm_add(rtm,&info,MIN_WAITTIME);
1136	}
1137
1138	for (i = 0; i < KHASH_SIZE; i++) {
1139		for (k = khash_bins[i]; k != 0; k = k->k_next) {
1140			if (k->k_state & KS_CHECK) {
1141				msglog("%s --> %s disappeared from kernel",
1142				       addrname(k->k_dst, k->k_mask, 0),
1143				       naddr_ntoa(k->k_gate));
1144				del_static(k->k_dst, k->k_mask, k->k_gate, 1);
1145			}
1146		}
1147	}
1148}
1149
1150
1151/* Listen to announcements from the kernel
1152 */
1153void
1154read_rt(void)
1155{
1156	long cc;
1157	struct interface *ifp;
1158	struct sockaddr_in gate_sin;
1159	naddr mask, gate;
1160	union {
1161		struct {
1162			struct rt_msghdr rtm;
1163			struct sockaddr addrs[RTAX_MAX];
1164		} r;
1165		struct if_msghdr ifm;
1166	} m;
1167	char str[100], *strp;
1168	struct rt_addrinfo info;
1169
1170
1171	for (;;) {
1172		cc = read(rt_sock, &m, sizeof(m));
1173		if (cc <= 0) {
1174			if (cc < 0 && errno != EWOULDBLOCK)
1175				LOGERR("read(rt_sock)");
1176			return;
1177		}
1178
1179		if (m.r.rtm.rtm_version != RTM_VERSION) {
1180			msglog("bogus routing message version %d",
1181			       m.r.rtm.rtm_version);
1182			continue;
1183		}
1184
1185		/* Ignore our own results.
1186		 */
1187		if (m.r.rtm.rtm_type <= RTM_CHANGE
1188		    && m.r.rtm.rtm_pid == mypid) {
1189			static int complained = 0;
1190			if (!complained) {
1191				msglog("receiving our own change messages");
1192				complained = 1;
1193			}
1194			continue;
1195		}
1196
1197		if (m.r.rtm.rtm_type == RTM_IFINFO
1198		    || m.r.rtm.rtm_type == RTM_NEWADDR
1199		    || m.r.rtm.rtm_type == RTM_DELADDR) {
1200			ifp = ifwithindex(m.ifm.ifm_index,
1201					  m.r.rtm.rtm_type != RTM_DELADDR);
1202			if (ifp == 0)
1203				trace_act("note %s with flags %#x"
1204					  " for unknown interface index #%d",
1205					  rtm_type_name(m.r.rtm.rtm_type),
1206					  m.ifm.ifm_flags,
1207					  m.ifm.ifm_index);
1208			else
1209				trace_act("note %s with flags %#x for %s",
1210					  rtm_type_name(m.r.rtm.rtm_type),
1211					  m.ifm.ifm_flags,
1212					  ifp->int_name);
1213
1214			/* After being informed of a change to an interface,
1215			 * check them all now if the check would otherwise
1216			 * be a long time from now, if the interface is
1217			 * not known, or if the interface has been turned
1218			 * off or on.
1219			 */
1220			if (ifinit_timer.tv_sec-now.tv_sec>=CHECK_BAD_INTERVAL
1221			    || ifp == 0
1222			    || ((ifp->int_if_flags ^ m.ifm.ifm_flags)
1223				& IFF_UP) != 0)
1224				ifinit_timer.tv_sec = now.tv_sec;
1225			continue;
1226		}
1227#ifdef RTM_OIFINFO
1228		if (m.r.rtm.rtm_type == RTM_OIFINFO)
1229			continue;	/* ignore compat message */
1230#endif
1231
1232		strcpy(str, rtm_type_name(m.r.rtm.rtm_type));
1233		strp = &str[strlen(str)];
1234		if (m.r.rtm.rtm_type <= RTM_CHANGE)
1235			strp += sprintf(strp," from pid %d",m.r.rtm.rtm_pid);
1236
1237		rt_xaddrs(&info, m.r.addrs, &m.r.addrs[RTAX_MAX],
1238			  m.r.rtm.rtm_addrs);
1239
1240		if (INFO_DST(&info) == 0) {
1241			trace_act("ignore %s without dst", str);
1242			continue;
1243		}
1244
1245		if (INFO_DST(&info)->sa_family != AF_INET) {
1246			trace_act("ignore %s for AF %d", str,
1247				  INFO_DST(&info)->sa_family);
1248			continue;
1249		}
1250
1251		mask = ((INFO_MASK(&info) != 0)
1252			? ntohl(S_ADDR(INFO_MASK(&info)))
1253			: (m.r.rtm.rtm_flags & RTF_HOST)
1254			? HOST_MASK
1255			: std_mask(S_ADDR(INFO_DST(&info))));
1256
1257		strp += sprintf(strp, ": %s",
1258				addrname(S_ADDR(INFO_DST(&info)), mask, 0));
1259
1260		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info))))) {
1261			trace_act("ignore multicast %s", str);
1262			continue;
1263		}
1264
1265		if (m.r.rtm.rtm_flags & RTF_LLINFO) {
1266			trace_act("ignore ARP %s", str);
1267			continue;
1268		}
1269
1270#if defined(RTF_CLONED) && defined(__bsdi__)
1271		if (m.r.rtm.rtm_flags & RTF_CLONED) {
1272			trace_act("ignore cloned %s", str);
1273			continue;
1274		}
1275#endif
1276
1277		if (get_info_gate(&INFO_GATE(&info), &gate_sin)) {
1278			gate = S_ADDR(INFO_GATE(&info));
1279			strp += sprintf(strp, " --> %s", naddr_ntoa(gate));
1280		} else {
1281			gate = 0;
1282		}
1283
1284		if (INFO_AUTHOR(&info) != 0)
1285			strp += sprintf(strp, " by authority of %s",
1286					saddr_ntoa(INFO_AUTHOR(&info)));
1287
1288		switch (m.r.rtm.rtm_type) {
1289		case RTM_ADD:
1290		case RTM_CHANGE:
1291		case RTM_REDIRECT:
1292			if (m.r.rtm.rtm_errno != 0) {
1293				trace_act("ignore %s with \"%s\" error",
1294					  str, strerror(m.r.rtm.rtm_errno));
1295			} else {
1296				trace_act("%s", str);
1297				rtm_add(&m.r.rtm,&info,0);
1298			}
1299			break;
1300
1301		case RTM_DELETE:
1302			if (m.r.rtm.rtm_errno != 0
1303			    && m.r.rtm.rtm_errno != ESRCH) {
1304				trace_act("ignore %s with \"%s\" error",
1305					  str, strerror(m.r.rtm.rtm_errno));
1306			} else {
1307				trace_act("%s", str);
1308				del_static(S_ADDR(INFO_DST(&info)), mask,
1309					   gate, 1);
1310			}
1311			break;
1312
1313		case RTM_LOSING:
1314			trace_act("%s", str);
1315			rtm_lose(&m.r.rtm,&info);
1316			break;
1317
1318		default:
1319			trace_act("ignore %s", str);
1320			break;
1321		}
1322	}
1323}
1324
1325
1326/* after aggregating, note routes that belong in the kernel
1327 */
1328static void
1329kern_out(struct ag_info *ag)
1330{
1331	struct khash *k;
1332
1333
1334	/* Do not install bad routes if they are not already present.
1335	 * This includes routes that had RS_NET_SYN for interfaces that
1336	 * recently died.
1337	 */
1338	if (ag->ag_metric == HOPCNT_INFINITY) {
1339		k = kern_find(htonl(ag->ag_dst_h), ag->ag_mask, 0);
1340		if (k == 0)
1341			return;
1342	} else {
1343		k = kern_add(htonl(ag->ag_dst_h), ag->ag_mask);
1344	}
1345
1346	if (k->k_state & KS_NEW) {
1347		/* will need to add new entry to the kernel table */
1348		k->k_state = KS_ADD;
1349		if (ag->ag_state & AGS_GATEWAY)
1350			k->k_state |= KS_GATEWAY;
1351		k->k_gate = ag->ag_gate;
1352		k->k_metric = ag->ag_metric;
1353		return;
1354	}
1355
1356	if (k->k_state & KS_STATIC)
1357		return;
1358
1359	/* modify existing kernel entry if necessary */
1360	if (k->k_gate != ag->ag_gate
1361	    || k->k_metric != ag->ag_metric) {
1362		/* Must delete bad interface routes etc. to change them. */
1363		if (k->k_metric == HOPCNT_INFINITY)
1364			k->k_state |= KS_DEL_ADD;
1365		k->k_gate = ag->ag_gate;
1366		k->k_metric = ag->ag_metric;
1367		k->k_state |= KS_CHANGE;
1368	}
1369
1370	/* If the daemon thinks the route should exist, forget
1371	 * about any redirections.
1372	 * If the daemon thinks the route should exist, eventually
1373	 * override manual intervention by the operator.
1374	 */
1375	if ((k->k_state & (KS_DYNAMIC | KS_DELETED)) != 0) {
1376		k->k_state &= ~KS_DYNAMIC;
1377		k->k_state |= (KS_ADD | KS_DEL_ADD);
1378	}
1379
1380	if ((k->k_state & KS_GATEWAY)
1381	    && !(ag->ag_state & AGS_GATEWAY)) {
1382		k->k_state &= ~KS_GATEWAY;
1383		k->k_state |= (KS_ADD | KS_DEL_ADD);
1384	} else if (!(k->k_state & KS_GATEWAY)
1385		   && (ag->ag_state & AGS_GATEWAY)) {
1386		k->k_state |= KS_GATEWAY;
1387		k->k_state |= (KS_ADD | KS_DEL_ADD);
1388	}
1389
1390	/* Deleting-and-adding is necessary to change aspects of a route.
1391	 * Just delete instead of deleting and then adding a bad route.
1392	 * Otherwise, we want to keep the route in the kernel.
1393	 */
1394	if (k->k_metric == HOPCNT_INFINITY
1395	    && (k->k_state & KS_DEL_ADD))
1396		k->k_state |= KS_DELETE;
1397	else
1398		k->k_state &= ~KS_DELETE;
1399#undef RT
1400}
1401
1402
1403/* ARGSUSED */
1404static int
1405walk_kern(struct radix_node *rn,
1406	  struct walkarg *argp UNUSED)
1407{
1408#define RT ((struct rt_entry *)rn)
1409	char metric, pref;
1410	u_int ags = 0;
1411
1412
1413	/* Do not install synthetic routes */
1414	if (RT->rt_state & RS_NET_SYN)
1415		return 0;
1416
1417	if (!(RT->rt_state & RS_IF)) {
1418		/* This is an ordinary route, not for an interface.
1419		 */
1420
1421		/* aggregate, ordinary good routes without regard to
1422		 * their metric
1423		 */
1424		pref = 1;
1425		ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1426
1427		/* Do not install host routes directly to hosts, to avoid
1428		 * interfering with ARP entries in the kernel table.
1429		 */
1430		if (RT_ISHOST(RT)
1431		    && ntohl(RT->rt_dst) == RT->rt_gate)
1432			return 0;
1433
1434	} else {
1435		/* This is an interface route.
1436		 * Do not install routes for "external" remote interfaces.
1437		 */
1438		if (RT->rt_ifp != 0 && (RT->rt_ifp->int_state & IS_EXTERNAL))
1439			return 0;
1440
1441		/* Interfaces should override received routes.
1442		 */
1443		pref = 0;
1444		ags |= (AGS_IF | AGS_CORS_GATE);
1445
1446		/* If it is not an interface, or an alias for an interface,
1447		 * it must be a "gateway."
1448		 *
1449		 * If it is a "remote" interface, it is also a "gateway" to
1450		 * the kernel if is not an alias.
1451		 */
1452		if (RT->rt_ifp == 0
1453		    || (RT->rt_ifp->int_state & IS_REMOTE))
1454			ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1455	}
1456
1457	/* If RIP is off and IRDP is on, let the route to the discovered
1458	 * route suppress any RIP routes.  Eventually the RIP routes
1459	 * will time-out and be deleted.  This reaches the steady-state
1460	 * quicker.
1461	 */
1462	if ((RT->rt_state & RS_RDISC) && rip_sock < 0)
1463		ags |= AGS_CORS_GATE;
1464
1465	metric = RT->rt_metric;
1466	if (metric == HOPCNT_INFINITY) {
1467		/* if the route is dead, so try hard to aggregate. */
1468		pref = HOPCNT_INFINITY;
1469		ags |= (AGS_FINE_GATE | AGS_SUPPRESS);
1470		ags &= ~(AGS_IF | AGS_CORS_GATE);
1471	}
1472
1473	ag_check(RT->rt_dst, RT->rt_mask, RT->rt_gate, 0,
1474		 metric,pref, 0, 0, ags, kern_out);
1475	return 0;
1476#undef RT
1477}
1478
1479
1480/* Update the kernel table to match the daemon table.
1481 */
1482static void
1483fix_kern(void)
1484{
1485	int i;
1486	struct khash *k, **pk;
1487
1488
1489	need_kern = age_timer;
1490
1491	/* Walk daemon table, updating the copy of the kernel table.
1492	 */
1493	(void)rn_walktree(rhead, walk_kern, 0);
1494	ag_flush(0,0,kern_out);
1495
1496	for (i = 0; i < KHASH_SIZE; i++) {
1497		for (pk = &khash_bins[i]; (k = *pk) != 0; ) {
1498			/* Do not touch static routes */
1499			if (k->k_state & KS_STATIC) {
1500				kern_check_static(k,0);
1501				pk = &k->k_next;
1502				continue;
1503			}
1504
1505			/* check hold on routes deleted by the operator */
1506			if (k->k_keep > now.tv_sec) {
1507				/* ensure we check when the hold is over */
1508				LIM_SEC(need_kern, k->k_keep);
1509				/* mark for the next cycle */
1510				k->k_state |= KS_DELETE;
1511				pk = &k->k_next;
1512				continue;
1513			}
1514
1515			if ((k->k_state & KS_DELETE)
1516			    && !(k->k_state & KS_DYNAMIC)) {
1517				kern_ioctl(k, RTM_DELETE, 0);
1518				*pk = k->k_next;
1519				free(k);
1520				continue;
1521			}
1522
1523			if (k->k_state & KS_DEL_ADD)
1524				kern_ioctl(k, RTM_DELETE, 0);
1525
1526			if (k->k_state & KS_ADD) {
1527				kern_ioctl(k, RTM_ADD,
1528					   ((0 != (k->k_state & (KS_GATEWAY
1529							| KS_DYNAMIC)))
1530					    ? RTF_GATEWAY : 0));
1531			} else if (k->k_state & KS_CHANGE) {
1532				kern_ioctl(k,  RTM_CHANGE,
1533					   ((0 != (k->k_state & (KS_GATEWAY
1534							| KS_DYNAMIC)))
1535					    ? RTF_GATEWAY : 0));
1536			}
1537			k->k_state &= ~(KS_ADD|KS_CHANGE|KS_DEL_ADD);
1538
1539			/* Mark this route to be deleted in the next cycle.
1540			 * This deletes routes that disappear from the
1541			 * daemon table, since the normal aging code
1542			 * will clear the bit for routes that have not
1543			 * disappeared from the daemon table.
1544			 */
1545			k->k_state |= KS_DELETE;
1546			pk = &k->k_next;
1547		}
1548	}
1549}
1550
1551
1552/* Delete a static route in the image of the kernel table.
1553 */
1554void
1555del_static(naddr dst,
1556	   naddr mask,
1557	   naddr gate,
1558	   int gone)
1559{
1560	struct khash *k;
1561	struct rt_entry *rt;
1562
1563	/* Just mark it in the table to be deleted next time the kernel
1564	 * table is updated.
1565	 * If it has already been deleted, mark it as such, and set its
1566	 * keep-timer so that it will not be deleted again for a while.
1567	 * This lets the operator delete a route added by the daemon
1568	 * and add a replacement.
1569	 */
1570	k = kern_find(dst, mask, 0);
1571	if (k != 0 && (gate == 0 || k->k_gate == gate)) {
1572		k->k_state &= ~(KS_STATIC | KS_DYNAMIC | KS_CHECK);
1573		k->k_state |= KS_DELETE;
1574		if (gone) {
1575			k->k_state |= KS_DELETED;
1576			k->k_keep = now.tv_sec + K_KEEP_LIM;
1577		}
1578	}
1579
1580	rt = rtget(dst, mask);
1581	if (rt != 0 && (rt->rt_state & RS_STATIC))
1582		rtbad(rt);
1583}
1584
1585
1586/* Delete all routes generated from ICMP Redirects that use a given gateway,
1587 * as well as old redirected routes.
1588 */
1589void
1590del_redirects(naddr bad_gate,
1591	      time_t old)
1592{
1593	int i;
1594	struct khash *k;
1595
1596
1597	for (i = 0; i < KHASH_SIZE; i++) {
1598		for (k = khash_bins[i]; k != 0; k = k->k_next) {
1599			if (!(k->k_state & KS_DYNAMIC)
1600			    || (k->k_state & KS_STATIC))
1601				continue;
1602
1603			if (k->k_gate != bad_gate
1604			    && k->k_redirect_time > old
1605			    && !supplier)
1606				continue;
1607
1608			k->k_state |= KS_DELETE;
1609			k->k_state &= ~KS_DYNAMIC;
1610			need_kern.tv_sec = now.tv_sec;
1611			trace_act("mark redirected %s --> %s for deletion",
1612				  addrname(k->k_dst, k->k_mask, 0),
1613				  naddr_ntoa(k->k_gate));
1614		}
1615	}
1616}
1617
1618
1619/* Start the daemon tables.
1620 */
1621extern int max_keylen;
1622
1623void
1624rtinit(void)
1625{
1626	int i;
1627	struct ag_info *ag;
1628
1629	/* Initialize the radix trees */
1630	max_keylen = sizeof(struct sockaddr_in);
1631	rn_init();
1632	rn_inithead((void**)&rhead, 32);
1633
1634	/* mark all of the slots in the table free */
1635	ag_avail = ag_slots;
1636	for (ag = ag_slots, i = 1; i < NUM_AG_SLOTS; i++) {
1637		ag->ag_fine = ag+1;
1638		ag++;
1639	}
1640}
1641
1642
1643#ifdef _HAVE_SIN_LEN
1644static struct sockaddr_in dst_sock = {sizeof(dst_sock), AF_INET, 0, {0}, {0}};
1645static struct sockaddr_in mask_sock = {sizeof(mask_sock), AF_INET, 0, {0}, {0}};
1646#else
1647static struct sockaddr_in_new dst_sock = {_SIN_ADDR_SIZE, AF_INET};
1648static struct sockaddr_in_new mask_sock = {_SIN_ADDR_SIZE, AF_INET};
1649#endif
1650
1651
1652static void
1653set_need_flash(void)
1654{
1655	if (!need_flash) {
1656		need_flash = 1;
1657		/* Do not send the flash update immediately.  Wait a little
1658		 * while to hear from other routers.
1659		 */
1660		no_flash.tv_sec = now.tv_sec + MIN_WAITTIME;
1661	}
1662}
1663
1664
1665/* Get a particular routing table entry
1666 */
1667struct rt_entry *
1668rtget(naddr dst, naddr mask)
1669{
1670	struct rt_entry *rt;
1671
1672	dst_sock.sin_addr.s_addr = dst;
1673	mask_sock.sin_addr.s_addr = htonl(mask);
1674	masktrim(&mask_sock);
1675	rt = (struct rt_entry *)rhead->rnh_lookup(&dst_sock,&mask_sock,rhead);
1676	if (!rt
1677	    || rt->rt_dst != dst
1678	    || rt->rt_mask != mask)
1679		return 0;
1680
1681	return rt;
1682}
1683
1684
1685/* Find a route to dst as the kernel would.
1686 */
1687struct rt_entry *
1688rtfind(naddr dst)
1689{
1690	dst_sock.sin_addr.s_addr = dst;
1691	return (struct rt_entry *)rhead->rnh_matchaddr(&dst_sock, rhead);
1692}
1693
1694
1695/* add a route to the table
1696 */
1697void
1698rtadd(naddr	dst,
1699      naddr	mask,
1700      u_int	state,			/* rt_state for the entry */
1701      struct	rt_spare *new)
1702{
1703	struct rt_entry *rt;
1704	naddr smask;
1705	int i;
1706	struct rt_spare *rts;
1707
1708	rt = (struct rt_entry *)rtmalloc(sizeof (*rt), "rtadd");
1709	memset(rt, 0, sizeof(*rt));
1710	for (rts = rt->rt_spares, i = NUM_SPARES; i != 0; i--, rts++)
1711		rts->rts_metric = HOPCNT_INFINITY;
1712
1713	rt->rt_nodes->rn_key = (caddr_t)&rt->rt_dst_sock;
1714	rt->rt_dst = dst;
1715	rt->rt_dst_sock.sin_family = AF_INET;
1716#ifdef _HAVE_SIN_LEN
1717	rt->rt_dst_sock.sin_len = dst_sock.sin_len;
1718#endif
1719	if (mask != HOST_MASK) {
1720		smask = std_mask(dst);
1721		if ((smask & ~mask) == 0 && mask > smask)
1722			state |= RS_SUBNET;
1723	}
1724	mask_sock.sin_addr.s_addr = htonl(mask);
1725	masktrim(&mask_sock);
1726	rt->rt_mask = mask;
1727	rt->rt_state = state;
1728	rt->rt_spares[0] = *new;
1729	rt->rt_time = now.tv_sec;
1730	rt->rt_poison_metric = HOPCNT_INFINITY;
1731	rt->rt_seqno = update_seqno;
1732
1733	if (++total_routes == MAX_ROUTES)
1734		msglog("have maximum (%d) routes", total_routes);
1735	if (TRACEACTIONS)
1736		trace_add_del("Add", rt);
1737
1738	need_kern.tv_sec = now.tv_sec;
1739	set_need_flash();
1740
1741	if (0 == rhead->rnh_addaddr(&rt->rt_dst_sock, &mask_sock,
1742				    rhead, rt->rt_nodes)) {
1743		msglog("rnh_addaddr() failed for %s mask=%#lx",
1744		       naddr_ntoa(dst), (u_long)mask);
1745		free(rt);
1746	}
1747}
1748
1749
1750/* notice a changed route
1751 */
1752void
1753rtchange(struct rt_entry *rt,
1754	 u_int	state,			/* new state bits */
1755	 struct rt_spare *new,
1756	 char	*label)
1757{
1758	if (rt->rt_metric != new->rts_metric) {
1759		/* Fix the kernel immediately if it seems the route
1760		 * has gone bad, since there may be a working route that
1761		 * aggregates this route.
1762		 */
1763		if (new->rts_metric == HOPCNT_INFINITY) {
1764			need_kern.tv_sec = now.tv_sec;
1765			if (new->rts_time >= now.tv_sec - EXPIRE_TIME)
1766				new->rts_time = now.tv_sec - EXPIRE_TIME;
1767		}
1768		rt->rt_seqno = update_seqno;
1769		set_need_flash();
1770	}
1771
1772	if (rt->rt_gate != new->rts_gate) {
1773		need_kern.tv_sec = now.tv_sec;
1774		rt->rt_seqno = update_seqno;
1775		set_need_flash();
1776	}
1777
1778	state |= (rt->rt_state & RS_SUBNET);
1779
1780	/* Keep various things from deciding ageless routes are stale.
1781	 */
1782	if (!AGE_RT(state, new->rts_ifp))
1783		new->rts_time = now.tv_sec;
1784
1785	if (TRACEACTIONS)
1786		trace_change(rt, state, new,
1787			     label ? label : "Chg   ");
1788
1789	rt->rt_state = state;
1790	rt->rt_spares[0] = *new;
1791}
1792
1793
1794/* check for a better route among the spares
1795 */
1796static struct rt_spare *
1797rts_better(struct rt_entry *rt)
1798{
1799	struct rt_spare *rts, *rts1;
1800	int i;
1801
1802	/* find the best alternative among the spares */
1803	rts = rt->rt_spares+1;
1804	for (i = NUM_SPARES, rts1 = rts+1; i > 2; i--, rts1++) {
1805		if (BETTER_LINK(rt,rts1,rts))
1806			rts = rts1;
1807	}
1808
1809	return rts;
1810}
1811
1812
1813/* switch to a backup route
1814 */
1815void
1816rtswitch(struct rt_entry *rt,
1817	 struct rt_spare *rts)
1818{
1819	struct rt_spare swap;
1820	char label[10];
1821
1822
1823	/* Do not change permanent routes */
1824	if (0 != (rt->rt_state & (RS_MHOME | RS_STATIC | RS_RDISC
1825				  | RS_NET_SYN | RS_IF)))
1826		return;
1827
1828	/* find the best alternative among the spares */
1829	if (rts == 0)
1830		rts = rts_better(rt);
1831
1832	/* Do not bother if it is not worthwhile.
1833	 */
1834	if (!BETTER_LINK(rt, rts, rt->rt_spares))
1835		return;
1836
1837	swap = rt->rt_spares[0];
1838	(void)sprintf(label, "Use #%d", (int)(rts - rt->rt_spares));
1839	rtchange(rt, rt->rt_state & ~(RS_NET_SYN | RS_RDISC), rts, label);
1840	if (swap.rts_metric == HOPCNT_INFINITY) {
1841		*rts = rts_empty;
1842	} else {
1843		*rts = swap;
1844	}
1845}
1846
1847
1848void
1849rtdelete(struct rt_entry *rt)
1850{
1851	struct khash *k;
1852
1853
1854	if (TRACEACTIONS)
1855		trace_add_del("Del", rt);
1856
1857	k = kern_find(rt->rt_dst, rt->rt_mask, 0);
1858	if (k != 0) {
1859		k->k_state |= KS_DELETE;
1860		need_kern.tv_sec = now.tv_sec;
1861	}
1862
1863	dst_sock.sin_addr.s_addr = rt->rt_dst;
1864	mask_sock.sin_addr.s_addr = htonl(rt->rt_mask);
1865	masktrim(&mask_sock);
1866	if (rt != (struct rt_entry *)rhead->rnh_deladdr(&dst_sock, &mask_sock,
1867							rhead)) {
1868		msglog("rnh_deladdr() failed");
1869	} else {
1870		free(rt);
1871		total_routes--;
1872	}
1873}
1874
1875
1876void
1877rts_delete(struct rt_entry *rt,
1878	   struct rt_spare *rts)
1879{
1880	trace_upslot(rt, rts, &rts_empty);
1881	*rts = rts_empty;
1882}
1883
1884
1885/* Get rid of a bad route, and try to switch to a replacement.
1886 */
1887void
1888rtbad(struct rt_entry *rt)
1889{
1890	struct rt_spare new;
1891
1892	/* Poison the route */
1893	new = rt->rt_spares[0];
1894	new.rts_metric = HOPCNT_INFINITY;
1895	rtchange(rt, rt->rt_state & ~(RS_IF | RS_LOCAL | RS_STATIC), &new, 0);
1896	rtswitch(rt, 0);
1897}
1898
1899
1900/* Junk a RS_NET_SYN or RS_LOCAL route,
1901 *	unless it is needed by another interface.
1902 */
1903void
1904rtbad_sub(struct rt_entry *rt)
1905{
1906	struct interface *ifp, *ifp1;
1907	struct intnet *intnetp;
1908	u_int state;
1909
1910
1911	ifp1 = 0;
1912	state = 0;
1913
1914	if (rt->rt_state & RS_LOCAL) {
1915		/* Is this the route through loopback for the interface?
1916		 * If so, see if it is used by any other interfaces, such
1917		 * as a point-to-point interface with the same local address.
1918		 */
1919		for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
1920			/* Retain it if another interface needs it.
1921			 */
1922			if (ifp->int_addr == rt->rt_ifp->int_addr) {
1923				state |= RS_LOCAL;
1924				ifp1 = ifp;
1925				break;
1926			}
1927		}
1928
1929	}
1930
1931	if (!(state & RS_LOCAL)) {
1932		/* Retain RIPv1 logical network route if there is another
1933		 * interface that justifies it.
1934		 */
1935		if (rt->rt_state & RS_NET_SYN) {
1936			for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
1937				if ((ifp->int_state & IS_NEED_NET_SYN)
1938				    && rt->rt_mask == ifp->int_std_mask
1939				    && rt->rt_dst == ifp->int_std_addr) {
1940					state |= RS_NET_SYN;
1941					ifp1 = ifp;
1942					break;
1943				}
1944			}
1945		}
1946
1947		/* or if there is an authority route that needs it. */
1948		for (intnetp = intnets;
1949		     intnetp != 0;
1950		     intnetp = intnetp->intnet_next) {
1951			if (intnetp->intnet_addr == rt->rt_dst
1952			    && intnetp->intnet_mask == rt->rt_mask) {
1953				state |= (RS_NET_SYN | RS_NET_INT);
1954				break;
1955			}
1956		}
1957	}
1958
1959	if (ifp1 != 0 || (state & RS_NET_SYN)) {
1960		struct rt_spare new = rt->rt_spares[0];
1961		new.rts_ifp = ifp1;
1962		rtchange(rt, ((rt->rt_state & ~(RS_NET_SYN|RS_LOCAL)) | state),
1963			 &new, 0);
1964	} else {
1965		rtbad(rt);
1966	}
1967}
1968
1969
1970/* Called while walking the table looking for sick interfaces
1971 * or after a time change.
1972 */
1973/* ARGSUSED */
1974int
1975walk_bad(struct radix_node *rn,
1976	 struct walkarg *argp UNUSED)
1977{
1978#define RT ((struct rt_entry *)rn)
1979	struct rt_spare *rts;
1980	int i;
1981
1982
1983	/* fix any spare routes through the interface
1984	 */
1985	rts = RT->rt_spares;
1986	for (i = NUM_SPARES; i != 1; i--) {
1987		rts++;
1988		if (rts->rts_metric < HOPCNT_INFINITY
1989		    && (rts->rts_ifp == 0
1990			|| (rts->rts_ifp->int_state & IS_BROKE)))
1991			rts_delete(RT, rts);
1992	}
1993
1994	/* Deal with the main route
1995	 */
1996	/* finished if it has been handled before or if its interface is ok
1997	 */
1998	if (RT->rt_ifp == 0 || !(RT->rt_ifp->int_state & IS_BROKE))
1999		return 0;
2000
2001	/* Bad routes for other than interfaces are easy.
2002	 */
2003	if (0 == (RT->rt_state & (RS_IF | RS_NET_SYN | RS_LOCAL))) {
2004		rtbad(RT);
2005		return 0;
2006	}
2007
2008	rtbad_sub(RT);
2009	return 0;
2010#undef RT
2011}
2012
2013
2014/* Check the age of an individual route.
2015 */
2016/* ARGSUSED */
2017static int
2018walk_age(struct radix_node *rn,
2019	   struct walkarg *argp UNUSED)
2020{
2021#define RT ((struct rt_entry *)rn)
2022	struct interface *ifp;
2023	struct rt_spare *rts;
2024	int i;
2025
2026
2027	/* age all of the spare routes, including the primary route
2028	 * currently in use
2029	 */
2030	rts = RT->rt_spares;
2031	for (i = NUM_SPARES; i != 0; i--, rts++) {
2032
2033		ifp = rts->rts_ifp;
2034		if (i == NUM_SPARES) {
2035			if (!AGE_RT(RT->rt_state, ifp)) {
2036				/* Keep various things from deciding ageless
2037				 * routes are stale
2038				 */
2039				rts->rts_time = now.tv_sec;
2040				continue;
2041			}
2042
2043			/* forget RIP routes after RIP has been turned off.
2044			 */
2045			if (rip_sock < 0) {
2046				rtdelete(RT);
2047				return 0;
2048			}
2049		}
2050
2051		/* age failing routes
2052		 */
2053		if (age_bad_gate == rts->rts_gate
2054		    && rts->rts_time >= now_stale) {
2055			rts->rts_time -= SUPPLY_INTERVAL;
2056		}
2057
2058		/* trash the spare routes when they go bad */
2059		if (rts->rts_metric < HOPCNT_INFINITY
2060		    && now_garbage > rts->rts_time
2061		    && i != NUM_SPARES)
2062			rts_delete(RT, rts);
2063	}
2064
2065
2066	/* finished if the active route is still fresh */
2067	if (now_stale <= RT->rt_time)
2068		return 0;
2069
2070	/* try to switch to an alternative */
2071	rtswitch(RT, 0);
2072
2073	/* Delete a dead route after it has been publically mourned. */
2074	if (now_garbage > RT->rt_time) {
2075		rtdelete(RT);
2076		return 0;
2077	}
2078
2079	/* Start poisoning a bad route before deleting it. */
2080	if (now.tv_sec - RT->rt_time > EXPIRE_TIME) {
2081		struct rt_spare new = RT->rt_spares[0];
2082		new.rts_metric = HOPCNT_INFINITY;
2083		rtchange(RT, RT->rt_state, &new, 0);
2084	}
2085	return 0;
2086}
2087
2088
2089/* Watch for dead routes and interfaces.
2090 */
2091void
2092age(naddr bad_gate)
2093{
2094	struct interface *ifp;
2095	int need_query = 0;
2096
2097	/* If not listening to RIP, there is no need to age the routes in
2098	 * the table.
2099	 */
2100	age_timer.tv_sec = (now.tv_sec
2101			    + ((rip_sock < 0) ? NEVER : SUPPLY_INTERVAL));
2102
2103	/* Check for dead IS_REMOTE interfaces by timing their
2104	 * transmissions.
2105	 */
2106	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
2107		if (!(ifp->int_state & IS_REMOTE))
2108			continue;
2109
2110		/* ignore unreachable remote interfaces */
2111		if (!check_remote(ifp))
2112			continue;
2113
2114		/* Restore remote interface that has become reachable
2115		 */
2116		if (ifp->int_state & IS_BROKE)
2117			if_ok(ifp, "remote ");
2118
2119		if (ifp->int_act_time != NEVER
2120		    && now.tv_sec - ifp->int_act_time > EXPIRE_TIME) {
2121			msglog("remote interface %s to %s timed out after"
2122			       " %ld:%ld",
2123			       ifp->int_name,
2124			       naddr_ntoa(ifp->int_dstaddr),
2125			       (now.tv_sec - ifp->int_act_time)/60,
2126			       (now.tv_sec - ifp->int_act_time)%60);
2127			if_sick(ifp);
2128		}
2129
2130		/* If we have not heard from the other router
2131		 * recently, ask it.
2132		 */
2133		if (now.tv_sec >= ifp->int_query_time) {
2134			ifp->int_query_time = NEVER;
2135			need_query = 1;
2136		}
2137	}
2138
2139	/* Age routes. */
2140	age_bad_gate = bad_gate;
2141	(void)rn_walktree(rhead, walk_age, 0);
2142
2143	/* delete old redirected routes to keep the kernel table small
2144	 * and prevent blackholes
2145	 */
2146	del_redirects(bad_gate, now.tv_sec-STALE_TIME);
2147
2148	/* Update the kernel routing table. */
2149	fix_kern();
2150
2151	/* poke reticent remote gateways */
2152	if (need_query)
2153		rip_query();
2154}
2155