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