Home | History | Annotate | Line # | Download | only in routed
table.c revision 1.1.1.5
      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 acknowledgment:
     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(sgi) && !defined(__NetBSD__)
     35 static char sccsid[] __attribute__((unused)) = "@(#)tables.c	8.1 (Berkeley) 6/5/93";
     36 #elif defined(__NetBSD__)
     37 __RCSID("$NetBSD: table.c,v 1.1.1.5 1999/02/23 09:56:52 christos Exp $");
     38 #endif
     39 
     40 #include "defs.h"
     41 
     42 static struct rt_spare *rts_better(struct rt_entry *);
     43 static struct rt_spare rts_empty = {0,0,0,HOPCNT_INFINITY,0,0,0};
     44 
     45 struct radix_node_head *rhead;		/* root of the radix tree */
     46 
     47 int	need_flash = 1;			/* flash update needed
     48 					 * start =1 to suppress the 1st
     49 					 */
     50 
     51 struct timeval age_timer;		/* next check of old routes */
     52 struct timeval need_kern = {		/* need to update kernel table */
     53 	EPOCH+MIN_WAITTIME-1
     54 };
     55 
     56 int	stopint;
     57 
     58 int	total_routes;
     59 
     60 /* zap any old routes through this gateway */
     61 naddr	age_bad_gate;
     62 
     63 
     64 /* It is desirable to "aggregate" routes, to combine differing routes of
     65  * the same metric and next hop into a common route with a smaller netmask
     66  * or to suppress redundant routes, routes that add no information to
     67  * routes with smaller netmasks.
     68  *
     69  * A route is redundant if and only if any and all routes with smaller
     70  * but matching netmasks and nets are the same.  Since routes are
     71  * kept sorted in the radix tree, redundant routes always come second.
     72  *
     73  * There are two kinds of aggregations.  First, two routes of the same bit
     74  * mask and differing only in the least significant bit of the network
     75  * number can be combined into a single route with a coarser mask.
     76  *
     77  * Second, a route can be suppressed in favor of another route with a more
     78  * coarse mask provided no incompatible routes with intermediate masks
     79  * are present.  The second kind of aggregation involves suppressing routes.
     80  * A route must not be suppressed if an incompatible route exists with
     81  * an intermediate mask, since the suppressed route would be covered
     82  * by the intermediate.
     83  *
     84  * This code relies on the radix tree walk encountering routes
     85  * sorted first by address, with the smallest address first.
     86  */
     87 
     88 struct ag_info ag_slots[NUM_AG_SLOTS], *ag_avail, *ag_corsest, *ag_finest;
     89 
     90 /* #define DEBUG_AG */
     91 #ifdef DEBUG_AG
     92 #define CHECK_AG() {int acnt = 0; struct ag_info *cag;		\
     93 	for (cag = ag_avail; cag != 0; cag = cag->ag_fine)	\
     94 		acnt++;						\
     95 	for (cag = ag_corsest; cag != 0; cag = cag->ag_fine)	\
     96 		acnt++;						\
     97 	if (acnt != NUM_AG_SLOTS) {				\
     98 		(void)fflush(stderr);				\
     99 		abort();					\
    100 	}							\
    101 }
    102 #else
    103 #define CHECK_AG()
    104 #endif
    105 
    106 
    107 /* Output the contents of an aggregation table slot.
    108  *	This function must always be immediately followed with the deletion
    109  *	of the target slot.
    110  */
    111 static void
    112 ag_out(struct ag_info *ag,
    113 	 void (*out)(struct ag_info *))
    114 {
    115 	struct ag_info *ag_cors;
    116 	naddr bit;
    117 
    118 
    119 	/* Forget it if this route should not be output for split-horizon. */
    120 	if (ag->ag_state & AGS_SPLIT_HZ)
    121 		return;
    122 
    123 	/* If we output both the even and odd twins, then the immediate parent,
    124 	 * if it is present, is redundant, unless the parent manages to
    125 	 * aggregate into something coarser.
    126 	 * On successive calls, this code detects the even and odd twins,
    127 	 * and marks the parent.
    128 	 *
    129 	 * Note that the order in which the radix tree code emits routes
    130 	 * ensures that the twins are seen before the parent is emitted.
    131 	 */
    132 	ag_cors = ag->ag_cors;
    133 	if (ag_cors != 0
    134 	    && ag_cors->ag_mask == ag->ag_mask<<1
    135 	    && ag_cors->ag_dst_h == (ag->ag_dst_h & ag_cors->ag_mask)) {
    136 		ag_cors->ag_state |= ((ag_cors->ag_dst_h == ag->ag_dst_h)
    137 				      ? AGS_REDUN0
    138 				      : AGS_REDUN1);
    139 	}
    140 
    141 	/* Skip it if this route is itself redundant.
    142 	 *
    143 	 * It is ok to change the contents of the slot here, since it is
    144 	 * always deleted next.
    145 	 */
    146 	if (ag->ag_state & AGS_REDUN0) {
    147 		if (ag->ag_state & AGS_REDUN1)
    148 			return;		/* quit if fully redundant */
    149 		/* make it finer if it is half-redundant */
    150 		bit = (-ag->ag_mask) >> 1;
    151 		ag->ag_dst_h |= bit;
    152 		ag->ag_mask |= bit;
    153 
    154 	} else if (ag->ag_state & AGS_REDUN1) {
    155 		/* make it finer if it is half-redundant */
    156 		bit = (-ag->ag_mask) >> 1;
    157 		ag->ag_mask |= bit;
    158 	}
    159 	out(ag);
    160 }
    161 
    162 
    163 static void
    164 ag_del(struct ag_info *ag)
    165 {
    166 	CHECK_AG();
    167 
    168 	if (ag->ag_cors == 0)
    169 		ag_corsest = ag->ag_fine;
    170 	else
    171 		ag->ag_cors->ag_fine = ag->ag_fine;
    172 
    173 	if (ag->ag_fine == 0)
    174 		ag_finest = ag->ag_cors;
    175 	else
    176 		ag->ag_fine->ag_cors = ag->ag_cors;
    177 
    178 	ag->ag_fine = ag_avail;
    179 	ag_avail = ag;
    180 
    181 	CHECK_AG();
    182 }
    183 
    184 
    185 /* Flush routes waiting for aggregation.
    186  *	This must not suppress a route unless it is known that among all
    187  *	routes with coarser masks that match it, the one with the longest
    188  *	mask is appropriate.  This is ensured by scanning the routes
    189  *	in lexical order, and with the most restrictive mask first
    190  *	among routes to the same destination.
    191  */
    192 void
    193 ag_flush(naddr lim_dst_h,		/* flush routes to here */
    194 	 naddr lim_mask,		/* matching this mask */
    195 	 void (*out)(struct ag_info *))
    196 {
    197 	struct ag_info *ag, *ag_cors;
    198 	naddr dst_h;
    199 
    200 
    201 	for (ag = ag_finest;
    202 	     ag != 0 && ag->ag_mask >= lim_mask;
    203 	     ag = ag_cors) {
    204 		ag_cors = ag->ag_cors;
    205 
    206 		/* work on only the specified routes */
    207 		dst_h = ag->ag_dst_h;
    208 		if ((dst_h & lim_mask) != lim_dst_h)
    209 			continue;
    210 
    211 		if (!(ag->ag_state & AGS_SUPPRESS))
    212 			ag_out(ag, out);
    213 
    214 		else for ( ; ; ag_cors = ag_cors->ag_cors) {
    215 			/* Look for a route that can suppress the
    216 			 * current route */
    217 			if (ag_cors == 0) {
    218 				/* failed, so output it and look for
    219 				 * another route to work on
    220 				 */
    221 				ag_out(ag, out);
    222 				break;
    223 			}
    224 
    225 			if ((dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h) {
    226 				/* We found a route with a coarser mask that
    227 				 * aggregates the current target.
    228 				 *
    229 				 * If it has a different next hop, it
    230 				 * cannot replace the target, so output
    231 				 * the target.
    232 				 */
    233 				if (ag->ag_gate != ag_cors->ag_gate
    234 				    && !(ag->ag_state & AGS_FINE_GATE)
    235 				    && !(ag_cors->ag_state & AGS_CORS_GATE)) {
    236 					ag_out(ag, out);
    237 					break;
    238 				}
    239 
    240 				/* If the coarse route has a good enough
    241 				 * metric, it suppresses the target.
    242 				 * If the suppressed target was redundant,
    243 				 * then mark the suppressor redundant.
    244 				 */
    245 				if (ag_cors->ag_pref <= ag->ag_pref) {
    246 				    if (ag_cors->ag_seqno > ag->ag_seqno)
    247 					ag_cors->ag_seqno = ag->ag_seqno;
    248 				    if (AG_IS_REDUN(ag->ag_state)
    249 					&& ag_cors->ag_mask==ag->ag_mask<<1) {
    250 					if (ag_cors->ag_dst_h == dst_h)
    251 					    ag_cors->ag_state |= AGS_REDUN0;
    252 					else
    253 					    ag_cors->ag_state |= AGS_REDUN1;
    254 				    }
    255 				    if (ag->ag_tag != ag_cors->ag_tag)
    256 					    ag_cors->ag_tag = 0;
    257 				    if (ag->ag_nhop != ag_cors->ag_nhop)
    258 					    ag_cors->ag_nhop = 0;
    259 				    break;
    260 				}
    261 			}
    262 		}
    263 
    264 		/* That route has either been output or suppressed */
    265 		ag_cors = ag->ag_cors;
    266 		ag_del(ag);
    267 	}
    268 
    269 	CHECK_AG();
    270 }
    271 
    272 
    273 /* Try to aggregate a route with previous routes.
    274  */
    275 void
    276 ag_check(naddr	dst,
    277 	 naddr	mask,
    278 	 naddr	gate,
    279 	 naddr	nhop,
    280 	 char	metric,
    281 	 char	pref,
    282 	 u_int	seqno,
    283 	 u_short tag,
    284 	 u_short state,
    285 	 void (*out)(struct ag_info *))	/* output using this */
    286 {
    287 	struct ag_info *ag, *nag, *ag_cors;
    288 	naddr xaddr;
    289 	int x;
    290 
    291 	NTOHL(dst);
    292 
    293 	/* Punt non-contiguous subnet masks.
    294 	 *
    295 	 * (X & -X) contains a single bit if and only if X is a power of 2.
    296 	 * (X + (X & -X)) == 0 if and only if X is a power of 2.
    297 	 */
    298 	if ((mask & -mask) + mask != 0) {
    299 		struct ag_info nc_ag;
    300 
    301 		nc_ag.ag_dst_h = dst;
    302 		nc_ag.ag_mask = mask;
    303 		nc_ag.ag_gate = gate;
    304 		nc_ag.ag_nhop = nhop;
    305 		nc_ag.ag_metric = metric;
    306 		nc_ag.ag_pref = pref;
    307 		nc_ag.ag_tag = tag;
    308 		nc_ag.ag_state = state;
    309 		nc_ag.ag_seqno = seqno;
    310 		out(&nc_ag);
    311 		return;
    312 	}
    313 
    314 	/* Search for the right slot in the aggregation table.
    315 	 */
    316 	ag_cors = 0;
    317 	ag = ag_corsest;
    318 	while (ag != 0) {
    319 		if (ag->ag_mask >= mask)
    320 			break;
    321 
    322 		/* Suppress old routes (i.e. combine with compatible routes
    323 		 * with coarser masks) as we look for the right slot in the
    324 		 * aggregation table for the new route.
    325 		 * A route to an address less than the current destination
    326 		 * will not be affected by the current route or any route
    327 		 * seen hereafter.  That means it is safe to suppress it.
    328 		 * This check keeps poor routes (e.g. with large hop counts)
    329 		 * from preventing suppression of finer routes.
    330 		 */
    331 		if (ag_cors != 0
    332 		    && ag->ag_dst_h < dst
    333 		    && (ag->ag_state & AGS_SUPPRESS)
    334 		    && ag_cors->ag_pref <= ag->ag_pref
    335 		    && (ag->ag_dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h
    336 		    && (ag_cors->ag_gate == ag->ag_gate
    337 			|| (ag->ag_state & AGS_FINE_GATE)
    338 			|| (ag_cors->ag_state & AGS_CORS_GATE))) {
    339 			if (ag_cors->ag_seqno > ag->ag_seqno)
    340 				ag_cors->ag_seqno = ag->ag_seqno;
    341 			/*  If the suppressed target was redundant,
    342 			 * then mark the suppressor redundant.
    343 			 */
    344 			if (AG_IS_REDUN(ag->ag_state)
    345 			    && ag_cors->ag_mask==ag->ag_mask<<1) {
    346 				if (ag_cors->ag_dst_h == dst)
    347 					ag_cors->ag_state |= AGS_REDUN0;
    348 				else
    349 					ag_cors->ag_state |= AGS_REDUN1;
    350 			}
    351 			if (ag->ag_tag != ag_cors->ag_tag)
    352 				ag_cors->ag_tag = 0;
    353 			if (ag->ag_nhop != ag_cors->ag_nhop)
    354 				ag_cors->ag_nhop = 0;
    355 			ag_del(ag);
    356 			CHECK_AG();
    357 		} else {
    358 			ag_cors = ag;
    359 		}
    360 		ag = ag_cors->ag_fine;
    361 	}
    362 
    363 	/* If we find the even/odd twin of the new route, and if the
    364 	 * masks and so forth are equal, we can aggregate them.
    365 	 * We can probably promote one of the pair.
    366 	 *
    367 	 * Since the routes are encountered in lexical order,
    368 	 * the new route must be odd.  However, the second or later
    369 	 * times around this loop, it could be the even twin promoted
    370 	 * from the even/odd pair of twins of the finer route.
    371 	 */
    372 	while (ag != 0
    373 	       && ag->ag_mask == mask
    374 	       && ((ag->ag_dst_h ^ dst) & (mask<<1)) == 0) {
    375 
    376 		/* Here we know the target route and the route in the current
    377 		 * slot have the same netmasks and differ by at most the
    378 		 * last bit.  They are either for the same destination, or
    379 		 * for an even/odd pair of destinations.
    380 		 */
    381 		if (ag->ag_dst_h == dst) {
    382 			/* We have two routes to the same destination.
    383 			 * Routes are encountered in lexical order, so a
    384 			 * route is never promoted until the parent route is
    385 			 * already present.  So we know that the new route is
    386 			 * a promoted (or aggregated) pair and the route
    387 			 * already in the slot is the explicit route.
    388 			 *
    389 			 * Prefer the best route if their metrics differ,
    390 			 * or the aggregated one if not, following a sort
    391 			 * of longest-match rule.
    392 			 */
    393 			if (pref <= ag->ag_pref) {
    394 				ag->ag_gate = gate;
    395 				ag->ag_nhop = nhop;
    396 				ag->ag_tag = tag;
    397 				ag->ag_metric = metric;
    398 				ag->ag_pref = pref;
    399 				x = ag->ag_state;
    400 				ag->ag_state = state;
    401 				state = x;
    402 			}
    403 
    404 			/* The sequence number controls flash updating,
    405 			 * and should be the smaller of the two.
    406 			 */
    407 			if (ag->ag_seqno > seqno)
    408 				ag->ag_seqno = seqno;
    409 
    410 			/* Some bits are set if they are set on either route,
    411 			 * except when the route is for an interface.
    412 			 */
    413 			if (!(ag->ag_state & AGS_IF))
    414 				ag->ag_state |= (state & (AGS_AGGREGATE_EITHER
    415 							| AGS_REDUN0
    416 							| AGS_REDUN1));
    417 			return;
    418 		}
    419 
    420 		/* If one of the routes can be promoted and the other can
    421 		 * be suppressed, it may be possible to combine them or
    422 		 * worthwhile to promote one.
    423 		 *
    424 		 * Any route that can be promoted is always
    425 		 * marked to be eligible to be suppressed.
    426 		 */
    427 		if (!((state & AGS_AGGREGATE)
    428 		      && (ag->ag_state & AGS_SUPPRESS))
    429 		    && !((ag->ag_state & AGS_AGGREGATE)
    430 			 && (state & AGS_SUPPRESS)))
    431 			break;
    432 
    433 		/* A pair of even/odd twin routes can be combined
    434 		 * if either is redundant, or if they are via the
    435 		 * same gateway and have the same metric.
    436 		 */
    437 		if (AG_IS_REDUN(ag->ag_state)
    438 		    || AG_IS_REDUN(state)
    439 		    || (ag->ag_gate == gate
    440 			&& ag->ag_pref == pref
    441 			&& (state & ag->ag_state & AGS_AGGREGATE) != 0)) {
    442 
    443 			/* We have both the even and odd pairs.
    444 			 * Since the routes are encountered in order,
    445 			 * the route in the slot must be the even twin.
    446 			 *
    447 			 * Combine and promote (aggregate) the pair of routes.
    448 			 */
    449 			if (seqno > ag->ag_seqno)
    450 				seqno = ag->ag_seqno;
    451 			if (!AG_IS_REDUN(state))
    452 				state &= ~AGS_REDUN1;
    453 			if (AG_IS_REDUN(ag->ag_state))
    454 				state |= AGS_REDUN0;
    455 			else
    456 				state &= ~AGS_REDUN0;
    457 			state |= (ag->ag_state & AGS_AGGREGATE_EITHER);
    458 			if (ag->ag_tag != tag)
    459 				tag = 0;
    460 			if (ag->ag_nhop != nhop)
    461 				nhop = 0;
    462 
    463 			/* Get rid of the even twin that was already
    464 			 * in the slot.
    465 			 */
    466 			ag_del(ag);
    467 
    468 		} else if (ag->ag_pref >= pref
    469 			   && (ag->ag_state & AGS_AGGREGATE)) {
    470 			/* If we cannot combine the pair, maybe the route
    471 			 * with the worse metric can be promoted.
    472 			 *
    473 			 * Promote the old, even twin, by giving its slot
    474 			 * in the table to the new, odd twin.
    475 			 */
    476 			ag->ag_dst_h = dst;
    477 
    478 			xaddr = ag->ag_gate;
    479 			ag->ag_gate = gate;
    480 			gate = xaddr;
    481 
    482 			xaddr = ag->ag_nhop;
    483 			ag->ag_nhop = nhop;
    484 			nhop = xaddr;
    485 
    486 			x = ag->ag_tag;
    487 			ag->ag_tag = tag;
    488 			tag = x;
    489 
    490 			/* The promoted route is even-redundant only if the
    491 			 * even twin was fully redundant.  It is not
    492 			 * odd-redundant because the odd-twin will still be
    493 			 * in the table.
    494 			 */
    495 			x = ag->ag_state;
    496 			if (!AG_IS_REDUN(x))
    497 				x &= ~AGS_REDUN0;
    498 			x &= ~AGS_REDUN1;
    499 			ag->ag_state = state;
    500 			state = x;
    501 
    502 			x = ag->ag_metric;
    503 			ag->ag_metric = metric;
    504 			metric = x;
    505 
    506 			x = ag->ag_pref;
    507 			ag->ag_pref = pref;
    508 			pref = x;
    509 
    510 			/* take the newest sequence number */
    511 			if (seqno >= ag->ag_seqno)
    512 				seqno = ag->ag_seqno;
    513 			else
    514 				ag->ag_seqno = seqno;
    515 
    516 		} else {
    517 			if (!(state & AGS_AGGREGATE))
    518 				break;	/* cannot promote either twin */
    519 
    520 			/* Promote the new, odd twin by shaving its
    521 			 * mask and address.
    522 			 * The promoted route is odd-redundant only if the
    523 			 * odd twin was fully redundant.  It is not
    524 			 * even-redundant because the even twin is still in
    525 			 * the table.
    526 			 */
    527 			if (!AG_IS_REDUN(state))
    528 				state &= ~AGS_REDUN1;
    529 			state &= ~AGS_REDUN0;
    530 			if (seqno > ag->ag_seqno)
    531 				seqno = ag->ag_seqno;
    532 			else
    533 				ag->ag_seqno = seqno;
    534 		}
    535 
    536 		mask <<= 1;
    537 		dst &= mask;
    538 
    539 		if (ag_cors == 0) {
    540 			ag = ag_corsest;
    541 			break;
    542 		}
    543 		ag = ag_cors;
    544 		ag_cors = ag->ag_cors;
    545 	}
    546 
    547 	/* When we can no longer promote and combine routes,
    548 	 * flush the old route in the target slot.  Also flush
    549 	 * any finer routes that we know will never be aggregated by
    550 	 * the new route.
    551 	 *
    552 	 * In case we moved toward coarser masks,
    553 	 * get back where we belong
    554 	 */
    555 	if (ag != 0
    556 	    && ag->ag_mask < mask) {
    557 		ag_cors = ag;
    558 		ag = ag->ag_fine;
    559 	}
    560 
    561 	/* Empty the target slot
    562 	 */
    563 	if (ag != 0 && ag->ag_mask == mask) {
    564 		ag_flush(ag->ag_dst_h, ag->ag_mask, out);
    565 		ag = (ag_cors == 0) ? ag_corsest : ag_cors->ag_fine;
    566 	}
    567 
    568 #ifdef DEBUG_AG
    569 	(void)fflush(stderr);
    570 	if (ag == 0 && ag_cors != ag_finest)
    571 		abort();
    572 	if (ag_cors == 0 && ag != ag_corsest)
    573 		abort();
    574 	if (ag != 0 && ag->ag_cors != ag_cors)
    575 		abort();
    576 	if (ag_cors != 0 && ag_cors->ag_fine != ag)
    577 		abort();
    578 	CHECK_AG();
    579 #endif
    580 
    581 	/* Save the new route on the end of the table.
    582 	 */
    583 	nag = ag_avail;
    584 	ag_avail = nag->ag_fine;
    585 
    586 	nag->ag_dst_h = dst;
    587 	nag->ag_mask = mask;
    588 	nag->ag_gate = gate;
    589 	nag->ag_nhop = nhop;
    590 	nag->ag_metric = metric;
    591 	nag->ag_pref = pref;
    592 	nag->ag_tag = tag;
    593 	nag->ag_state = state;
    594 	nag->ag_seqno = seqno;
    595 
    596 	nag->ag_fine = ag;
    597 	if (ag != 0)
    598 		ag->ag_cors = nag;
    599 	else
    600 		ag_finest = nag;
    601 	nag->ag_cors = ag_cors;
    602 	if (ag_cors == 0)
    603 		ag_corsest = nag;
    604 	else
    605 		ag_cors->ag_fine = nag;
    606 	CHECK_AG();
    607 }
    608 
    609 
    610 static const char *
    611 rtm_type_name(u_char type)
    612 {
    613 	static const char *rtm_types[] = {
    614 		"RTM_ADD",
    615 		"RTM_DELETE",
    616 		"RTM_CHANGE",
    617 		"RTM_GET",
    618 		"RTM_LOSING",
    619 		"RTM_REDIRECT",
    620 		"RTM_MISS",
    621 		"RTM_LOCK",
    622 		"RTM_OLDADD",
    623 		"RTM_OLDDEL",
    624 		"RTM_RESOLVE",
    625 		"RTM_NEWADDR",
    626 		"RTM_DELADDR",
    627 		"RTM_IFINFO"
    628 	};
    629 	static char name0[10];
    630 
    631 
    632 	if (type > sizeof(rtm_types)/sizeof(rtm_types[0])
    633 	    || type == 0) {
    634 		sprintf(name0, "RTM type %#x", type);
    635 		return name0;
    636 	} else {
    637 		return rtm_types[type-1];
    638 	}
    639 }
    640 
    641 
    642 /* Trim a mask in a sockaddr
    643  *	Produce a length of 0 for an address of 0.
    644  *	Otherwise produce the index of the first zero byte.
    645  */
    646 void
    647 #ifdef _HAVE_SIN_LEN
    648 masktrim(struct sockaddr_in *ap)
    649 #else
    650 masktrim(struct sockaddr_in_new *ap)
    651 #endif
    652 {
    653 	char *cp;
    654 
    655 	if (ap->sin_addr.s_addr == 0) {
    656 		ap->sin_len = 0;
    657 		return;
    658 	}
    659 	cp = (char *)(&ap->sin_addr.s_addr+1);
    660 	while (*--cp == 0)
    661 		continue;
    662 	ap->sin_len = cp - (char*)ap + 1;
    663 }
    664 
    665 
    666 /* Tell the kernel to add, delete or change a route
    667  */
    668 static void
    669 rtioctl(int action,			/* RTM_DELETE, etc */
    670 	naddr dst,
    671 	naddr gate,
    672 	naddr mask,
    673 	int metric,
    674 	int flags)
    675 {
    676 	struct {
    677 		struct rt_msghdr w_rtm;
    678 		struct sockaddr_in w_dst;
    679 		struct sockaddr_in w_gate;
    680 #ifdef _HAVE_SA_LEN
    681 		struct sockaddr_in w_mask;
    682 #else
    683 		struct sockaddr_in_new w_mask;
    684 #endif
    685 	} w;
    686 	long cc;
    687 #   define PAT " %-10s %s metric=%d flags=%#x"
    688 #   define ARGS rtm_type_name(action), rtname(dst,mask,gate), metric, flags
    689 
    690 again:
    691 	memset(&w, 0, sizeof(w));
    692 	w.w_rtm.rtm_msglen = sizeof(w);
    693 	w.w_rtm.rtm_version = RTM_VERSION;
    694 	w.w_rtm.rtm_type = action;
    695 	w.w_rtm.rtm_flags = flags;
    696 	w.w_rtm.rtm_seq = ++rt_sock_seqno;
    697 	w.w_rtm.rtm_addrs = RTA_DST|RTA_GATEWAY;
    698 	if (metric != 0 || action == RTM_CHANGE) {
    699 		w.w_rtm.rtm_rmx.rmx_hopcount = metric;
    700 		w.w_rtm.rtm_inits |= RTV_HOPCOUNT;
    701 	}
    702 	w.w_dst.sin_family = AF_INET;
    703 	w.w_dst.sin_addr.s_addr = dst;
    704 	w.w_gate.sin_family = AF_INET;
    705 	w.w_gate.sin_addr.s_addr = gate;
    706 #ifdef _HAVE_SA_LEN
    707 	w.w_dst.sin_len = sizeof(w.w_dst);
    708 	w.w_gate.sin_len = sizeof(w.w_gate);
    709 #endif
    710 	if (mask == HOST_MASK) {
    711 		w.w_rtm.rtm_flags |= RTF_HOST;
    712 		w.w_rtm.rtm_msglen -= sizeof(w.w_mask);
    713 	} else {
    714 		w.w_rtm.rtm_addrs |= RTA_NETMASK;
    715 		w.w_mask.sin_addr.s_addr = htonl(mask);
    716 #ifdef _HAVE_SA_LEN
    717 		masktrim(&w.w_mask);
    718 		if (w.w_mask.sin_len == 0)
    719 			w.w_mask.sin_len = sizeof(long);
    720 		w.w_rtm.rtm_msglen -= (sizeof(w.w_mask) - w.w_mask.sin_len);
    721 #endif
    722 	}
    723 
    724 #ifndef NO_INSTALL
    725 	cc = write(rt_sock, &w, w.w_rtm.rtm_msglen);
    726 	if (cc < 0) {
    727 		if (errno == ESRCH
    728 		    && (action == RTM_CHANGE || action == RTM_DELETE)) {
    729 			trace_act("route disappeared before" PAT, ARGS);
    730 			if (action == RTM_CHANGE) {
    731 				action = RTM_ADD;
    732 				goto again;
    733 			}
    734 			return;
    735 		}
    736 		msglog("write(rt_sock)" PAT ": %s", ARGS, strerror(errno));
    737 		return;
    738 	} else if (cc != w.w_rtm.rtm_msglen) {
    739 		msglog("write(rt_sock) wrote %ld instead of %d for" PAT,
    740 		       cc, w.w_rtm.rtm_msglen, ARGS);
    741 		return;
    742 	}
    743 #endif
    744 	if (TRACEKERNEL)
    745 		trace_misc("write kernel" PAT, ARGS);
    746 #undef PAT
    747 #undef ARGS
    748 }
    749 
    750 
    751 #define KHASH_SIZE 71			/* should be prime */
    752 #define KHASH(a,m) khash_bins[((a) ^ (m)) % KHASH_SIZE]
    753 static struct khash {
    754 	struct khash *k_next;
    755 	naddr	k_dst;
    756 	naddr	k_mask;
    757 	naddr	k_gate;
    758 	short	k_metric;
    759 	u_short	k_state;
    760 #define	    KS_NEW	0x001
    761 #define	    KS_DELETE	0x002		/* need to delete the route */
    762 #define	    KS_ADD	0x004		/* add to the kernel */
    763 #define	    KS_CHANGE	0x008		/* tell kernel to change the route */
    764 #define	    KS_DEL_ADD	0x010		/* delete & add to change the kernel */
    765 #define	    KS_STATIC	0x020		/* Static flag in kernel */
    766 #define	    KS_GATEWAY	0x040		/* G flag in kernel */
    767 #define	    KS_DYNAMIC	0x080		/* result of redirect */
    768 #define	    KS_DELETED	0x100		/* already deleted from kernel */
    769 #define	    KS_CHECK	0x200
    770 	time_t	k_keep;
    771 #define	    K_KEEP_LIM	30
    772 	time_t	k_redirect_time;	/* when redirected route 1st seen */
    773 } *khash_bins[KHASH_SIZE];
    774 
    775 
    776 static struct khash*
    777 kern_find(naddr dst, naddr mask, struct khash ***ppk)
    778 {
    779 	struct khash *k, **pk;
    780 
    781 	for (pk = &KHASH(dst,mask); (k = *pk) != 0; pk = &k->k_next) {
    782 		if (k->k_dst == dst && k->k_mask == mask)
    783 			break;
    784 	}
    785 	if (ppk != 0)
    786 		*ppk = pk;
    787 	return k;
    788 }
    789 
    790 
    791 static struct khash*
    792 kern_add(naddr dst, naddr mask)
    793 {
    794 	struct khash *k, **pk;
    795 
    796 	k = kern_find(dst, mask, &pk);
    797 	if (k != 0)
    798 		return k;
    799 
    800 	k = (struct khash *)rtmalloc(sizeof(*k), "kern_add");
    801 
    802 	memset(k, 0, sizeof(*k));
    803 	k->k_dst = dst;
    804 	k->k_mask = mask;
    805 	k->k_state = KS_NEW;
    806 	k->k_keep = now.tv_sec;
    807 	*pk = k;
    808 
    809 	return k;
    810 }
    811 
    812 
    813 /* If a kernel route has a non-zero metric, check that it is still in the
    814  *	daemon table, and not deleted by interfaces coming and going.
    815  */
    816 static void
    817 kern_check_static(struct khash *k,
    818 		  struct interface *ifp)
    819 {
    820 	struct rt_entry *rt;
    821 	struct rt_spare new;
    822 
    823 	if (k->k_metric == 0)
    824 		return;
    825 
    826 	memset(&new, 0, sizeof(new));
    827 	new.rts_ifp = ifp;
    828 	new.rts_gate = k->k_gate;
    829 	new.rts_router = (ifp != 0) ? ifp->int_addr : loopaddr;
    830 	new.rts_metric = k->k_metric;
    831 	new.rts_time = now.tv_sec;
    832 
    833 	rt = rtget(k->k_dst, k->k_mask);
    834 	if (rt != 0) {
    835 		if (!(rt->rt_state & RS_STATIC))
    836 			rtchange(rt, rt->rt_state | RS_STATIC, &new, 0);
    837 	} else {
    838 		rtadd(k->k_dst, k->k_mask, RS_STATIC, &new);
    839 	}
    840 }
    841 
    842 
    843 /* operate on a kernel entry
    844  */
    845 static void
    846 kern_ioctl(struct khash *k,
    847 	   int action,			/* RTM_DELETE, etc */
    848 	   int flags)
    849 
    850 {
    851 	switch (action) {
    852 	case RTM_DELETE:
    853 		k->k_state &= ~KS_DYNAMIC;
    854 		if (k->k_state & KS_DELETED)
    855 			return;
    856 		k->k_state |= KS_DELETED;
    857 		break;
    858 	case RTM_ADD:
    859 		k->k_state &= ~KS_DELETED;
    860 		break;
    861 	case RTM_CHANGE:
    862 		if (k->k_state & KS_DELETED) {
    863 			action = RTM_ADD;
    864 			k->k_state &= ~KS_DELETED;
    865 		}
    866 		break;
    867 	}
    868 
    869 	rtioctl(action, k->k_dst, k->k_gate, k->k_mask, k->k_metric, flags);
    870 }
    871 
    872 
    873 /* add a route the kernel told us
    874  */
    875 static void
    876 rtm_add(struct rt_msghdr *rtm,
    877 	struct rt_addrinfo *info,
    878 	time_t keep)
    879 {
    880 	struct khash *k;
    881 	struct interface *ifp;
    882 	naddr mask;
    883 
    884 
    885 	if (rtm->rtm_flags & RTF_HOST) {
    886 		mask = HOST_MASK;
    887 	} else if (INFO_MASK(info) != 0) {
    888 		mask = ntohl(S_ADDR(INFO_MASK(info)));
    889 	} else {
    890 		msglog("ignore %s without mask", rtm_type_name(rtm->rtm_type));
    891 		return;
    892 	}
    893 
    894 	k = kern_add(S_ADDR(INFO_DST(info)), mask);
    895 	if (k->k_state & KS_NEW)
    896 		k->k_keep = now.tv_sec+keep;
    897 	if (INFO_GATE(info) == 0) {
    898 		trace_act("note %s without gateway",
    899 			  rtm_type_name(rtm->rtm_type));
    900 		k->k_metric = HOPCNT_INFINITY;
    901 	} else if (INFO_GATE(info)->sa_family != AF_INET) {
    902 		trace_act("note %s with gateway AF=%d",
    903 			  rtm_type_name(rtm->rtm_type),
    904 			  INFO_GATE(info)->sa_family);
    905 		k->k_metric = HOPCNT_INFINITY;
    906 	} else {
    907 		k->k_gate = S_ADDR(INFO_GATE(info));
    908 		k->k_metric = rtm->rtm_rmx.rmx_hopcount;
    909 		if (k->k_metric < 0)
    910 			k->k_metric = 0;
    911 		else if (k->k_metric > HOPCNT_INFINITY-1)
    912 			k->k_metric = HOPCNT_INFINITY-1;
    913 	}
    914 	k->k_state &= ~(KS_DELETE | KS_ADD | KS_CHANGE | KS_DEL_ADD
    915 			| KS_DELETED | KS_GATEWAY | KS_STATIC
    916 			| KS_NEW | KS_CHECK);
    917 	if (rtm->rtm_flags & RTF_GATEWAY)
    918 		k->k_state |= KS_GATEWAY;
    919 	if (rtm->rtm_flags & RTF_STATIC)
    920 		k->k_state |= KS_STATIC;
    921 
    922 	if (0 != (rtm->rtm_flags & (RTF_DYNAMIC | RTF_MODIFIED))) {
    923 		if (INFO_AUTHOR(info) != 0
    924 		    && INFO_AUTHOR(info)->sa_family == AF_INET)
    925 			ifp = iflookup(S_ADDR(INFO_AUTHOR(info)));
    926 		else
    927 			ifp = 0;
    928 		if (supplier
    929 		    && (ifp == 0 || !(ifp->int_state & IS_REDIRECT_OK))) {
    930 			/* Routers are not supposed to listen to redirects,
    931 			 * so delete it if it came via an unknown interface
    932 			 * or the interface does not have special permission.
    933 			 */
    934 			k->k_state &= ~KS_DYNAMIC;
    935 			k->k_state |= KS_DELETE;
    936 			LIM_SEC(need_kern, 0);
    937 			trace_act("mark for deletion redirected %s --> %s"
    938 				  " via %s",
    939 				  addrname(k->k_dst, k->k_mask, 0),
    940 				  naddr_ntoa(k->k_gate),
    941 				  ifp ? ifp->int_name : "unknown interface");
    942 		} else {
    943 			k->k_state |= KS_DYNAMIC;
    944 			k->k_redirect_time = now.tv_sec;
    945 			trace_act("accept redirected %s --> %s via %s",
    946 				  addrname(k->k_dst, k->k_mask, 0),
    947 				  naddr_ntoa(k->k_gate),
    948 				  ifp ? ifp->int_name : "unknown interface");
    949 		}
    950 		return;
    951 	}
    952 
    953 	/* If it is not a static route, quit until the next comparison
    954 	 * between the kernel and daemon tables, when it will be deleted.
    955 	 */
    956 	if (!(k->k_state & KS_STATIC)) {
    957 		k->k_state |= KS_DELETE;
    958 		LIM_SEC(need_kern, k->k_keep);
    959 		return;
    960 	}
    961 
    962 	/* Put static routes with real metrics into the daemon table so
    963 	 * they can be advertised.
    964 	 *
    965 	 * Find the interface toward the gateway.
    966 	 */
    967 	ifp = iflookup(k->k_gate);
    968 	if (ifp == 0)
    969 		msglog("static route %s --> %s impossibly lacks ifp",
    970 		       addrname(S_ADDR(INFO_DST(info)), mask, 0),
    971 		       naddr_ntoa(k->k_gate));
    972 
    973 	kern_check_static(k, ifp);
    974 }
    975 
    976 
    977 /* deal with packet loss
    978  */
    979 static void
    980 rtm_lose(struct rt_msghdr *rtm,
    981 	 struct rt_addrinfo *info)
    982 {
    983 	if (INFO_GATE(info) == 0
    984 	    || INFO_GATE(info)->sa_family != AF_INET) {
    985 		trace_act("ignore %s without gateway",
    986 			  rtm_type_name(rtm->rtm_type));
    987 		return;
    988 	}
    989 
    990 	if (rdisc_ok)
    991 		rdisc_age(S_ADDR(INFO_GATE(info)));
    992 	age(S_ADDR(INFO_GATE(info)));
    993 }
    994 
    995 
    996 /* Make the gateway slot of an info structure point to something
    997  * useful.  If it is not already useful, but it specifies an interface,
    998  * then fill in the sockaddr_in provided and point it there.
    999  */
   1000 static int
   1001 get_info_gate(struct sockaddr **sap,
   1002 	      struct sockaddr_in *sin)
   1003 {
   1004 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)*sap;
   1005 	struct interface *ifp;
   1006 
   1007 	if (sdl == 0)
   1008 		return 0;
   1009 	if ((sdl)->sdl_family == AF_INET)
   1010 		return 1;
   1011 	if ((sdl)->sdl_family != AF_LINK)
   1012 		return 0;
   1013 
   1014 	ifp = ifwithindex(sdl->sdl_index, 1);
   1015 	if (ifp == 0)
   1016 		return 0;
   1017 
   1018 	sin->sin_addr.s_addr = ifp->int_addr;
   1019 #ifdef _HAVE_SA_LEN
   1020 	sin->sin_len = sizeof(*sin);
   1021 #endif
   1022 	sin->sin_family = AF_INET;
   1023 	*sap = (struct sockaddr*)sin;
   1024 
   1025 	return 1;
   1026 }
   1027 
   1028 
   1029 /* Clean the kernel table by copying it to the daemon image.
   1030  * Eventually the daemon will delete any extra routes.
   1031  */
   1032 void
   1033 flush_kern(void)
   1034 {
   1035 	static char *sysctl_buf;
   1036 	static size_t sysctl_buf_size = 0;
   1037 	size_t needed;
   1038 	int mib[6];
   1039 	char *next, *lim;
   1040 	struct rt_msghdr *rtm;
   1041 	struct sockaddr_in gate_sin;
   1042 	struct rt_addrinfo info;
   1043 	int i;
   1044 	struct khash *k;
   1045 
   1046 
   1047 	for (i = 0; i < KHASH_SIZE; i++) {
   1048 		for (k = khash_bins[i]; k != 0; k = k->k_next) {
   1049 			k->k_state |= KS_CHECK;
   1050 		}
   1051 	}
   1052 
   1053 	mib[0] = CTL_NET;
   1054 	mib[1] = PF_ROUTE;
   1055 	mib[2] = 0;		/* protocol */
   1056 	mib[3] = 0;		/* wildcard address family */
   1057 	mib[4] = NET_RT_DUMP;
   1058 	mib[5] = 0;		/* no flags */
   1059 	for (;;) {
   1060 		if ((needed = sysctl_buf_size) != 0) {
   1061 			if (sysctl(mib, 6, sysctl_buf,&needed, 0, 0) >= 0)
   1062 				break;
   1063 			if (errno != ENOMEM && errno != EFAULT)
   1064 				BADERR(1,"flush_kern: sysctl(RT_DUMP)");
   1065 			free(sysctl_buf);
   1066 			needed = 0;
   1067 		}
   1068 		if (sysctl(mib, 6, 0, &needed, 0, 0) < 0)
   1069 			BADERR(1,"flush_kern: sysctl(RT_DUMP) estimate");
   1070 		/* Kludge around the habit of some systems, such as
   1071 		 * BSD/OS 3.1, to not admit how many routes are in the
   1072 		 * kernel, or at least to be quite wrong.
   1073 		 */
   1074 		needed += 50*(sizeof(*rtm)+5*sizeof(struct sockaddr));
   1075 		sysctl_buf = rtmalloc(sysctl_buf_size = needed,
   1076 				      "flush_kern sysctl(RT_DUMP)");
   1077 	}
   1078 
   1079 	lim = sysctl_buf + needed;
   1080 	for (next = sysctl_buf; next < lim; next += rtm->rtm_msglen) {
   1081 		rtm = (struct rt_msghdr *)next;
   1082 		if (rtm->rtm_msglen == 0) {
   1083 			msglog("zero length kernel route at "
   1084 			       " %#x in buffer %#x before %#x",
   1085 			       (int)rtm, (int)sysctl_buf, (int)lim);
   1086 			break;
   1087 		}
   1088 
   1089 		rt_xaddrs(&info,
   1090 			  (struct sockaddr *)(rtm+1),
   1091 			  (struct sockaddr *)(next + rtm->rtm_msglen),
   1092 			  rtm->rtm_addrs);
   1093 
   1094 		if (INFO_DST(&info) == 0
   1095 		    || INFO_DST(&info)->sa_family != AF_INET)
   1096 			continue;
   1097 
   1098 		/* ignore ARP table entries on systems with a merged route
   1099 		 * and ARP table.
   1100 		 */
   1101 		if (rtm->rtm_flags & RTF_LLINFO)
   1102 			continue;
   1103 
   1104 		/* ignore multicast addresses
   1105 		 */
   1106 		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info)))))
   1107 			continue;
   1108 
   1109 		if (!get_info_gate(&INFO_GATE(&info), &gate_sin))
   1110 			continue;
   1111 
   1112 		/* Note static routes and interface routes, and also
   1113 		 * preload the image of the kernel table so that
   1114 		 * we can later clean it, as well as avoid making
   1115 		 * unneeded changes.  Keep the old kernel routes for a
   1116 		 * few seconds to allow a RIP or router-discovery
   1117 		 * response to be heard.
   1118 		 */
   1119 		rtm_add(rtm,&info,MIN_WAITTIME);
   1120 	}
   1121 
   1122 	for (i = 0; i < KHASH_SIZE; i++) {
   1123 		for (k = khash_bins[i]; k != 0; k = k->k_next) {
   1124 			if (k->k_state & KS_CHECK) {
   1125 				msglog("%s --> %s disappeared from kernel",
   1126 				       addrname(k->k_dst, k->k_mask, 0),
   1127 				       naddr_ntoa(k->k_gate));
   1128 				del_static(k->k_dst, k->k_mask, k->k_gate, 1);
   1129 			}
   1130 		}
   1131 	}
   1132 }
   1133 
   1134 
   1135 /* Listen to announcements from the kernel
   1136  */
   1137 void
   1138 read_rt(void)
   1139 {
   1140 	long cc;
   1141 	struct interface *ifp;
   1142 	struct sockaddr_in gate_sin;
   1143 	naddr mask, gate;
   1144 	union {
   1145 		struct {
   1146 			struct rt_msghdr rtm;
   1147 			struct sockaddr addrs[RTAX_MAX];
   1148 		} r;
   1149 		struct if_msghdr ifm;
   1150 	} m;
   1151 	char str[100], *strp;
   1152 	struct rt_addrinfo info;
   1153 
   1154 
   1155 	for (;;) {
   1156 		cc = read(rt_sock, &m, sizeof(m));
   1157 		if (cc <= 0) {
   1158 			if (cc < 0 && errno != EWOULDBLOCK)
   1159 				LOGERR("read(rt_sock)");
   1160 			return;
   1161 		}
   1162 
   1163 		if (m.r.rtm.rtm_version != RTM_VERSION) {
   1164 			msglog("bogus routing message version %d",
   1165 			       m.r.rtm.rtm_version);
   1166 			continue;
   1167 		}
   1168 
   1169 		/* Ignore our own results.
   1170 		 */
   1171 		if (m.r.rtm.rtm_type <= RTM_CHANGE
   1172 		    && m.r.rtm.rtm_pid == mypid) {
   1173 			static int complained = 0;
   1174 			if (!complained) {
   1175 				msglog("receiving our own change messages");
   1176 				complained = 1;
   1177 			}
   1178 			continue;
   1179 		}
   1180 
   1181 		if (m.r.rtm.rtm_type == RTM_IFINFO
   1182 		    || m.r.rtm.rtm_type == RTM_NEWADDR
   1183 		    || m.r.rtm.rtm_type == RTM_DELADDR) {
   1184 			ifp = ifwithindex(m.ifm.ifm_index,
   1185 					  m.r.rtm.rtm_type != RTM_DELADDR);
   1186 			if (ifp == 0)
   1187 				trace_act("note %s with flags %#x"
   1188 					  " for unknown interface index #%d",
   1189 					  rtm_type_name(m.r.rtm.rtm_type),
   1190 					  m.ifm.ifm_flags,
   1191 					  m.ifm.ifm_index);
   1192 			else
   1193 				trace_act("note %s with flags %#x for %s",
   1194 					  rtm_type_name(m.r.rtm.rtm_type),
   1195 					  m.ifm.ifm_flags,
   1196 					  ifp->int_name);
   1197 
   1198 			/* After being informed of a change to an interface,
   1199 			 * check them all now if the check would otherwise
   1200 			 * be a long time from now, if the interface is
   1201 			 * not known, or if the interface has been turned
   1202 			 * off or on.
   1203 			 */
   1204 			if (ifinit_timer.tv_sec-now.tv_sec>=CHECK_BAD_INTERVAL
   1205 			    || ifp == 0
   1206 			    || ((ifp->int_if_flags ^ m.ifm.ifm_flags)
   1207 				& IFF_UP) != 0)
   1208 				ifinit_timer.tv_sec = now.tv_sec;
   1209 			continue;
   1210 		}
   1211 
   1212 		strcpy(str, rtm_type_name(m.r.rtm.rtm_type));
   1213 		strp = &str[strlen(str)];
   1214 		if (m.r.rtm.rtm_type <= RTM_CHANGE)
   1215 			strp += sprintf(strp," from pid %d",m.r.rtm.rtm_pid);
   1216 
   1217 		rt_xaddrs(&info, m.r.addrs, &m.r.addrs[RTAX_MAX],
   1218 			  m.r.rtm.rtm_addrs);
   1219 
   1220 		if (INFO_DST(&info) == 0) {
   1221 			trace_act("ignore %s without dst", str);
   1222 			continue;
   1223 		}
   1224 
   1225 		if (INFO_DST(&info)->sa_family != AF_INET) {
   1226 			trace_act("ignore %s for AF %d", str,
   1227 				  INFO_DST(&info)->sa_family);
   1228 			continue;
   1229 		}
   1230 
   1231 		mask = ((INFO_MASK(&info) != 0)
   1232 			? ntohl(S_ADDR(INFO_MASK(&info)))
   1233 			: (m.r.rtm.rtm_flags & RTF_HOST)
   1234 			? HOST_MASK
   1235 			: std_mask(S_ADDR(INFO_DST(&info))));
   1236 
   1237 		strp += sprintf(strp, ": %s",
   1238 				addrname(S_ADDR(INFO_DST(&info)), mask, 0));
   1239 
   1240 		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info))))) {
   1241 			trace_act("ignore multicast %s", str);
   1242 			continue;
   1243 		}
   1244 
   1245 		if (m.r.rtm.rtm_flags & RTF_LLINFO) {
   1246 			trace_act("ignore ARP %s", str);
   1247 			continue;
   1248 		}
   1249 
   1250 		if (get_info_gate(&INFO_GATE(&info), &gate_sin)) {
   1251 			gate = S_ADDR(INFO_GATE(&info));
   1252 			strp += sprintf(strp, " --> %s", naddr_ntoa(gate));
   1253 		} else {
   1254 			gate = 0;
   1255 		}
   1256 
   1257 		if (INFO_AUTHOR(&info) != 0)
   1258 			strp += sprintf(strp, " by authority of %s",
   1259 					saddr_ntoa(INFO_AUTHOR(&info)));
   1260 
   1261 		switch (m.r.rtm.rtm_type) {
   1262 		case RTM_ADD:
   1263 		case RTM_CHANGE:
   1264 		case RTM_REDIRECT:
   1265 			if (m.r.rtm.rtm_errno != 0) {
   1266 				trace_act("ignore %s with \"%s\" error",
   1267 					  str, strerror(m.r.rtm.rtm_errno));
   1268 			} else {
   1269 				trace_act("%s", str);
   1270 				rtm_add(&m.r.rtm,&info,0);
   1271 			}
   1272 			break;
   1273 
   1274 		case RTM_DELETE:
   1275 			if (m.r.rtm.rtm_errno != 0
   1276 			    && m.r.rtm.rtm_errno != ESRCH) {
   1277 				trace_act("ignore %s with \"%s\" error",
   1278 					  str, strerror(m.r.rtm.rtm_errno));
   1279 			} else {
   1280 				trace_act("%s", str);
   1281 				del_static(S_ADDR(INFO_DST(&info)), mask,
   1282 					   gate, 1);
   1283 			}
   1284 			break;
   1285 
   1286 		case RTM_LOSING:
   1287 			trace_act("%s", str);
   1288 			rtm_lose(&m.r.rtm,&info);
   1289 			break;
   1290 
   1291 		default:
   1292 			trace_act("ignore %s", str);
   1293 			break;
   1294 		}
   1295 	}
   1296 }
   1297 
   1298 
   1299 /* after aggregating, note routes that belong in the kernel
   1300  */
   1301 static void
   1302 kern_out(struct ag_info *ag)
   1303 {
   1304 	struct khash *k;
   1305 
   1306 
   1307 	/* Do not install bad routes if they are not already present.
   1308 	 * This includes routes that had RS_NET_SYN for interfaces that
   1309 	 * recently died.
   1310 	 */
   1311 	if (ag->ag_metric == HOPCNT_INFINITY) {
   1312 		k = kern_find(htonl(ag->ag_dst_h), ag->ag_mask, 0);
   1313 		if (k == 0)
   1314 			return;
   1315 	} else {
   1316 		k = kern_add(htonl(ag->ag_dst_h), ag->ag_mask);
   1317 	}
   1318 
   1319 	if (k->k_state & KS_NEW) {
   1320 		/* will need to add new entry to the kernel table */
   1321 		k->k_state = KS_ADD;
   1322 		if (ag->ag_state & AGS_GATEWAY)
   1323 			k->k_state |= KS_GATEWAY;
   1324 		k->k_gate = ag->ag_gate;
   1325 		k->k_metric = ag->ag_metric;
   1326 		return;
   1327 	}
   1328 
   1329 	if (k->k_state & KS_STATIC)
   1330 		return;
   1331 
   1332 	/* modify existing kernel entry if necessary */
   1333 	if (k->k_gate != ag->ag_gate
   1334 	    || k->k_metric != ag->ag_metric) {
   1335 		/* Must delete bad interface routes etc. to change them. */
   1336 		if (k->k_metric == HOPCNT_INFINITY)
   1337 			k->k_state |= KS_DEL_ADD;
   1338 		k->k_gate = ag->ag_gate;
   1339 		k->k_metric = ag->ag_metric;
   1340 		k->k_state |= KS_CHANGE;
   1341 	}
   1342 
   1343 	/* If the daemon thinks the route should exist, forget
   1344 	 * about any redirections.
   1345 	 * If the daemon thinks the route should exist, eventually
   1346 	 * override manual intervention by the operator.
   1347 	 */
   1348 	if ((k->k_state & (KS_DYNAMIC | KS_DELETED)) != 0) {
   1349 		k->k_state &= ~KS_DYNAMIC;
   1350 		k->k_state |= (KS_ADD | KS_DEL_ADD);
   1351 	}
   1352 
   1353 	if ((k->k_state & KS_GATEWAY)
   1354 	    && !(ag->ag_state & AGS_GATEWAY)) {
   1355 		k->k_state &= ~KS_GATEWAY;
   1356 		k->k_state |= (KS_ADD | KS_DEL_ADD);
   1357 	} else if (!(k->k_state & KS_GATEWAY)
   1358 		   && (ag->ag_state & AGS_GATEWAY)) {
   1359 		k->k_state |= KS_GATEWAY;
   1360 		k->k_state |= (KS_ADD | KS_DEL_ADD);
   1361 	}
   1362 
   1363 	/* Deleting-and-adding is necessary to change aspects of a route.
   1364 	 * Just delete instead of deleting and then adding a bad route.
   1365 	 * Otherwise, we want to keep the route in the kernel.
   1366 	 */
   1367 	if (k->k_metric == HOPCNT_INFINITY
   1368 	    && (k->k_state & KS_DEL_ADD))
   1369 		k->k_state |= KS_DELETE;
   1370 	else
   1371 		k->k_state &= ~KS_DELETE;
   1372 #undef RT
   1373 }
   1374 
   1375 
   1376 /* ARGSUSED */
   1377 static int
   1378 walk_kern(struct radix_node *rn,
   1379 	  struct walkarg *argp UNUSED)
   1380 {
   1381 #define RT ((struct rt_entry *)rn)
   1382 	char metric, pref;
   1383 	u_int ags = 0;
   1384 
   1385 
   1386 	/* Do not install synthetic routes */
   1387 	if (RT->rt_state & RS_NET_SYN)
   1388 		return 0;
   1389 
   1390 	if (!(RT->rt_state & RS_IF)) {
   1391 		/* This is an ordinary route, not for an interface.
   1392 		 */
   1393 
   1394 		/* aggregate, ordinary good routes without regard to
   1395 		 * their metric
   1396 		 */
   1397 		pref = 1;
   1398 		ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
   1399 
   1400 		/* Do not install host routes directly to hosts, to avoid
   1401 		 * interfering with ARP entries in the kernel table.
   1402 		 */
   1403 		if (RT_ISHOST(RT)
   1404 		    && ntohl(RT->rt_dst) == RT->rt_gate)
   1405 			return 0;
   1406 
   1407 	} else {
   1408 		/* This is an interface route.
   1409 		 * Do not install routes for "external" remote interfaces.
   1410 		 */
   1411 		if (RT->rt_ifp != 0 && (RT->rt_ifp->int_state & IS_EXTERNAL))
   1412 			return 0;
   1413 
   1414 		/* Interfaces should override received routes.
   1415 		 */
   1416 		pref = 0;
   1417 		ags |= (AGS_IF | AGS_CORS_GATE);
   1418 
   1419 		/* If it is not an interface, or an alias for an interface,
   1420 		 * it must be a "gateway."
   1421 		 *
   1422 		 * If it is a "remote" interface, it is also a "gateway" to
   1423 		 * the kernel if is not a alias.
   1424 		 */
   1425 		if (RT->rt_ifp == 0
   1426 		    || (RT->rt_ifp->int_state & IS_REMOTE))
   1427 			ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
   1428 	}
   1429 
   1430 	/* If RIP is off and IRDP is on, let the route to the discovered
   1431 	 * route suppress any RIP routes.  Eventually the RIP routes
   1432 	 * will time-out and be deleted.  This reaches the steady-state
   1433 	 * quicker.
   1434 	 */
   1435 	if ((RT->rt_state & RS_RDISC) && rip_sock < 0)
   1436 		ags |= AGS_CORS_GATE;
   1437 
   1438 	metric = RT->rt_metric;
   1439 	if (metric == HOPCNT_INFINITY) {
   1440 		/* if the route is dead, so try hard to aggregate. */
   1441 		pref = HOPCNT_INFINITY;
   1442 		ags |= (AGS_FINE_GATE | AGS_SUPPRESS);
   1443 		ags &= ~(AGS_IF | AGS_CORS_GATE);
   1444 	}
   1445 
   1446 	ag_check(RT->rt_dst, RT->rt_mask, RT->rt_gate, 0,
   1447 		 metric,pref, 0, 0, ags, kern_out);
   1448 	return 0;
   1449 #undef RT
   1450 }
   1451 
   1452 
   1453 /* Update the kernel table to match the daemon table.
   1454  */
   1455 static void
   1456 fix_kern(void)
   1457 {
   1458 	int i;
   1459 	struct khash *k, **pk;
   1460 
   1461 
   1462 	need_kern = age_timer;
   1463 
   1464 	/* Walk daemon table, updating the copy of the kernel table.
   1465 	 */
   1466 	(void)rn_walktree(rhead, walk_kern, 0);
   1467 	ag_flush(0,0,kern_out);
   1468 
   1469 	for (i = 0; i < KHASH_SIZE; i++) {
   1470 		for (pk = &khash_bins[i]; (k = *pk) != 0; ) {
   1471 			/* Do not touch static routes */
   1472 			if (k->k_state & KS_STATIC) {
   1473 				kern_check_static(k,0);
   1474 				pk = &k->k_next;
   1475 				continue;
   1476 			}
   1477 
   1478 			/* check hold on routes deleted by the operator */
   1479 			if (k->k_keep > now.tv_sec) {
   1480 				/* ensure we check when the hold is over */
   1481 				LIM_SEC(need_kern, k->k_keep);
   1482 				/* mark for the next cycle */
   1483 				k->k_state |= KS_DELETE;
   1484 				pk = &k->k_next;
   1485 				continue;
   1486 			}
   1487 
   1488 			if ((k->k_state & KS_DELETE)
   1489 			    && !(k->k_state & KS_DYNAMIC)) {
   1490 				kern_ioctl(k, RTM_DELETE, 0);
   1491 				*pk = k->k_next;
   1492 				free(k);
   1493 				continue;
   1494 			}
   1495 
   1496 			if (k->k_state & KS_DEL_ADD)
   1497 				kern_ioctl(k, RTM_DELETE, 0);
   1498 
   1499 			if (k->k_state & KS_ADD) {
   1500 				kern_ioctl(k, RTM_ADD,
   1501 					   ((0 != (k->k_state & (KS_GATEWAY
   1502 							| KS_DYNAMIC)))
   1503 					    ? RTF_GATEWAY : 0));
   1504 			} else if (k->k_state & KS_CHANGE) {
   1505 				kern_ioctl(k,  RTM_CHANGE,
   1506 					   ((0 != (k->k_state & (KS_GATEWAY
   1507 							| KS_DYNAMIC)))
   1508 					    ? RTF_GATEWAY : 0));
   1509 			}
   1510 			k->k_state &= ~(KS_ADD|KS_CHANGE|KS_DEL_ADD);
   1511 
   1512 			/* Mark this route to be deleted in the next cycle.
   1513 			 * This deletes routes that disappear from the
   1514 			 * daemon table, since the normal aging code
   1515 			 * will clear the bit for routes that have not
   1516 			 * disappeared from the daemon table.
   1517 			 */
   1518 			k->k_state |= KS_DELETE;
   1519 			pk = &k->k_next;
   1520 		}
   1521 	}
   1522 }
   1523 
   1524 
   1525 /* Delete a static route in the image of the kernel table.
   1526  */
   1527 void
   1528 del_static(naddr dst,
   1529 	   naddr mask,
   1530 	   naddr gate,
   1531 	   int gone)
   1532 {
   1533 	struct khash *k;
   1534 	struct rt_entry *rt;
   1535 
   1536 	/* Just mark it in the table to be deleted next time the kernel
   1537 	 * table is updated.
   1538 	 * If it has already been deleted, mark it as such, and set its
   1539 	 * keep-timer so that it will not be deleted again for a while.
   1540 	 * This lets the operator delete a route added by the daemon
   1541 	 * and add a replacement.
   1542 	 */
   1543 	k = kern_find(dst, mask, 0);
   1544 	if (k != 0 && (gate == 0 || k->k_gate == gate)) {
   1545 		k->k_state &= ~(KS_STATIC | KS_DYNAMIC | KS_CHECK);
   1546 		k->k_state |= KS_DELETE;
   1547 		if (gone) {
   1548 			k->k_state |= KS_DELETED;
   1549 			k->k_keep = now.tv_sec + K_KEEP_LIM;
   1550 		}
   1551 	}
   1552 
   1553 	rt = rtget(dst, mask);
   1554 	if (rt != 0 && (rt->rt_state & RS_STATIC))
   1555 		rtbad(rt);
   1556 }
   1557 
   1558 
   1559 /* Delete all routes generated from ICMP Redirects that use a given gateway,
   1560  * as well as old redirected routes.
   1561  */
   1562 void
   1563 del_redirects(naddr bad_gate,
   1564 	      time_t old)
   1565 {
   1566 	int i;
   1567 	struct khash *k;
   1568 
   1569 
   1570 	for (i = 0; i < KHASH_SIZE; i++) {
   1571 		for (k = khash_bins[i]; k != 0; k = k->k_next) {
   1572 			if (!(k->k_state & KS_DYNAMIC)
   1573 			    || (k->k_state & KS_STATIC))
   1574 				continue;
   1575 
   1576 			if (k->k_gate != bad_gate
   1577 			    && k->k_redirect_time > old
   1578 			    && !supplier)
   1579 				continue;
   1580 
   1581 			k->k_state |= KS_DELETE;
   1582 			k->k_state &= ~KS_DYNAMIC;
   1583 			need_kern.tv_sec = now.tv_sec;
   1584 			trace_act("mark redirected %s --> %s for deletion",
   1585 				  addrname(k->k_dst, k->k_mask, 0),
   1586 				  naddr_ntoa(k->k_gate));
   1587 		}
   1588 	}
   1589 }
   1590 
   1591 
   1592 /* Start the daemon tables.
   1593  */
   1594 extern int max_keylen;
   1595 
   1596 void
   1597 rtinit(void)
   1598 {
   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 	memset(rt, 0, 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=%#lx",
   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", (int)(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 *argp UNUSED)
   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 *argp UNUSED)
   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 			       " %ld:%ld",
   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