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