xref: /titanic_50/usr/src/cmd/cmd-inet/usr.sbin/in.routed/table.c (revision 3af08d828975d7e2581b6829e0eecff14d87a483)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  *
5  * Copyright (c) 1983, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgment:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD: src/sbin/routed/table.c,v 1.15 2000/08/11 08:24:38 sheldonh Exp $
37  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 #include "defs.h"
42 #include <fcntl.h>
43 #include <stropts.h>
44 #include <sys/tihdr.h>
45 #include <inet/mib2.h>
46 #include <inet/ip.h>
47 
48 /* This structure is used to store a disassembled routing socket message. */
49 struct rt_addrinfo {
50 	int	rti_addrs;
51 	struct sockaddr_storage *rti_info[RTAX_MAX];
52 };
53 
54 static struct rt_spare *rts_better(struct rt_entry *);
55 static struct rt_spare rts_empty = EMPTY_RT_SPARE;
56 static void set_need_flash(void);
57 static void rtbad(struct rt_entry *, struct interface *);
58 static int rt_xaddrs(struct rt_addrinfo *, struct sockaddr_storage *,
59     char *, int);
60 static struct interface *gwkludge_iflookup(in_addr_t, in_addr_t, in_addr_t);
61 
62 struct radix_node_head *rhead;		/* root of the radix tree */
63 
64 /* Flash update needed.  _B_TRUE to suppress the 1st. */
65 boolean_t need_flash = _B_TRUE;
66 
67 struct timeval age_timer;		/* next check of old routes */
68 struct timeval need_kern = {		/* need to update kernel table */
69 	EPOCH+MIN_WAITTIME-1, 0
70 };
71 
72 static uint32_t	total_routes;
73 
74 #define	ROUNDUP_LONG(a) \
75 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
76 
77 /*
78  * It is desirable to "aggregate" routes, to combine differing routes of
79  * the same metric and next hop into a common route with a smaller netmask
80  * or to suppress redundant routes, routes that add no information to
81  * routes with smaller netmasks.
82  *
83  * A route is redundant if and only if any and all routes with smaller
84  * but matching netmasks and nets are the same.  Since routes are
85  * kept sorted in the radix tree, redundant routes always come second.
86  *
87  * There are two kinds of aggregations.  First, two routes of the same bit
88  * mask and differing only in the least significant bit of the network
89  * number can be combined into a single route with a coarser mask.
90  *
91  * Second, a route can be suppressed in favor of another route with a more
92  * coarse mask provided no incompatible routes with intermediate masks
93  * are present.  The second kind of aggregation involves suppressing routes.
94  * A route must not be suppressed if an incompatible route exists with
95  * an intermediate mask, since the suppressed route would be covered
96  * by the intermediate.
97  *
98  * This code relies on the radix tree walk encountering routes
99  * sorted first by address, with the smallest address first.
100  */
101 
102 static struct ag_info ag_slots[NUM_AG_SLOTS], *ag_avail, *ag_corsest,
103 	*ag_finest;
104 
105 #ifdef DEBUG_AG
106 #define	CHECK_AG() do { int acnt = 0; struct ag_info *cag;	\
107 	for (cag = ag_avail; cag != NULL; cag = cag->ag_fine)	\
108 		acnt++;						\
109 	for (cag = ag_corsest; cag != NULL; cag = cag->ag_fine)	\
110 		acnt++;						\
111 	if (acnt != NUM_AG_SLOTS)				\
112 		abort();					\
113 } while (_B_FALSE)
114 #else
115 #define	CHECK_AG()	(void)0
116 #endif
117 
118 
119 /*
120  * Output the contents of an aggregation table slot.
121  *	This function must always be immediately followed with the deletion
122  *	of the target slot.
123  */
124 static void
125 ag_out(struct ag_info *ag, void (*out)(struct ag_info *))
126 {
127 	struct ag_info *ag_cors;
128 	uint32_t bit;
129 
130 
131 	/* Forget it if this route should not be output for split-horizon. */
132 	if (ag->ag_state & AGS_SPLIT_HZ)
133 		return;
134 
135 	/*
136 	 * If we output both the even and odd twins, then the immediate parent,
137 	 * if it is present, is redundant, unless the parent manages to
138 	 * aggregate into something coarser.
139 	 * On successive calls, this code detects the even and odd twins,
140 	 * and marks the parent.
141 	 *
142 	 * Note that the order in which the radix tree code emits routes
143 	 * ensures that the twins are seen before the parent is emitted.
144 	 */
145 	ag_cors = ag->ag_cors;
146 	if (ag_cors != NULL &&
147 	    ag_cors->ag_mask == (ag->ag_mask << 1) &&
148 	    ag_cors->ag_dst_h == (ag->ag_dst_h & ag_cors->ag_mask)) {
149 		ag_cors->ag_state |= ((ag_cors->ag_dst_h == ag->ag_dst_h) ?
150 		    AGS_REDUN0 : AGS_REDUN1);
151 	}
152 
153 	/*
154 	 * Skip it if this route is itself redundant.
155 	 *
156 	 * It is ok to change the contents of the slot here, since it is
157 	 * always deleted next.
158 	 */
159 	if (ag->ag_state & AGS_REDUN0) {
160 		if (ag->ag_state & AGS_REDUN1)
161 			return;		/* quit if fully redundant */
162 		/* make it finer if it is half-redundant */
163 		bit = (-ag->ag_mask) >> 1;
164 		ag->ag_dst_h |= bit;
165 		ag->ag_mask |= bit;
166 
167 	} else if (ag->ag_state & AGS_REDUN1) {
168 		/* make it finer if it is half-redundant */
169 		bit = (-ag->ag_mask) >> 1;
170 		ag->ag_mask |= bit;
171 	}
172 	out(ag);
173 }
174 
175 
176 static void
177 ag_del(struct ag_info *ag)
178 {
179 	CHECK_AG();
180 
181 	if (ag->ag_cors == NULL)
182 		ag_corsest = ag->ag_fine;
183 	else
184 		ag->ag_cors->ag_fine = ag->ag_fine;
185 
186 	if (ag->ag_fine == NULL)
187 		ag_finest = ag->ag_cors;
188 	else
189 		ag->ag_fine->ag_cors = ag->ag_cors;
190 
191 	ag->ag_fine = ag_avail;
192 	ag_avail = ag;
193 
194 	CHECK_AG();
195 }
196 
197 
198 /* Look for a route that can suppress the given route. */
199 static struct ag_info *
200 ag_find_suppressor(struct ag_info *ag)
201 {
202 	struct ag_info *ag_cors;
203 	in_addr_t dst_h = ag->ag_dst_h;
204 
205 	for (ag_cors = ag->ag_cors; ag_cors != NULL;
206 	    ag_cors = ag_cors->ag_cors) {
207 
208 		if ((dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h) {
209 			/*
210 			 * We found a route with a coarser mask that covers
211 			 * the given target.  It can suppress the target
212 			 * only if it has a good enough metric and it
213 			 * either has the same (gateway, ifp), or if its state
214 			 * includes AGS_CORS_GATE or the target's state
215 			 * includes AGS_FINE_GATE.
216 			 */
217 			if (ag_cors->ag_pref <= ag->ag_pref &&
218 			    (((ag->ag_nhop == ag_cors->ag_nhop) &&
219 			    (ag->ag_ifp == ag_cors->ag_ifp)) ||
220 			    ag_cors->ag_state & AGS_CORS_GATE ||
221 			    ag->ag_state & AGS_FINE_GATE)) {
222 				return (ag_cors);
223 			}
224 		}
225 	}
226 
227 	return (NULL);
228 }
229 
230 
231 /*
232  * Flush routes waiting for aggregation.
233  * This must not suppress a route unless it is known that among all routes
234  * with coarser masks that match it, the one with the longest mask is
235  * appropriate.  This is ensured by scanning the routes in lexical order,
236  * and with the most restrictive mask first among routes to the same
237  * destination.
238  */
239 void
240 ag_flush(in_addr_t lim_dst_h,	/* flush routes to here */
241     in_addr_t lim_mask,		/* matching this mask */
242     void (*out)(struct ag_info *))
243 {
244 	struct ag_info *ag, *ag_cors, *ag_supr;
245 	in_addr_t dst_h;
246 
247 
248 	for (ag = ag_finest; ag != NULL && ag->ag_mask >= lim_mask;
249 	    ag = ag_cors) {
250 		/* Get the next route now, before we delete ag. */
251 		ag_cors = ag->ag_cors;
252 
253 		/* Work on only the specified routes. */
254 		dst_h = ag->ag_dst_h;
255 		if ((dst_h & lim_mask) != lim_dst_h)
256 			continue;
257 
258 		/*
259 		 * Don't try to suppress the route if its state doesn't
260 		 * include AGS_SUPPRESS.
261 		 */
262 		if (!(ag->ag_state & AGS_SUPPRESS)) {
263 			ag_out(ag, out);
264 			ag_del(ag);
265 			continue;
266 		}
267 
268 		ag_supr = ag_find_suppressor(ag);
269 		if (ag_supr == NULL) {
270 			/*
271 			 * We didn't find a route which suppresses the
272 			 * target, so the target can go out.
273 			 */
274 			ag_out(ag, out);
275 		} else {
276 			/*
277 			 * We found a route which suppresses the target, so
278 			 * don't output the target.
279 			 */
280 			if (TRACEACTIONS) {
281 				trace_misc("aggregated away %s",
282 				    rtname(htonl(ag->ag_dst_h), ag->ag_mask,
283 				    ag->ag_nhop));
284 				trace_misc("on coarser route %s",
285 				    rtname(htonl(ag_supr->ag_dst_h),
286 				    ag_supr->ag_mask, ag_supr->ag_nhop));
287 			}
288 			/*
289 			 * If the suppressed target was redundant, then
290 			 * mark the suppressor as redundant.
291 			 */
292 			if (AG_IS_REDUN(ag->ag_state) &&
293 			    ag_supr->ag_mask == (ag->ag_mask<<1)) {
294 				if (ag_supr->ag_dst_h == dst_h)
295 					ag_supr->ag_state |= AGS_REDUN0;
296 				else
297 					ag_supr->ag_state |= AGS_REDUN1;
298 			}
299 			if (ag->ag_tag != ag_supr->ag_tag)
300 				ag_supr->ag_tag = 0;
301 			if (ag->ag_nhop != ag_supr->ag_nhop)
302 				ag_supr->ag_nhop = 0;
303 		}
304 
305 		/* The route has either been output or suppressed */
306 		ag_del(ag);
307 	}
308 
309 	CHECK_AG();
310 }
311 
312 
313 /* Try to aggregate a route with previous routes. */
314 void
315 ag_check(in_addr_t dst,
316     in_addr_t	mask,
317     in_addr_t	gate,
318     struct interface *ifp,
319     in_addr_t	nhop,
320     uint8_t	metric,
321     uint8_t	pref,
322     uint32_t	seqno,
323     uint16_t	tag,
324     uint16_t	state,
325     void (*out)(struct ag_info *))	/* output using this */
326 {
327 	struct ag_info *ag, *nag, *ag_cors;
328 	in_addr_t xaddr;
329 	int tmp;
330 	struct interface *xifp;
331 
332 	dst = ntohl(dst);
333 
334 	/*
335 	 * Don't bother trying to aggregate routes with non-contiguous
336 	 * subnet masks.
337 	 *
338 	 * (X & -X) contains a single bit if and only if X is a power of 2.
339 	 * (X + (X & -X)) == 0 if and only if X is a power of 2.
340 	 */
341 	if ((mask & -mask) + mask != 0) {
342 		struct ag_info nc_ag;
343 
344 		nc_ag.ag_dst_h = dst;
345 		nc_ag.ag_mask = mask;
346 		nc_ag.ag_gate = gate;
347 		nc_ag.ag_ifp = ifp;
348 		nc_ag.ag_nhop = nhop;
349 		nc_ag.ag_metric = metric;
350 		nc_ag.ag_pref = pref;
351 		nc_ag.ag_tag = tag;
352 		nc_ag.ag_state = state;
353 		nc_ag.ag_seqno = seqno;
354 		out(&nc_ag);
355 		return;
356 	}
357 
358 	/* Search for the right slot in the aggregation table. */
359 	ag_cors = NULL;
360 	ag = ag_corsest;
361 	while (ag != NULL) {
362 		if (ag->ag_mask >= mask)
363 			break;
364 
365 		/*
366 		 * Suppress old routes (i.e. combine with compatible routes
367 		 * with coarser masks) as we look for the right slot in the
368 		 * aggregation table for the new route.
369 		 * A route to an address less than the current destination
370 		 * will not be affected by the current route or any route
371 		 * seen hereafter.  That means it is safe to suppress it.
372 		 * This check keeps poor routes (e.g. with large hop counts)
373 		 * from preventing suppression of finer routes.
374 		 */
375 		if (ag_cors != NULL && ag->ag_dst_h < dst &&
376 		    (ag->ag_state & AGS_SUPPRESS) &&
377 		    ag_cors->ag_pref <= ag->ag_pref &&
378 		    (ag->ag_dst_h & ag_cors->ag_mask) == ag_cors->ag_dst_h &&
379 		    ((ag_cors->ag_nhop == ag->ag_nhop &&
380 		    (ag_cors->ag_ifp == ag->ag_ifp))||
381 			(ag->ag_state & AGS_FINE_GATE) ||
382 			(ag_cors->ag_state & AGS_CORS_GATE))) {
383 			/*
384 			 * If the suppressed target was redundant,
385 			 * then mark the suppressor redundant.
386 			 */
387 			if (AG_IS_REDUN(ag->ag_state) &&
388 			    ag_cors->ag_mask == (ag->ag_mask << 1)) {
389 				if (ag_cors->ag_dst_h == dst)
390 					ag_cors->ag_state |= AGS_REDUN0;
391 				else
392 					ag_cors->ag_state |= AGS_REDUN1;
393 			}
394 			if (ag->ag_tag != ag_cors->ag_tag)
395 				ag_cors->ag_tag = 0;
396 			if (ag->ag_nhop != ag_cors->ag_nhop)
397 				ag_cors->ag_nhop = 0;
398 			ag_del(ag);
399 			CHECK_AG();
400 		} else {
401 			ag_cors = ag;
402 		}
403 		ag = ag_cors->ag_fine;
404 	}
405 
406 	/*
407 	 * If we find the even/odd twin of the new route, and if the
408 	 * masks and so forth are equal, we can aggregate them.
409 	 * We can probably promote one of the pair.
410 	 *
411 	 * Since the routes are encountered in lexical order,
412 	 * the new route must be odd.  However, the second or later
413 	 * times around this loop, it could be the even twin promoted
414 	 * from the even/odd pair of twins of the finer route.
415 	 */
416 	while (ag != NULL && ag->ag_mask == mask &&
417 	    ((ag->ag_dst_h ^ dst) & (mask<<1)) == 0) {
418 
419 		/*
420 		 * Here we know the target route and the route in the current
421 		 * slot have the same netmasks and differ by at most the
422 		 * last bit.  They are either for the same destination, or
423 		 * for an even/odd pair of destinations.
424 		 */
425 		if (ag->ag_dst_h == dst) {
426 			if (ag->ag_nhop == nhop && ag->ag_ifp == ifp) {
427 				/*
428 				 * We have two routes to the same destination,
429 				 * with the same nexthop and interface.
430 				 * Routes are encountered in lexical order,
431 				 * so a route is never promoted until the
432 				 * parent route is already present.  So we
433 				 * know that the new route is a promoted (or
434 				 * aggregated) pair and the route already in
435 				 * the slot is the explicit route.
436 				 *
437 				 * Prefer the best route if their metrics
438 				 * differ, or the aggregated one if not,
439 				 * following a sort of longest-match rule.
440 				 */
441 				if (pref <= ag->ag_pref) {
442 					ag->ag_gate = gate;
443 					ag->ag_ifp = ifp;
444 					ag->ag_nhop = nhop;
445 					ag->ag_tag = tag;
446 					ag->ag_metric = metric;
447 					ag->ag_pref = pref;
448 					if (seqno > ag->ag_seqno)
449 						ag->ag_seqno = seqno;
450 					tmp = ag->ag_state;
451 					ag->ag_state = state;
452 					state = tmp;
453 				}
454 
455 				/*
456 				 * Some bits are set if they are set on
457 				 * either route, except when the route is
458 				 * for an interface.
459 				 */
460 				if (!(ag->ag_state & AGS_IF))
461 					ag->ag_state |=
462 					    (state & (AGS_AGGREGATE_EITHER |
463 					    AGS_REDUN0 | AGS_REDUN1));
464 
465 				return;
466 			} else {
467 				/*
468 				 * multiple routes to same dest/mask with
469 				 * differing gate nexthop/or ifp. Flush
470 				 * both out.
471 				 */
472 				break;
473 			}
474 		}
475 
476 		/*
477 		 * If one of the routes can be promoted and the other can
478 		 * be suppressed, it may be possible to combine them or
479 		 * worthwhile to promote one.
480 		 *
481 		 * Any route that can be promoted is always
482 		 * marked to be eligible to be suppressed.
483 		 */
484 		if (!((state & AGS_AGGREGATE) &&
485 		    (ag->ag_state & AGS_SUPPRESS)) &&
486 		    !((ag->ag_state & AGS_AGGREGATE) && (state & AGS_SUPPRESS)))
487 			break;
488 
489 		/*
490 		 * A pair of even/odd twin routes can be combined
491 		 * if either is redundant, or if they are via the
492 		 * same gateway and have the same metric.
493 		 */
494 		if (AG_IS_REDUN(ag->ag_state) || AG_IS_REDUN(state) ||
495 		    (ag->ag_nhop == nhop && ag->ag_ifp == ifp &&
496 		    ag->ag_pref == pref &&
497 		    (state & ag->ag_state & AGS_AGGREGATE) != 0)) {
498 
499 			/*
500 			 * We have both the even and odd pairs.
501 			 * Since the routes are encountered in order,
502 			 * the route in the slot must be the even twin.
503 			 *
504 			 * Combine and promote (aggregate) the pair of routes.
505 			 */
506 			if (seqno < ag->ag_seqno)
507 				seqno = ag->ag_seqno;
508 			if (!AG_IS_REDUN(state))
509 				state &= ~AGS_REDUN1;
510 			if (AG_IS_REDUN(ag->ag_state))
511 				state |= AGS_REDUN0;
512 			else
513 				state &= ~AGS_REDUN0;
514 			state |= (ag->ag_state & AGS_AGGREGATE_EITHER);
515 			if (ag->ag_tag != tag)
516 				tag = 0;
517 			if (ag->ag_nhop != nhop)
518 				nhop = 0;
519 
520 			/*
521 			 * Get rid of the even twin that was already
522 			 * in the slot.
523 			 */
524 			ag_del(ag);
525 
526 		} else if (ag->ag_pref >= pref &&
527 		    (ag->ag_state & AGS_AGGREGATE)) {
528 			/*
529 			 * If we cannot combine the pair, maybe the route
530 			 * with the worse metric can be promoted.
531 			 *
532 			 * Promote the old, even twin, by giving its slot
533 			 * in the table to the new, odd twin.
534 			 */
535 			ag->ag_dst_h = dst;
536 
537 			xaddr = ag->ag_gate;
538 			ag->ag_gate = gate;
539 			gate = xaddr;
540 
541 			xifp = ag->ag_ifp;
542 			ag->ag_ifp = ifp;
543 			ifp = xifp;
544 
545 			xaddr = ag->ag_nhop;
546 			ag->ag_nhop = nhop;
547 			nhop = xaddr;
548 
549 			tmp = ag->ag_tag;
550 			ag->ag_tag = tag;
551 			tag = tmp;
552 
553 			/*
554 			 * The promoted route is even-redundant only if the
555 			 * even twin was fully redundant.  It is not
556 			 * odd-redundant because the odd-twin will still be
557 			 * in the table.
558 			 */
559 			tmp = ag->ag_state;
560 			if (!AG_IS_REDUN(tmp))
561 				tmp &= ~AGS_REDUN0;
562 			tmp &= ~AGS_REDUN1;
563 			ag->ag_state = state;
564 			state = tmp;
565 
566 			tmp = ag->ag_metric;
567 			ag->ag_metric = metric;
568 			metric = tmp;
569 
570 			tmp = ag->ag_pref;
571 			ag->ag_pref = pref;
572 			pref = tmp;
573 
574 			/* take the newest sequence number */
575 			if (seqno <= ag->ag_seqno)
576 				seqno = ag->ag_seqno;
577 			else
578 				ag->ag_seqno = seqno;
579 
580 		} else {
581 			if (!(state & AGS_AGGREGATE))
582 				break;	/* cannot promote either twin */
583 
584 			/*
585 			 * Promote the new, odd twin by shaving its
586 			 * mask and address.
587 			 * The promoted route is odd-redundant only if the
588 			 * odd twin was fully redundant.  It is not
589 			 * even-redundant because the even twin is still in
590 			 * the table.
591 			 */
592 			if (!AG_IS_REDUN(state))
593 				state &= ~AGS_REDUN1;
594 			state &= ~AGS_REDUN0;
595 			if (seqno < ag->ag_seqno)
596 				seqno = ag->ag_seqno;
597 			else
598 				ag->ag_seqno = seqno;
599 		}
600 
601 		mask <<= 1;
602 		dst &= mask;
603 
604 		if (ag_cors == NULL) {
605 			ag = ag_corsest;
606 			break;
607 		}
608 		ag = ag_cors;
609 		ag_cors = ag->ag_cors;
610 	}
611 
612 	/*
613 	 * When we can no longer promote and combine routes,
614 	 * flush the old route in the target slot.  Also flush
615 	 * any finer routes that we know will never be aggregated by
616 	 * the new route.
617 	 *
618 	 * In case we moved toward coarser masks,
619 	 * get back where we belong
620 	 */
621 	if (ag != NULL && ag->ag_mask < mask) {
622 		ag_cors = ag;
623 		ag = ag->ag_fine;
624 	}
625 
626 	/* Empty the target slot */
627 	if (ag != NULL && ag->ag_mask == mask) {
628 		ag_flush(ag->ag_dst_h, ag->ag_mask, out);
629 		ag = (ag_cors == NULL) ? ag_corsest : ag_cors->ag_fine;
630 	}
631 
632 #ifdef DEBUG_AG
633 	if (ag == NULL && ag_cors != ag_finest)
634 		abort();
635 	if (ag_cors == NULL && ag != ag_corsest)
636 		abort();
637 	if (ag != NULL && ag->ag_cors != ag_cors)
638 		abort();
639 	if (ag_cors != NULL && ag_cors->ag_fine != ag)
640 		abort();
641 	CHECK_AG();
642 #endif
643 
644 	/* Save the new route on the end of the table. */
645 	nag = ag_avail;
646 	ag_avail = nag->ag_fine;
647 
648 	nag->ag_dst_h = dst;
649 	nag->ag_mask = mask;
650 	nag->ag_ifp = ifp;
651 	nag->ag_gate = gate;
652 	nag->ag_nhop = nhop;
653 	nag->ag_metric = metric;
654 	nag->ag_pref = pref;
655 	nag->ag_tag = tag;
656 	nag->ag_state = state;
657 	nag->ag_seqno = seqno;
658 
659 	nag->ag_fine = ag;
660 	if (ag != NULL)
661 		ag->ag_cors = nag;
662 	else
663 		ag_finest = nag;
664 	nag->ag_cors = ag_cors;
665 	if (ag_cors == NULL)
666 		ag_corsest = nag;
667 	else
668 		ag_cors->ag_fine = nag;
669 	CHECK_AG();
670 }
671 
672 
673 static const char *
674 rtm_type_name(uchar_t type)
675 {
676 	static const char *rtm_types[] = {
677 		"RTM_ADD",
678 		"RTM_DELETE",
679 		"RTM_CHANGE",
680 		"RTM_GET",
681 		"RTM_LOSING",
682 		"RTM_REDIRECT",
683 		"RTM_MISS",
684 		"RTM_LOCK",
685 		"RTM_OLDADD",
686 		"RTM_OLDDEL",
687 		"RTM_RESOLVE",
688 		"RTM_NEWADDR",
689 		"RTM_DELADDR",
690 		"RTM_IFINFO",
691 		"RTM_NEWMADDR",
692 		"RTM_DELMADDR"
693 	};
694 #define	NEW_RTM_PAT	"RTM type %#x"
695 	static char name0[sizeof (NEW_RTM_PAT) + 2];
696 
697 	if (type > sizeof (rtm_types) / sizeof (rtm_types[0]) || type == 0) {
698 		(void) snprintf(name0, sizeof (name0), NEW_RTM_PAT, type);
699 		return (name0);
700 	} else {
701 		return (rtm_types[type-1]);
702 	}
703 #undef	NEW_RTM_PAT
704 }
705 
706 
707 static void
708 dump_rt_msg(const char *act, struct rt_msghdr *rtm, int mlen)
709 {
710 	const char *mtype;
711 	uchar_t *cp;
712 	int i, j;
713 	char buffer[16*3 + 1], *ibs;
714 	struct ifa_msghdr *ifam;
715 	struct if_msghdr *ifm;
716 
717 	switch (rtm->rtm_type) {
718 	case RTM_NEWADDR:
719 	case RTM_DELADDR:
720 		mtype = "ifam";
721 		break;
722 	case RTM_IFINFO:
723 		mtype = "ifm";
724 		break;
725 	default:
726 		mtype = "rtm";
727 		break;
728 	}
729 	trace_misc("%s %s %d bytes", act, mtype, mlen);
730 	if (mlen > rtm->rtm_msglen) {
731 		trace_misc("%s: extra %d bytes ignored", mtype,
732 		    mlen - rtm->rtm_msglen);
733 		mlen = rtm->rtm_msglen;
734 	} else if (mlen < rtm->rtm_msglen) {
735 		trace_misc("%s: truncated by %d bytes", mtype,
736 		    rtm->rtm_msglen - mlen);
737 	}
738 	switch (rtm->rtm_type) {
739 	case RTM_NEWADDR:
740 	case RTM_DELADDR:
741 		ifam = (struct ifa_msghdr *)rtm;
742 		trace_misc("ifam: msglen %d version %d type %d addrs %X",
743 		    ifam->ifam_msglen, ifam->ifam_version, ifam->ifam_type,
744 		    ifam->ifam_addrs);
745 		trace_misc("ifam: flags %X index %d metric %d",
746 		    ifam->ifam_flags, ifam->ifam_index, ifam->ifam_metric);
747 		cp = (uchar_t *)(ifam + 1);
748 		break;
749 	case RTM_IFINFO:
750 		ifm = (struct if_msghdr *)rtm;
751 		trace_misc("ifm: msglen %d version %d type %d addrs %X",
752 		    ifm->ifm_msglen, ifm->ifm_version, ifm->ifm_type,
753 		    ifm->ifm_addrs);
754 		ibs = if_bit_string(ifm->ifm_flags, _B_TRUE);
755 		if (ibs == NULL) {
756 			trace_misc("ifm: flags %#x index %d", ifm->ifm_flags,
757 			    ifm->ifm_index);
758 		} else {
759 			trace_misc("ifm: flags %s index %d", ibs,
760 			    ifm->ifm_index);
761 			free(ibs);
762 		}
763 		cp = (uchar_t *)(ifm + 1);
764 		break;
765 	default:
766 		trace_misc("rtm: msglen %d version %d type %d index %d",
767 		    rtm->rtm_msglen, rtm->rtm_version, rtm->rtm_type,
768 		    rtm->rtm_index);
769 		trace_misc("rtm: flags %X addrs %X pid %d seq %d",
770 		    rtm->rtm_flags, rtm->rtm_addrs, rtm->rtm_pid, rtm->rtm_seq);
771 		trace_misc("rtm: errno %d use %d inits %X", rtm->rtm_errno,
772 		    rtm->rtm_use, rtm->rtm_inits);
773 		cp = (uchar_t *)(rtm + 1);
774 		break;
775 	}
776 	i = mlen - (cp - (uint8_t *)rtm);
777 	while (i > 0) {
778 		buffer[0] = '\0';
779 		ibs = buffer;
780 		for (j = 0; j < 16 && i > 0; j++, i--)
781 			ibs += sprintf(ibs, " %02X", *cp++);
782 		trace_misc("addr%s", buffer);
783 	}
784 }
785 
786 /*
787  * Tell the kernel to add, delete or change a route
788  * Pass k_state from khash in for diagnostic info.
789  */
790 static void
791 rtioctl(int action,			/* RTM_DELETE, etc */
792     in_addr_t dst,
793     in_addr_t gate,
794     in_addr_t mask,
795     struct interface *ifp,
796     uint8_t metric,
797     int flags)
798 {
799 	static int rt_sock_seqno = 0;
800 	struct {
801 		struct rt_msghdr w_rtm;
802 		struct sockaddr_in w_dst;
803 		struct sockaddr_in w_gate;
804 		uint8_t w_space[512];
805 	} w;
806 	struct sockaddr_in w_mask;
807 	struct sockaddr_dl w_ifp;
808 	uint8_t *cp;
809 	long cc;
810 #define	PAT " %-10s %s metric=%d flags=%#x"
811 #define	ARGS rtm_type_name(action), rtname(dst, mask, gate), metric, flags
812 
813 again:
814 	(void) memset(&w, 0, sizeof (w));
815 	(void) memset(&w_mask, 0, sizeof (w_mask));
816 	(void) memset(&w_ifp, 0, sizeof (w_ifp));
817 	cp = w.w_space;
818 	w.w_rtm.rtm_msglen = sizeof (struct rt_msghdr) +
819 	    2 * ROUNDUP_LONG(sizeof (struct sockaddr_in));
820 	w.w_rtm.rtm_version = RTM_VERSION;
821 	w.w_rtm.rtm_type = action;
822 	w.w_rtm.rtm_flags = flags;
823 	w.w_rtm.rtm_seq = ++rt_sock_seqno;
824 	w.w_rtm.rtm_addrs = RTA_DST|RTA_GATEWAY;
825 	if (metric != 0 || action == RTM_CHANGE) {
826 		w.w_rtm.rtm_rmx.rmx_hopcount = metric;
827 		w.w_rtm.rtm_inits |= RTV_HOPCOUNT;
828 	}
829 	w.w_dst.sin_family = AF_INET;
830 	w.w_dst.sin_addr.s_addr = dst;
831 	w.w_gate.sin_family = AF_INET;
832 	w.w_gate.sin_addr.s_addr = gate;
833 	if (mask == HOST_MASK) {
834 		w.w_rtm.rtm_flags |= RTF_HOST;
835 	} else {
836 		w.w_rtm.rtm_addrs |= RTA_NETMASK;
837 		w_mask.sin_family = AF_INET;
838 		w_mask.sin_addr.s_addr = htonl(mask);
839 		(void) memmove(cp, &w_mask, sizeof (w_mask));
840 		cp += ROUNDUP_LONG(sizeof (struct sockaddr_in));
841 		w.w_rtm.rtm_msglen += ROUNDUP_LONG(sizeof (struct sockaddr_in));
842 	}
843 	if (ifp == NULL)
844 		ifp = iflookup(gate);
845 
846 	if ((ifp == NULL) || (ifp->int_phys == NULL)) {
847 		trace_misc("no ifp for" PAT, ARGS);
848 	} else {
849 		if (ifp->int_phys->phyi_index > UINT16_MAX) {
850 			trace_misc("ifindex %d is too big for sdl_index",
851 			    ifp->int_phys->phyi_index);
852 		} else {
853 			w_ifp.sdl_family = AF_LINK;
854 			w.w_rtm.rtm_addrs |= RTA_IFP;
855 			w_ifp.sdl_index = ifp->int_phys->phyi_index;
856 			(void) memmove(cp, &w_ifp, sizeof (w_ifp));
857 			w.w_rtm.rtm_msglen +=
858 			    ROUNDUP_LONG(sizeof (struct sockaddr_dl));
859 		}
860 	}
861 
862 
863 	if (!no_install) {
864 		if (TRACERTS)
865 			dump_rt_msg("write", &w.w_rtm, w.w_rtm.rtm_msglen);
866 		cc = write(rt_sock, &w, w.w_rtm.rtm_msglen);
867 		if (cc < 0) {
868 			if (errno == ESRCH && (action == RTM_CHANGE ||
869 			    action == RTM_DELETE)) {
870 				trace_act("route disappeared before" PAT, ARGS);
871 				if (action == RTM_CHANGE) {
872 					action = RTM_ADD;
873 					goto again;
874 				}
875 				return;
876 			}
877 			writelog(LOG_WARNING, "write(rt_sock)" PAT ": %s ",
878 			    ARGS, rip_strerror(errno));
879 			return;
880 		} else if (cc != w.w_rtm.rtm_msglen) {
881 			msglog("write(rt_sock) wrote %ld instead of %d for" PAT,
882 			    cc, w.w_rtm.rtm_msglen, ARGS);
883 			return;
884 		}
885 	}
886 	if (TRACEKERNEL)
887 		trace_misc("write kernel" PAT, ARGS);
888 #undef PAT
889 #undef ARGS
890 }
891 
892 
893 /* Hash table containing our image of the kernel forwarding table. */
894 #define	KHASH_SIZE 71			/* should be prime */
895 #define	KHASH(a, m) khash_bins[((a) ^ (m)) % KHASH_SIZE]
896 static struct khash *khash_bins[KHASH_SIZE];
897 
898 #define	K_KEEP_LIM	30	/* k_keep */
899 
900 static struct khash *
901 kern_find(in_addr_t dst, in_addr_t mask, in_addr_t gate,
902     struct interface *ifp, struct khash ***ppk)
903 {
904 	struct khash *k, **pk;
905 
906 	if (ifp != NULL && ifp->int_phys != NULL) {
907 		ifp = ifwithname(ifp->int_phys->phyi_name);
908 	}
909 
910 	for (pk = &KHASH(dst, mask); (k = *pk) != NULL; pk = &k->k_next) {
911 		if (k->k_dst == dst && k->k_mask == mask &&
912 		    (gate == 0 || k->k_gate == gate) &&
913 		    (ifp == NULL || k->k_ifp == ifp)) {
914 			break;
915 		}
916 	}
917 	if (ppk != NULL)
918 		*ppk = pk;
919 	return (k);
920 }
921 
922 
923 /*
924  * Find out if there is an alternate route to a given destination
925  * off of a given interface.
926  */
927 static struct khash *
928 kern_alternate(in_addr_t dst, in_addr_t mask, in_addr_t gate,
929     struct interface *ifp, struct khash ***ppk)
930 {
931 	struct khash *k, **pk;
932 
933 	if (ifp != NULL && ifp->int_phys != NULL) {
934 		ifp = ifwithname(ifp->int_phys->phyi_name);
935 	}
936 	for (pk = &KHASH(dst, mask); (k = *pk) != NULL; pk = &k->k_next) {
937 		if (k->k_dst == dst && k->k_mask == mask &&
938 		    (k->k_gate != gate) &&
939 		    (k->k_ifp == ifp)) {
940 			break;
941 		}
942 	}
943 	if (ppk != NULL)
944 		*ppk = pk;
945 	return (k);
946 }
947 
948 static struct khash *
949 kern_add(in_addr_t dst, uint32_t mask, in_addr_t gate, struct interface *ifp)
950 {
951 	struct khash *k, **pk;
952 
953 	if (ifp != NULL && ifp->int_phys != NULL) {
954 		ifp = ifwithname(ifp->int_phys->phyi_name);
955 	}
956 	k = kern_find(dst, mask, gate, ifp, &pk);
957 	if (k != NULL)
958 		return (k);
959 
960 	k = rtmalloc(sizeof (*k), "kern_add");
961 
962 	(void) memset(k, 0, sizeof (*k));
963 	k->k_dst = dst;
964 	k->k_mask = mask;
965 	k->k_state = KS_NEW;
966 	k->k_keep = now.tv_sec;
967 	k->k_gate = gate;
968 	k->k_ifp = ifp;
969 	*pk = k;
970 
971 	return (k);
972 }
973 
974 /* delete all khash entries that are wired through the interface ifp */
975 void
976 kern_flush_ifp(struct interface *ifp)
977 {
978 	struct khash *k, *kprev, *knext;
979 	int i;
980 
981 	if (ifp != NULL && ifp->int_phys != NULL) {
982 		ifp = ifwithname(ifp->int_phys->phyi_name);
983 	}
984 	for (i = 0; i < KHASH_SIZE; i++) {
985 		kprev = NULL;
986 		for (k = khash_bins[i]; k != NULL; k = knext) {
987 			knext = k->k_next;
988 			if (k->k_ifp == ifp) {
989 				if (kprev != NULL)
990 					kprev->k_next = k->k_next;
991 				else
992 					khash_bins[i] = k->k_next;
993 				free(k);
994 				continue;
995 			}
996 			kprev = k;
997 		}
998 	}
999 }
1000 
1001 /*
1002  * rewire khash entries that currently go through oldifp to
1003  * go through newifp.
1004  */
1005 void
1006 kern_rewire_ifp(struct interface *oldifp, struct interface *newifp)
1007 {
1008 	struct khash *k;
1009 	int i;
1010 
1011 	if (oldifp != NULL && oldifp->int_phys != NULL) {
1012 		oldifp = ifwithname(oldifp->int_phys->phyi_name);
1013 	}
1014 	if (newifp != NULL && newifp->int_phys != NULL) {
1015 		newifp = ifwithname(newifp->int_phys->phyi_name);
1016 	}
1017 	for (i = 0; i < KHASH_SIZE; i++) {
1018 		for (k = khash_bins[i]; k; k = k->k_next) {
1019 			if (k->k_ifp == oldifp) {
1020 				k->k_ifp = newifp;
1021 				trace_misc("kern_rewire_ifp k 0x%lx "
1022 				    "from %s to %s", k, oldifp->int_name,
1023 				    newifp->int_name);
1024 			}
1025 		}
1026 	}
1027 }
1028 
1029 
1030 /*
1031  * Check that a static route it is still in the daemon table, and not
1032  * deleted by interfaces coming and going.  This is also the routine
1033  * responsible for adding new static routes to the daemon table.
1034  */
1035 static void
1036 kern_check_static(struct khash *k, struct interface *ifp)
1037 {
1038 	struct rt_entry *rt;
1039 	struct rt_spare new;
1040 	uint16_t rt_state = RS_STATIC;
1041 
1042 	if (ifp != NULL && ifp->int_phys != NULL) {
1043 		ifp = ifwithname(ifp->int_phys->phyi_name);
1044 	}
1045 	(void) memset(&new, 0, sizeof (new));
1046 	new.rts_ifp = ifp;
1047 	new.rts_gate = k->k_gate;
1048 	new.rts_router = (ifp != NULL) ? ifp->int_addr : loopaddr;
1049 	new.rts_metric = k->k_metric;
1050 	new.rts_time = now.tv_sec;
1051 	new.rts_origin = RO_STATIC;
1052 
1053 	rt = rtget(k->k_dst, k->k_mask);
1054 	if ((ifp != NULL && !IS_IFF_ROUTING(ifp->int_if_flags)) ||
1055 	    (k->k_state & KS_PRIVATE))
1056 		rt_state |= RS_NOPROPAGATE;
1057 
1058 	if (rt != NULL) {
1059 		if ((rt->rt_state & RS_STATIC) == 0) {
1060 			/*
1061 			 * We are already tracking this dest/mask
1062 			 * via RIP/RDISC. Ignore the static route,
1063 			 * because we don't currently have a good
1064 			 * way to compare metrics on static routes
1065 			 * with rip metrics, and therefore cannot
1066 			 * mix and match the two.
1067 			 */
1068 			return;
1069 		}
1070 		rt_state |= rt->rt_state;
1071 		if (rt->rt_state != rt_state)
1072 			rtchange(rt, rt_state, &new, 0);
1073 	} else {
1074 		rtadd(k->k_dst, k->k_mask, rt_state, &new);
1075 	}
1076 }
1077 
1078 
1079 /* operate on a kernel entry */
1080 static void
1081 kern_ioctl(struct khash *k,
1082     int action,			/* RTM_DELETE, etc */
1083     int flags)
1084 {
1085 	if (((k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF) ||
1086 	    (k->k_state & KS_DEPRE_IF)) {
1087 		/*
1088 		 * Prevent execution of RTM_DELETE, RTM_ADD or
1089 		 * RTM_CHANGE of interface routes
1090 		 */
1091 		trace_act("Blocking execution of %s  %s --> %s ",
1092 		    rtm_type_name(action),
1093 		    addrname(k->k_dst, k->k_mask, 0), naddr_ntoa(k->k_gate));
1094 		return;
1095 	}
1096 
1097 	switch (action) {
1098 	case RTM_DELETE:
1099 		k->k_state &= ~KS_DYNAMIC;
1100 		if (k->k_state & KS_DELETED)
1101 			return;
1102 		k->k_state |= KS_DELETED;
1103 		break;
1104 	case RTM_ADD:
1105 		k->k_state &= ~KS_DELETED;
1106 		break;
1107 	case RTM_CHANGE:
1108 		if (k->k_state & KS_DELETED) {
1109 			action = RTM_ADD;
1110 			k->k_state &= ~KS_DELETED;
1111 		}
1112 		break;
1113 	}
1114 
1115 	rtioctl(action, k->k_dst, k->k_gate, k->k_mask, k->k_ifp,
1116 	    k->k_metric, flags);
1117 }
1118 
1119 
1120 /* add a route the kernel told us */
1121 static void
1122 rtm_add(struct rt_msghdr *rtm,
1123     struct rt_addrinfo *info,
1124     time_t keep,
1125     boolean_t interf_route,
1126     struct interface *ifptr)
1127 {
1128 	struct khash *k;
1129 	struct interface *ifp = ifptr;
1130 	in_addr_t mask, gate = 0;
1131 	static struct msg_limit msg_no_ifp;
1132 
1133 	if (rtm->rtm_flags & RTF_HOST) {
1134 		mask = HOST_MASK;
1135 	} else if (INFO_MASK(info) != 0) {
1136 		mask = ntohl(S_ADDR(INFO_MASK(info)));
1137 	} else {
1138 		writelog(LOG_WARNING,
1139 		    "ignore %s without mask", rtm_type_name(rtm->rtm_type));
1140 		return;
1141 	}
1142 
1143 	/*
1144 	 * Find the interface toward the gateway.
1145 	 */
1146 	if (INFO_GATE(info) != NULL)
1147 		gate = S_ADDR(INFO_GATE(info));
1148 
1149 	if (ifp == NULL) {
1150 		if (INFO_GATE(info) != NULL)
1151 			ifp = iflookup(gate);
1152 		if (ifp == NULL) {
1153 			msglim(&msg_no_ifp, gate,
1154 			    "route %s --> %s nexthop is not directly connected",
1155 			    addrname(S_ADDR(INFO_DST(info)), mask, 0),
1156 			    naddr_ntoa(gate));
1157 		} else {
1158 			if (ifp->int_phys != NULL) {
1159 				ifp = ifwithname(ifp->int_phys->phyi_name);
1160 			}
1161 		}
1162 	}
1163 
1164 	k = kern_add(S_ADDR(INFO_DST(info)), mask, gate, ifp);
1165 
1166 	if (k->k_state & KS_NEW)
1167 		k->k_keep = now.tv_sec+keep;
1168 	if (INFO_GATE(info) == 0) {
1169 		trace_act("note %s without gateway",
1170 		    rtm_type_name(rtm->rtm_type));
1171 		k->k_metric = HOPCNT_INFINITY;
1172 	} else if (INFO_GATE(info)->ss_family != AF_INET) {
1173 		trace_act("note %s with gateway AF=%d",
1174 		    rtm_type_name(rtm->rtm_type),
1175 		    INFO_GATE(info)->ss_family);
1176 		k->k_metric = HOPCNT_INFINITY;
1177 	} else {
1178 		k->k_gate = S_ADDR(INFO_GATE(info));
1179 		k->k_metric = rtm->rtm_rmx.rmx_hopcount;
1180 		if (k->k_metric < 0)
1181 			k->k_metric = 0;
1182 		else if (k->k_metric > HOPCNT_INFINITY-1)
1183 			k->k_metric = HOPCNT_INFINITY-1;
1184 	}
1185 
1186 	if ((k->k_state & KS_NEW) && interf_route) {
1187 		if (k->k_gate != 0 && findifaddr(k->k_gate) == NULL)
1188 			k->k_state |= KS_DEPRE_IF;
1189 		else
1190 			k->k_state |= KS_IF;
1191 	}
1192 
1193 	k->k_state &= ~(KS_NEW | KS_DELETE | KS_ADD | KS_CHANGE | KS_DEL_ADD |
1194 	    KS_STATIC | KS_GATEWAY | KS_DELETED | KS_PRIVATE | KS_CHECK);
1195 	if (rtm->rtm_flags & RTF_GATEWAY)
1196 		k->k_state |= KS_GATEWAY;
1197 	if (rtm->rtm_flags & RTF_STATIC)
1198 		k->k_state |= KS_STATIC;
1199 	if (rtm->rtm_flags & RTF_PRIVATE)
1200 		k->k_state |= KS_PRIVATE;
1201 
1202 
1203 	if (rtm->rtm_flags & (RTF_DYNAMIC | RTF_MODIFIED)) {
1204 		if (INFO_AUTHOR(info) != 0 &&
1205 		    INFO_AUTHOR(info)->ss_family == AF_INET)
1206 			ifp = iflookup(S_ADDR(INFO_AUTHOR(info)));
1207 		else
1208 			ifp = NULL;
1209 		if (should_supply(ifp) && (ifp == NULL ||
1210 		    !(ifp->int_state & IS_REDIRECT_OK))) {
1211 			/*
1212 			 * Routers are not supposed to listen to redirects,
1213 			 * so delete it if it came via an unknown interface
1214 			 * or the interface does not have special permission.
1215 			 */
1216 			k->k_state &= ~KS_DYNAMIC;
1217 			k->k_state |= KS_DELETE;
1218 			LIM_SEC(need_kern, 0);
1219 			trace_act("mark for deletion redirected %s --> %s"
1220 			    " via %s",
1221 			    addrname(k->k_dst, k->k_mask, 0),
1222 			    naddr_ntoa(k->k_gate),
1223 			    ifp ? ifp->int_name : "unknown interface");
1224 		} else {
1225 			k->k_state |= KS_DYNAMIC;
1226 			k->k_redirect_time = now.tv_sec;
1227 			trace_act("accept redirected %s --> %s via %s",
1228 			    addrname(k->k_dst, k->k_mask, 0),
1229 			    naddr_ntoa(k->k_gate),
1230 			    ifp ? ifp->int_name : "unknown interface");
1231 		}
1232 		return;
1233 	}
1234 
1235 	/*
1236 	 * If it is not a static route, quit until the next comparison
1237 	 * between the kernel and daemon tables, when it will be deleted.
1238 	 */
1239 	if (!(k->k_state & KS_STATIC)) {
1240 		if (!(k->k_state & (KS_IF|KS_DEPRE_IF|KS_FILE)))
1241 			k->k_state |= KS_DELETE;
1242 		LIM_SEC(need_kern, k->k_keep);
1243 		return;
1244 	}
1245 
1246 	/*
1247 	 * Put static routes with real metrics into the daemon table so
1248 	 * they can be advertised.
1249 	 */
1250 
1251 	kern_check_static(k, ifp);
1252 }
1253 
1254 
1255 /* deal with packet loss */
1256 static void
1257 rtm_lose(struct rt_msghdr *rtm, struct rt_addrinfo *info)
1258 {
1259 	if (INFO_GATE(info) == NULL || INFO_GATE(info)->ss_family != AF_INET) {
1260 		trace_act("ignore %s without gateway",
1261 		    rtm_type_name(rtm->rtm_type));
1262 		age(0);
1263 		return;
1264 	}
1265 
1266 	if (rdisc_ok)
1267 		rdisc_age(S_ADDR(INFO_GATE(info)));
1268 	age(S_ADDR(INFO_GATE(info)));
1269 }
1270 
1271 
1272 /*
1273  * Make the gateway slot of an info structure point to something
1274  * useful.  If it is not already useful, but it specifies an interface,
1275  * then fill in the sockaddr_in provided and point it there.
1276  */
1277 static int
1278 get_info_gate(struct sockaddr_storage **ssp, struct sockaddr_in *sin)
1279 {
1280 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)*ssp;
1281 	struct interface *ifp;
1282 
1283 	if (sdl == NULL)
1284 		return (0);
1285 	if ((sdl)->sdl_family == AF_INET)
1286 		return (1);
1287 	if ((sdl)->sdl_family != AF_LINK)
1288 		return (0);
1289 
1290 	ifp = ifwithindex(sdl->sdl_index, _B_TRUE);
1291 	if (ifp == NULL)
1292 		return (0);
1293 
1294 	sin->sin_addr.s_addr = ifp->int_addr;
1295 	sin->sin_family = AF_INET;
1296 	/* LINTED */
1297 	*ssp = (struct sockaddr_storage *)sin;
1298 
1299 	return (1);
1300 }
1301 
1302 
1303 /*
1304  * Clean the kernel table by copying it to the daemon image.
1305  * Eventually the daemon will delete any extra routes.
1306  */
1307 void
1308 sync_kern(void)
1309 {
1310 	int i;
1311 	struct khash *k;
1312 	struct {
1313 		struct T_optmgmt_req req;
1314 		struct opthdr hdr;
1315 	} req;
1316 	union {
1317 		struct T_optmgmt_ack ack;
1318 		unsigned char space[64];
1319 	} ack;
1320 	struct opthdr *rh;
1321 	struct strbuf cbuf, dbuf;
1322 	int ipfd, nroutes, flags, r;
1323 	mib2_ipRouteEntry_t routes[8];
1324 	mib2_ipRouteEntry_t *rp;
1325 	struct rt_msghdr rtm;
1326 	struct rt_addrinfo info;
1327 	struct sockaddr_in sin_dst;
1328 	struct sockaddr_in sin_gate;
1329 	struct sockaddr_in sin_mask;
1330 	struct sockaddr_in sin_author;
1331 	struct interface *ifp;
1332 	char ifname[LIFNAMSIZ + 1];
1333 
1334 	for (i = 0; i < KHASH_SIZE; i++) {
1335 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
1336 			if (!(k->k_state & (KS_IF|KS_DEPRE_IF)))
1337 				k->k_state |= KS_CHECK;
1338 		}
1339 	}
1340 
1341 	ipfd = open(IP_DEV_NAME, O_RDWR);
1342 	if (ipfd == -1) {
1343 		msglog("open " IP_DEV_NAME ": %s", rip_strerror(errno));
1344 		goto hash_clean;
1345 	}
1346 
1347 	req.req.PRIM_type = T_OPTMGMT_REQ;
1348 	req.req.OPT_offset = (caddr_t)&req.hdr - (caddr_t)&req;
1349 	req.req.OPT_length = sizeof (req.hdr);
1350 	req.req.MGMT_flags = T_CURRENT;
1351 
1352 	req.hdr.level = MIB2_IP;
1353 	req.hdr.name = 0;
1354 	req.hdr.len = 0;
1355 
1356 	cbuf.buf = (caddr_t)&req;
1357 	cbuf.len = sizeof (req);
1358 
1359 	if (putmsg(ipfd, &cbuf, NULL, 0) == -1) {
1360 		msglog("T_OPTMGMT_REQ putmsg: %s", rip_strerror(errno));
1361 		goto hash_clean;
1362 	}
1363 
1364 	for (;;) {
1365 		cbuf.buf = (caddr_t)&ack;
1366 		cbuf.maxlen = sizeof (ack);
1367 		dbuf.buf = (caddr_t)routes;
1368 		dbuf.maxlen = sizeof (routes);
1369 		flags = 0;
1370 		r = getmsg(ipfd, &cbuf, &dbuf, &flags);
1371 		if (r == -1) {
1372 			msglog("T_OPTMGMT_REQ getmsg: %s", rip_strerror(errno));
1373 			goto hash_clean;
1374 		}
1375 
1376 		if (cbuf.len < sizeof (struct T_optmgmt_ack) ||
1377 		    ack.ack.PRIM_type != T_OPTMGMT_ACK ||
1378 		    ack.ack.MGMT_flags != T_SUCCESS ||
1379 		    ack.ack.OPT_length < sizeof (struct opthdr)) {
1380 			msglog("bad T_OPTMGMT response; len=%d prim=%d "
1381 			    "flags=%d optlen=%d", cbuf.len, ack.ack.PRIM_type,
1382 			    ack.ack.MGMT_flags, ack.ack.OPT_length);
1383 			goto hash_clean;
1384 		}
1385 		/* LINTED */
1386 		rh = (struct opthdr *)((caddr_t)&ack + ack.ack.OPT_offset);
1387 		if (rh->level == 0 && rh->name == 0) {
1388 			break;
1389 		}
1390 		if (rh->level != MIB2_IP || rh->name != MIB2_IP_21) {
1391 			while (r == MOREDATA) {
1392 				r = getmsg(ipfd, NULL, &dbuf, &flags);
1393 			}
1394 			continue;
1395 		}
1396 		break;
1397 	}
1398 
1399 	(void) memset(&rtm, 0, sizeof (rtm));
1400 	(void) memset(&info, 0, sizeof (info));
1401 	(void) memset(&sin_dst, 0, sizeof (sin_dst));
1402 	(void) memset(&sin_gate, 0, sizeof (sin_gate));
1403 	(void) memset(&sin_mask, 0, sizeof (sin_mask));
1404 	(void) memset(&sin_author, 0, sizeof (sin_author));
1405 	sin_dst.sin_family = AF_INET;
1406 	/* LINTED */
1407 	info.rti_info[RTAX_DST] = (struct sockaddr_storage *)&sin_dst;
1408 	sin_gate.sin_family = AF_INET;
1409 	/* LINTED */
1410 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr_storage *)&sin_gate;
1411 	sin_mask.sin_family = AF_INET;
1412 	/* LINTED */
1413 	info.rti_info[RTAX_NETMASK] = (struct sockaddr_storage *)&sin_mask;
1414 	sin_dst.sin_family = AF_INET;
1415 	/* LINTED */
1416 	info.rti_info[RTAX_AUTHOR] = (struct sockaddr_storage *)&sin_author;
1417 
1418 	for (;;) {
1419 		nroutes = dbuf.len / sizeof (mib2_ipRouteEntry_t);
1420 		for (rp = routes; nroutes > 0; ++rp, nroutes--) {
1421 
1422 			/*
1423 			 * Ignore IRE cache, broadcast, and local address
1424 			 * entries; they're not subject to routing socket
1425 			 * control.
1426 			 */
1427 			if (rp->ipRouteInfo.re_ire_type &
1428 			    (IRE_BROADCAST | IRE_CACHE | IRE_LOCAL))
1429 				continue;
1430 
1431 			/* ignore multicast addresses */
1432 			if (IN_MULTICAST(ntohl(rp->ipRouteDest)))
1433 				continue;
1434 
1435 
1436 #ifdef DEBUG_KERNEL_ROUTE_READ
1437 			(void) fprintf(stderr, "route type %d, ire type %08X, "
1438 			    "flags %08X: %s", rp->ipRouteType,
1439 			    rp->ipRouteInfo.re_ire_type,
1440 			    rp->ipRouteInfo.re_flags,
1441 			    naddr_ntoa(rp->ipRouteDest));
1442 			(void) fprintf(stderr, " %s",
1443 			    naddr_ntoa(rp->ipRouteMask));
1444 			(void) fprintf(stderr, " %s\n",
1445 			    naddr_ntoa(rp->ipRouteNextHop));
1446 #endif
1447 
1448 			/* Fake up the needed entries */
1449 			rtm.rtm_flags = rp->ipRouteInfo.re_flags;
1450 			rtm.rtm_type = RTM_GET;
1451 			rtm.rtm_rmx.rmx_hopcount = rp->ipRouteMetric1;
1452 
1453 			(void) memset(ifname, 0, sizeof (ifname));
1454 			if (rp->ipRouteIfIndex.o_length <
1455 			    sizeof (rp->ipRouteIfIndex.o_bytes))
1456 				rp->ipRouteIfIndex.o_bytes[
1457 				    rp->ipRouteIfIndex.o_length] = '\0';
1458 				(void) strncpy(ifname,
1459 				    rp->ipRouteIfIndex.o_bytes,
1460 				    sizeof (ifname));
1461 
1462 			/*
1463 			 * First try to match up on gwkludge entries
1464 			 * before trying to match ifp by name.
1465 			 */
1466 			if ((ifp = gwkludge_iflookup(rp->ipRouteDest,
1467 			    rp->ipRouteNextHop,
1468 			    ntohl(rp->ipRouteMask))) == NULL) {
1469 				ifp = ifwithname(ifname);
1470 				if (ifp != NULL && ifp->int_phys != NULL) {
1471 					ifp = ifwithname(
1472 					    ifp->int_phys->phyi_name);
1473 				}
1474 			}
1475 
1476 			info.rti_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
1477 			if (rp->ipRouteInfo.re_ire_type & IRE_HOST_REDIRECT)
1478 				info.rti_addrs |= RTA_AUTHOR;
1479 			sin_dst.sin_addr.s_addr = rp->ipRouteDest;
1480 			sin_gate.sin_addr.s_addr = rp->ipRouteNextHop;
1481 			sin_mask.sin_addr.s_addr = rp->ipRouteMask;
1482 			sin_author.sin_addr.s_addr =
1483 			    rp->ipRouteInfo.re_src_addr;
1484 
1485 			/*
1486 			 * Note static routes and interface routes, and also
1487 			 * preload the image of the kernel table so that
1488 			 * we can later clean it, as well as avoid making
1489 			 * unneeded changes.  Keep the old kernel routes for a
1490 			 * few seconds to allow a RIP or router-discovery
1491 			 * response to be heard.
1492 			 */
1493 			rtm_add(&rtm, &info, MAX_WAITTIME,
1494 			    ((rp->ipRouteInfo.re_ire_type &
1495 			    (IRE_INTERFACE|IRE_LOOPBACK)) != 0), ifp);
1496 		}
1497 		if (r == 0) {
1498 			break;
1499 		}
1500 		r = getmsg(ipfd, NULL, &dbuf, &flags);
1501 	}
1502 
1503 hash_clean:
1504 	if (ipfd != -1)
1505 		(void) close(ipfd);
1506 	for (i = 0; i < KHASH_SIZE; i++) {
1507 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
1508 
1509 			/*
1510 			 * KS_DELETED routes have been removed from the
1511 			 * kernel, but we keep them around for reasons
1512 			 * stated in del_static(), so we skip the check
1513 			 * for KS_DELETED routes here.
1514 			 */
1515 			if ((k->k_state & (KS_CHECK|KS_DELETED)) == KS_CHECK) {
1516 
1517 				if (!(k->k_state & KS_DYNAMIC))
1518 				    writelog(LOG_WARNING,
1519 					"%s --> %s disappeared from kernel",
1520 					addrname(k->k_dst, k->k_mask, 0),
1521 					naddr_ntoa(k->k_gate));
1522 				del_static(k->k_dst, k->k_mask, k->k_gate,
1523 				    k->k_ifp, 1);
1524 
1525 			}
1526 		}
1527 	}
1528 }
1529 
1530 
1531 /* Listen to announcements from the kernel */
1532 void
1533 read_rt(void)
1534 {
1535 	long cc;
1536 	struct interface *ifp;
1537 	struct sockaddr_in gate_sin;
1538 	in_addr_t mask, gate;
1539 	union {
1540 		struct {
1541 			struct rt_msghdr rtm;
1542 			struct sockaddr_storage addrs[RTA_NUMBITS];
1543 		} r;
1544 		struct if_msghdr ifm;
1545 	} m;
1546 	char str[100], *strp;
1547 	struct rt_addrinfo info;
1548 
1549 
1550 	for (;;) {
1551 		cc = read(rt_sock, &m, sizeof (m));
1552 		if (cc <= 0) {
1553 			if (cc < 0 && errno != EWOULDBLOCK)
1554 				LOGERR("read(rt_sock)");
1555 			return;
1556 		}
1557 
1558 		if (TRACERTS)
1559 			dump_rt_msg("read", &m.r.rtm, cc);
1560 
1561 		if (cc < m.r.rtm.rtm_msglen) {
1562 			msglog("routing message truncated (%d < %d)",
1563 			    cc, m.r.rtm.rtm_msglen);
1564 		}
1565 
1566 		if (m.r.rtm.rtm_version != RTM_VERSION) {
1567 			msglog("bogus routing message version %d",
1568 			    m.r.rtm.rtm_version);
1569 			continue;
1570 		}
1571 
1572 		ifp = NULL;
1573 
1574 		if (m.r.rtm.rtm_type == RTM_IFINFO ||
1575 		    m.r.rtm.rtm_type == RTM_NEWADDR ||
1576 		    m.r.rtm.rtm_type == RTM_DELADDR) {
1577 			strp = if_bit_string(m.ifm.ifm_flags, _B_TRUE);
1578 			if (strp == NULL) {
1579 				strp = str;
1580 				(void) sprintf(str, "%#x", m.ifm.ifm_flags);
1581 			}
1582 			ifp = ifwithindex(m.ifm.ifm_index,
1583 			    m.r.rtm.rtm_type != RTM_DELADDR);
1584 			if (ifp == NULL) {
1585 				char ifname[LIFNAMSIZ], *ifnamep;
1586 
1587 				ifnamep = if_indextoname(m.ifm.ifm_index,
1588 				    ifname);
1589 				if (ifnamep == NULL) {
1590 					trace_act("note %s with flags %s"
1591 					    " for unknown interface index #%d",
1592 					    rtm_type_name(m.r.rtm.rtm_type),
1593 					    strp, m.ifm.ifm_index);
1594 				} else {
1595 					trace_act("note %s with flags %s"
1596 					    " for unknown interface %s",
1597 					    rtm_type_name(m.r.rtm.rtm_type),
1598 					    strp, ifnamep);
1599 				}
1600 			} else {
1601 				trace_act("note %s with flags %s for %s",
1602 				    rtm_type_name(m.r.rtm.rtm_type),
1603 				    strp, ifp->int_name);
1604 			}
1605 			if (strp != str)
1606 				free(strp);
1607 
1608 			/*
1609 			 * After being informed of a change to an interface,
1610 			 * check them all now if the check would otherwise
1611 			 * be a long time from now, if the interface is
1612 			 * not known, or if the interface has been turned
1613 			 * off or on.
1614 			 */
1615 			if (ifscan_timer.tv_sec-now.tv_sec >=
1616 			    CHECK_BAD_INTERVAL || ifp == NULL ||
1617 			    ((ifp->int_if_flags ^ m.ifm.ifm_flags) &
1618 				IFF_UP) != 0)
1619 				ifscan_timer.tv_sec = now.tv_sec;
1620 			continue;
1621 		} else {
1622 			if (m.r.rtm.rtm_index != 0)
1623 				ifp = ifwithindex(m.r.rtm.rtm_index, 1);
1624 		}
1625 
1626 		(void) strlcpy(str, rtm_type_name(m.r.rtm.rtm_type),
1627 		    sizeof (str));
1628 		strp = &str[strlen(str)];
1629 		if (m.r.rtm.rtm_type <= RTM_CHANGE)
1630 			strp += snprintf(strp, sizeof (str) - (strp - str),
1631 			    " from pid %d", (int)m.r.rtm.rtm_pid);
1632 
1633 		/* LINTED */
1634 		(void) rt_xaddrs(&info, (struct sockaddr_storage *)(&m.r.rtm +
1635 		    1), (char *)&m + cc, m.r.rtm.rtm_addrs);
1636 
1637 		if (INFO_DST(&info) == 0) {
1638 			trace_act("ignore %s without dst", str);
1639 			continue;
1640 		}
1641 
1642 		if (INFO_DST(&info)->ss_family != AF_INET) {
1643 			trace_act("ignore %s for AF %d", str,
1644 			    INFO_DST(&info)->ss_family);
1645 			continue;
1646 		}
1647 
1648 		mask = ((INFO_MASK(&info) != 0) ?
1649 		    ntohl(S_ADDR(INFO_MASK(&info))) :
1650 		    (m.r.rtm.rtm_flags & RTF_HOST) ?
1651 		    HOST_MASK : std_mask(S_ADDR(INFO_DST(&info))));
1652 
1653 		strp += snprintf(strp, sizeof (str) - (strp - str), ": %s",
1654 		    addrname(S_ADDR(INFO_DST(&info)), mask, 0));
1655 
1656 		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info))))) {
1657 			trace_act("ignore multicast %s", str);
1658 			continue;
1659 		}
1660 
1661 		if (m.r.rtm.rtm_flags & RTF_LLINFO) {
1662 			trace_act("ignore ARP %s", str);
1663 			continue;
1664 		}
1665 
1666 		if (get_info_gate(&INFO_GATE(&info), &gate_sin)) {
1667 			gate = S_ADDR(INFO_GATE(&info));
1668 			strp += snprintf(strp, sizeof (str) - (strp - str),
1669 			    " --> %s", naddr_ntoa(gate));
1670 		} else {
1671 			gate = 0;
1672 		}
1673 
1674 		if (INFO_AUTHOR(&info) != 0)
1675 			strp += snprintf(strp, sizeof (str) - (strp - str),
1676 			    " by authority of %s",
1677 			    saddr_ntoa(INFO_AUTHOR(&info)));
1678 
1679 		switch (m.r.rtm.rtm_type) {
1680 		case RTM_ADD:
1681 		case RTM_CHANGE:
1682 		case RTM_REDIRECT:
1683 			if (m.r.rtm.rtm_errno != 0) {
1684 				trace_act("ignore %s with \"%s\" error",
1685 				    str, rip_strerror(m.r.rtm.rtm_errno));
1686 			} else {
1687 				trace_act("%s", str);
1688 				rtm_add(&m.r.rtm, &info, 0,
1689 				    !(m.r.rtm.rtm_flags & RTF_GATEWAY) &&
1690 				    m.r.rtm.rtm_type != RTM_REDIRECT, ifp);
1691 
1692 			}
1693 			break;
1694 
1695 		case RTM_DELETE:
1696 			if (m.r.rtm.rtm_errno != 0 &&
1697 			    m.r.rtm.rtm_errno != ESRCH) {
1698 				trace_act("ignore %s with \"%s\" error",
1699 				    str, rip_strerror(m.r.rtm.rtm_errno));
1700 			} else {
1701 				trace_act("%s", str);
1702 				del_static(S_ADDR(INFO_DST(&info)), mask,
1703 				    gate, ifp, 1);
1704 			}
1705 			break;
1706 
1707 		case RTM_LOSING:
1708 			trace_act("%s", str);
1709 			rtm_lose(&m.r.rtm, &info);
1710 			break;
1711 
1712 		default:
1713 			trace_act("ignore %s", str);
1714 			break;
1715 		}
1716 	}
1717 }
1718 
1719 
1720 /*
1721  * Disassemble a routing message.  The result is an array of pointers
1722  * to sockaddr_storage structures stored in the info argument.
1723  *
1724  * ss is a pointer to the beginning of the data following the
1725  * rt_msghdr contained in the routing socket message, which consists
1726  * of a string of concatenated sockaddr structure of different types.
1727  *
1728  * Extended attributes can be appended at the end of the list.
1729  */
1730 static int
1731 rt_xaddrs(struct rt_addrinfo *info,
1732     struct sockaddr_storage *ss,
1733     char *lim,
1734     int addrs)
1735 {
1736 	int retv = 0;
1737 	int i;
1738 	int abit;
1739 	int complaints;
1740 	static int prev_complaints;
1741 
1742 #define	XBAD_AF		0x1
1743 #define	XBAD_SHORT	0x2
1744 #define	XBAD_LONG	0x4
1745 
1746 	(void) memset(info, 0, sizeof (*info));
1747 	info->rti_addrs = addrs;
1748 	complaints = 0;
1749 	for (i = 0, abit = 1; i < RTAX_MAX && (char *)ss < lim;
1750 	    i++, abit <<= 1) {
1751 		if ((addrs & abit) == 0)
1752 			continue;
1753 		info->rti_info[i] = ss;
1754 		/* Horrible interface here */
1755 		switch (ss->ss_family) {
1756 		case AF_UNIX:
1757 			/* LINTED */
1758 			ss = (struct sockaddr_storage *)(
1759 			    (struct sockaddr_un *)ss + 1);
1760 			break;
1761 		case AF_INET:
1762 			/* LINTED */
1763 			ss = (struct sockaddr_storage *)(
1764 			    (struct sockaddr_in *)ss + 1);
1765 			break;
1766 		case AF_LINK:
1767 			/* LINTED */
1768 			ss = (struct sockaddr_storage *)(
1769 			    (struct sockaddr_dl *)ss + 1);
1770 			break;
1771 		case AF_INET6:
1772 			/* LINTED */
1773 			ss = (struct sockaddr_storage *)(
1774 			    (struct sockaddr_in6 *)ss + 1);
1775 			break;
1776 		default:
1777 			if (!(prev_complaints & XBAD_AF))
1778 				writelog(LOG_WARNING,
1779 				    "unknown address family %d "
1780 				    "encountered", ss->ss_family);
1781 			if (complaints & XBAD_AF)
1782 				goto xaddr_done;
1783 			/* LINTED */
1784 			ss = (struct sockaddr_storage *)(
1785 			    (struct sockaddr *)ss + 1);
1786 			complaints |= XBAD_AF;
1787 			info->rti_addrs &= abit - 1;
1788 			addrs = info->rti_addrs;
1789 			retv = -1;
1790 			break;
1791 		}
1792 		if ((char *)ss > lim) {
1793 			if (!(prev_complaints & XBAD_SHORT))
1794 				msglog("sockaddr %d too short by %d "
1795 				    "bytes", i + 1, (char *)ss - lim);
1796 			complaints |= XBAD_SHORT;
1797 			info->rti_info[i] = NULL;
1798 			info->rti_addrs &= abit - 1;
1799 			retv = -1;
1800 			goto xaddr_done;
1801 		}
1802 	}
1803 
1804 	while (((char *)ss + sizeof (rtm_ext_t)) <= lim) {
1805 		rtm_ext_t *tp;
1806 		char *nxt;
1807 
1808 		/* LINTED: alignment */
1809 		tp = (rtm_ext_t *)ss;
1810 		nxt = (char *)(tp + 1) + tp->rtmex_len;
1811 
1812 		if (!IS_P2ALIGNED(tp->rtmex_len, sizeof (uint32_t)) ||
1813 		    nxt > lim) {
1814 			break;
1815 		}
1816 
1817 		/* LINTED: alignment */
1818 		ss = (struct sockaddr_storage *)nxt;
1819 	}
1820 
1821 	if ((char *)ss != lim) {
1822 		if ((char *)ss > lim) {
1823 			if (!(prev_complaints & XBAD_SHORT))
1824 				msglog("routing message too short by %d bytes",
1825 				    (char *)ss - lim);
1826 			complaints |= XBAD_SHORT;
1827 		} else if (!(prev_complaints & XBAD_LONG)) {
1828 			msglog("%d bytes of routing message left over",
1829 			    lim - (char *)ss);
1830 			complaints |= XBAD_LONG;
1831 		}
1832 		retv = -1;
1833 	}
1834 xaddr_done:
1835 	prev_complaints = complaints;
1836 	return (retv);
1837 }
1838 
1839 
1840 /* after aggregating, note routes that belong in the kernel */
1841 static void
1842 kern_out(struct ag_info *ag)
1843 {
1844 	struct khash *k;
1845 	struct interface *ifp;
1846 
1847 	ifp = ag->ag_ifp;
1848 
1849 	if (ifp != NULL && ifp->int_phys != NULL) {
1850 		ifp = ifwithname(ifp->int_phys->phyi_name);
1851 	}
1852 
1853 	/*
1854 	 * Do not install bad routes if they are not already present.
1855 	 * This includes routes that had RS_NET_SYN for interfaces that
1856 	 * recently died.
1857 	 */
1858 	if (ag->ag_metric == HOPCNT_INFINITY) {
1859 		k = kern_find(htonl(ag->ag_dst_h), ag->ag_mask,
1860 		    ag->ag_nhop, ag->ag_ifp, NULL);
1861 		if (k == NULL)
1862 			return;
1863 	} else {
1864 		k = kern_add(htonl(ag->ag_dst_h), ag->ag_mask, ag->ag_nhop,
1865 		    ifp);
1866 	}
1867 
1868 	if (k->k_state & KS_NEW) {
1869 		/* will need to add new entry to the kernel table */
1870 		k->k_state = KS_ADD;
1871 		if (ag->ag_state & AGS_GATEWAY)
1872 			k->k_state |= KS_GATEWAY;
1873 		if (ag->ag_state & AGS_IF)
1874 			k->k_state |= KS_IF;
1875 		if (ag->ag_state & AGS_PASSIVE)
1876 			k->k_state |= KS_PASSIVE;
1877 		if (ag->ag_state & AGS_FILE)
1878 			k->k_state |= KS_FILE;
1879 		k->k_gate = ag->ag_nhop;
1880 		k->k_ifp = ifp;
1881 		k->k_metric = ag->ag_metric;
1882 		return;
1883 	}
1884 
1885 	if ((k->k_state & (KS_STATIC|KS_DEPRE_IF)) ||
1886 	    ((k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF)) {
1887 		return;
1888 	}
1889 
1890 	/* modify existing kernel entry if necessary */
1891 	if (k->k_gate == ag->ag_nhop && k->k_ifp == ag->ag_ifp &&
1892 	    k->k_metric != ag->ag_metric) {
1893 			/*
1894 			 * Must delete bad interface routes etc.
1895 			 * to change them.
1896 			 */
1897 			if (k->k_metric == HOPCNT_INFINITY)
1898 				k->k_state |= KS_DEL_ADD;
1899 			k->k_gate = ag->ag_nhop;
1900 			k->k_metric = ag->ag_metric;
1901 			k->k_state |= KS_CHANGE;
1902 	}
1903 
1904 	/*
1905 	 * If the daemon thinks the route should exist, forget
1906 	 * about any redirections.
1907 	 * If the daemon thinks the route should exist, eventually
1908 	 * override manual intervention by the operator.
1909 	 */
1910 	if ((k->k_state & (KS_DYNAMIC | KS_DELETED)) != 0) {
1911 		k->k_state &= ~KS_DYNAMIC;
1912 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1913 	}
1914 
1915 	if ((k->k_state & KS_GATEWAY) && !(ag->ag_state & AGS_GATEWAY)) {
1916 		k->k_state &= ~KS_GATEWAY;
1917 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1918 	} else if (!(k->k_state & KS_GATEWAY) && (ag->ag_state & AGS_GATEWAY)) {
1919 		k->k_state |= KS_GATEWAY;
1920 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1921 	}
1922 
1923 	/*
1924 	 * Deleting-and-adding is necessary to change aspects of a route.
1925 	 * Just delete instead of deleting and then adding a bad route.
1926 	 * Otherwise, we want to keep the route in the kernel.
1927 	 */
1928 	if (k->k_metric == HOPCNT_INFINITY && (k->k_state & KS_DEL_ADD))
1929 		k->k_state |= KS_DELETE;
1930 	else
1931 		k->k_state &= ~KS_DELETE;
1932 #undef RT
1933 }
1934 
1935 /*
1936  * Update our image of the kernel forwarding table using the given
1937  * route from our internal routing table.
1938  */
1939 
1940 /*ARGSUSED1*/
1941 static int
1942 walk_kern(struct radix_node *rn, void *argp)
1943 {
1944 #define	RT ((struct rt_entry *)rn)
1945 	uint8_t metric, pref;
1946 	uint_t ags = 0;
1947 	int i;
1948 	struct rt_spare *rts;
1949 
1950 	/* Do not install synthetic routes */
1951 	if (RT->rt_state & RS_NET_SYN)
1952 		return (0);
1953 
1954 	/*
1955 	 * Do not install static routes here. Only
1956 	 * read_rt->rtm_add->kern_add should install those
1957 	 */
1958 	if ((RT->rt_state & RS_STATIC) &&
1959 	    (RT->rt_spares[0].rts_origin != RO_FILE))
1960 		return (0);
1961 
1962 	/* Do not clobber kernel if this is a route for a dead interface */
1963 	if (RT->rt_state & RS_BADIF)
1964 		return (0);
1965 
1966 	if (!(RT->rt_state & RS_IF)) {
1967 		/* This is an ordinary route, not for an interface. */
1968 
1969 		/*
1970 		 * aggregate, ordinary good routes without regard to
1971 		 * their metric
1972 		 */
1973 		pref = 1;
1974 		ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1975 
1976 		/*
1977 		 * Do not install host routes directly to hosts, to avoid
1978 		 * interfering with ARP entries in the kernel table.
1979 		 */
1980 		if (RT_ISHOST(RT) && ntohl(RT->rt_dst) == RT->rt_gate)
1981 			return (0);
1982 
1983 	} else {
1984 		/*
1985 		 * This is an interface route.
1986 		 * Do not install routes for "external" remote interfaces.
1987 		 */
1988 		if (RT->rt_ifp != NULL && (RT->rt_ifp->int_state & IS_EXTERNAL))
1989 			return (0);
1990 
1991 		/* Interfaces should override received routes. */
1992 		pref = 0;
1993 		ags |= (AGS_IF | AGS_CORS_GATE);
1994 		if (RT->rt_ifp != NULL &&
1995 		    !(RT->rt_ifp->int_if_flags & IFF_LOOPBACK) &&
1996 		    (RT->rt_ifp->int_state & (IS_PASSIVE|IS_ALIAS)) ==
1997 		    IS_PASSIVE) {
1998 			ags |= AGS_PASSIVE;
1999 		}
2000 
2001 		/*
2002 		 * If it is not an interface, or an alias for an interface,
2003 		 * it must be a "gateway."
2004 		 *
2005 		 * If it is a "remote" interface, it is also a "gateway" to
2006 		 * the kernel if is not a alias.
2007 		 */
2008 		if (RT->rt_ifp == NULL || (RT->rt_ifp->int_state & IS_REMOTE)) {
2009 
2010 			ags |= (AGS_GATEWAY | AGS_SUPPRESS);
2011 
2012 			/*
2013 			 * Do not aggregate IS_PASSIVE routes.
2014 			 */
2015 			if (!(RT->rt_ifp->int_state & IS_PASSIVE))
2016 				ags |= AGS_AGGREGATE;
2017 		}
2018 	}
2019 
2020 	metric = RT->rt_metric;
2021 	if (metric == HOPCNT_INFINITY) {
2022 		/* If the route is dead, try hard to aggregate. */
2023 		pref = HOPCNT_INFINITY;
2024 		ags |= (AGS_FINE_GATE | AGS_SUPPRESS);
2025 		ags &= ~(AGS_IF | AGS_CORS_GATE);
2026 	}
2027 
2028 	/*
2029 	 * dump all routes that have the same metric as rt_spares[0]
2030 	 * into the kern_table, to be added to the kernel.
2031 	 */
2032 	for (i = 0; i < RT->rt_num_spares; i++) {
2033 		rts = &RT->rt_spares[i];
2034 
2035 		/* Do not install external routes */
2036 		if (rts->rts_flags & RTS_EXTERNAL)
2037 			continue;
2038 
2039 		if (rts->rts_metric == metric) {
2040 			ag_check(RT->rt_dst, RT->rt_mask,
2041 			    rts->rts_router, rts->rts_ifp, rts->rts_gate,
2042 			    metric, pref, 0, 0,
2043 			    (rts->rts_origin & RO_FILE) ? (ags|AGS_FILE) : ags,
2044 			    kern_out);
2045 		}
2046 	}
2047 	return (0);
2048 #undef RT
2049 }
2050 
2051 
2052 /* Update the kernel table to match the daemon table. */
2053 static void
2054 fix_kern(void)
2055 {
2056 	int i;
2057 	struct khash *k, *pk, *knext;
2058 
2059 
2060 	need_kern = age_timer;
2061 
2062 	/* Walk daemon table, updating the copy of the kernel table. */
2063 	(void) rn_walktree(rhead, walk_kern, NULL);
2064 	ag_flush(0, 0, kern_out);
2065 
2066 	for (i = 0; i < KHASH_SIZE; i++) {
2067 		pk = NULL;
2068 		for (k = khash_bins[i]; k != NULL;  k = knext) {
2069 			knext = k->k_next;
2070 
2071 			/* Do not touch local interface routes */
2072 			if ((k->k_state & KS_DEPRE_IF) ||
2073 			    (k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF) {
2074 				pk = k;
2075 				continue;
2076 			}
2077 
2078 			/* Do not touch static routes */
2079 			if (k->k_state & KS_STATIC) {
2080 				kern_check_static(k, 0);
2081 				pk = k;
2082 				continue;
2083 			}
2084 
2085 			/* check hold on routes deleted by the operator */
2086 			if (k->k_keep > now.tv_sec) {
2087 				/* ensure we check when the hold is over */
2088 				LIM_SEC(need_kern, k->k_keep);
2089 				pk = k;
2090 				continue;
2091 			}
2092 
2093 			if ((k->k_state & KS_DELETE) &&
2094 			    !(k->k_state & KS_DYNAMIC)) {
2095 				if ((k->k_dst == RIP_DEFAULT) &&
2096 				    (k->k_ifp != NULL) &&
2097 				    (kern_alternate(RIP_DEFAULT,
2098 				    k->k_mask, k->k_gate, k->k_ifp,
2099 				    NULL) == NULL))
2100 					rdisc_restore(k->k_ifp);
2101 				kern_ioctl(k, RTM_DELETE, 0);
2102 				if (pk != NULL)
2103 					pk->k_next = knext;
2104 				else
2105 					khash_bins[i] = knext;
2106 				free(k);
2107 				continue;
2108 			}
2109 
2110 			if (k->k_state & KS_DEL_ADD)
2111 				kern_ioctl(k, RTM_DELETE, 0);
2112 
2113 			if (k->k_state & KS_ADD) {
2114 				if ((k->k_dst == RIP_DEFAULT) &&
2115 				    (k->k_ifp != NULL))
2116 					rdisc_suppress(k->k_ifp);
2117 				kern_ioctl(k, RTM_ADD,
2118 				    ((0 != (k->k_state & (KS_GATEWAY |
2119 					KS_DYNAMIC))) ? RTF_GATEWAY : 0));
2120 			} else if (k->k_state & KS_CHANGE) {
2121 				/*
2122 				 * Should be using RTM_CHANGE here, but
2123 				 * since RTM_CHANGE is currently
2124 				 * not multipath-aware, and assumes
2125 				 * that RTF_GATEWAY implies the gateway
2126 				 * of the route for dst has to be
2127 				 * changed, we play safe, and do a del + add.
2128 				 */
2129 				kern_ioctl(k,  RTM_DELETE, 0);
2130 				kern_ioctl(k, RTM_ADD,
2131 				    ((0 != (k->k_state & (KS_GATEWAY |
2132 					KS_DYNAMIC))) ? RTF_GATEWAY : 0));
2133 			}
2134 			k->k_state &= ~(KS_ADD|KS_CHANGE|KS_DEL_ADD);
2135 
2136 			/*
2137 			 * Mark this route to be deleted in the next cycle.
2138 			 * This deletes routes that disappear from the
2139 			 * daemon table, since the normal aging code
2140 			 * will clear the bit for routes that have not
2141 			 * disappeared from the daemon table.
2142 			 */
2143 			k->k_state |= KS_DELETE;
2144 			pk = k;
2145 		}
2146 	}
2147 }
2148 
2149 
2150 /* Delete a static route in the image of the kernel table. */
2151 void
2152 del_static(in_addr_t dst, in_addr_t mask, in_addr_t gate,
2153     struct interface *ifp, int gone)
2154 {
2155 	struct khash *k;
2156 	struct rt_entry *rt;
2157 
2158 	/*
2159 	 * Just mark it in the table to be deleted next time the kernel
2160 	 * table is updated.
2161 	 * If it has already been deleted, mark it as such, and set its
2162 	 * keep-timer so that it will not be deleted again for a while.
2163 	 * This lets the operator delete a route added by the daemon
2164 	 * and add a replacement.
2165 	 */
2166 	k = kern_find(dst, mask, gate, ifp, NULL);
2167 	if (k != NULL && (gate == 0 || k->k_gate == gate)) {
2168 		k->k_state &= ~(KS_STATIC | KS_DYNAMIC | KS_CHECK);
2169 		k->k_state |= KS_DELETE;
2170 		if (gone) {
2171 			k->k_state |= KS_DELETED;
2172 			k->k_keep = now.tv_sec + K_KEEP_LIM;
2173 		}
2174 	}
2175 
2176 	rt = rtget(dst, mask);
2177 	if (rt != NULL && (rt->rt_state & RS_STATIC))
2178 		rtbad(rt, NULL);
2179 }
2180 
2181 
2182 /*
2183  * Delete all routes generated from ICMP Redirects that use a given gateway,
2184  * as well as old redirected routes.
2185  */
2186 void
2187 del_redirects(in_addr_t bad_gate, time_t old)
2188 {
2189 	int i;
2190 	struct khash *k;
2191 	boolean_t dosupply = should_supply(NULL);
2192 
2193 	for (i = 0; i < KHASH_SIZE; i++) {
2194 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
2195 			if (!(k->k_state & KS_DYNAMIC) ||
2196 			    (k->k_state & (KS_STATIC|KS_IF|KS_DEPRE_IF)))
2197 				continue;
2198 
2199 			if (k->k_gate != bad_gate && k->k_redirect_time > old &&
2200 			    !dosupply)
2201 				continue;
2202 
2203 			k->k_state |= KS_DELETE;
2204 			k->k_state &= ~KS_DYNAMIC;
2205 			need_kern.tv_sec = now.tv_sec;
2206 			trace_act("mark redirected %s --> %s for deletion",
2207 			    addrname(k->k_dst, k->k_mask, 0),
2208 			    naddr_ntoa(k->k_gate));
2209 		}
2210 	}
2211 }
2212 
2213 /* Start the daemon tables. */
2214 void
2215 rtinit(void)
2216 {
2217 	int i;
2218 	struct ag_info *ag;
2219 
2220 	/* Initialize the radix trees */
2221 	rn_init();
2222 	(void) rn_inithead((void**)&rhead, 32);
2223 
2224 	/* mark all of the slots in the table free */
2225 	ag_avail = ag_slots;
2226 	for (ag = ag_slots, i = 1; i < NUM_AG_SLOTS; i++) {
2227 		ag->ag_fine = ag+1;
2228 		ag++;
2229 	}
2230 }
2231 
2232 
2233 static struct sockaddr_in dst_sock = {AF_INET};
2234 static struct sockaddr_in mask_sock = {AF_INET};
2235 
2236 
2237 static void
2238 set_need_flash(void)
2239 {
2240 	if (!need_flash) {
2241 		need_flash = _B_TRUE;
2242 		/*
2243 		 * Do not send the flash update immediately.  Wait a little
2244 		 * while to hear from other routers.
2245 		 */
2246 		no_flash.tv_sec = now.tv_sec + MIN_WAITTIME;
2247 	}
2248 }
2249 
2250 
2251 /* Get a particular routing table entry */
2252 struct rt_entry *
2253 rtget(in_addr_t dst, in_addr_t mask)
2254 {
2255 	struct rt_entry *rt;
2256 
2257 	dst_sock.sin_addr.s_addr = dst;
2258 	mask_sock.sin_addr.s_addr = htonl(mask);
2259 	rt = (struct rt_entry *)rhead->rnh_lookup(&dst_sock, &mask_sock, rhead);
2260 	if (rt == NULL || rt->rt_dst != dst || rt->rt_mask != mask)
2261 		return (NULL);
2262 
2263 	return (rt);
2264 }
2265 
2266 
2267 /* Find a route to dst as the kernel would. */
2268 struct rt_entry *
2269 rtfind(in_addr_t dst)
2270 {
2271 	dst_sock.sin_addr.s_addr = dst;
2272 	return ((struct rt_entry *)rhead->rnh_matchaddr(&dst_sock, rhead));
2273 }
2274 
2275 
2276 /* add a route to the table */
2277 void
2278 rtadd(in_addr_t	dst,
2279     in_addr_t	mask,
2280     uint16_t	state,			/* rt_state for the entry */
2281     struct	rt_spare *new)
2282 {
2283 	struct rt_entry *rt;
2284 	in_addr_t smask;
2285 	int i;
2286 	struct rt_spare *rts;
2287 
2288 	/* This is the only function that increments total_routes. */
2289 	if (total_routes == MAX_ROUTES) {
2290 		msglog("have maximum (%d) routes", total_routes);
2291 		return;
2292 	}
2293 
2294 	rt = rtmalloc(sizeof (*rt), "rtadd");
2295 	(void) memset(rt, 0, sizeof (*rt));
2296 	rt->rt_spares = rtmalloc(SPARE_INC  * sizeof (struct rt_spare),
2297 	    "rtadd");
2298 	rt->rt_num_spares = SPARE_INC;
2299 	(void) memset(rt->rt_spares, 0, SPARE_INC  * sizeof (struct rt_spare));
2300 	for (rts = rt->rt_spares, i = rt->rt_num_spares; i != 0; i--, rts++)
2301 		rts->rts_metric = HOPCNT_INFINITY;
2302 
2303 	rt->rt_nodes->rn_key = (uint8_t *)&rt->rt_dst_sock;
2304 	rt->rt_dst = dst;
2305 	rt->rt_dst_sock.sin_family = AF_INET;
2306 	if (mask != HOST_MASK) {
2307 		smask = std_mask(dst);
2308 		if ((smask & ~mask) == 0 && mask > smask)
2309 			state |= RS_SUBNET;
2310 	}
2311 	mask_sock.sin_addr.s_addr = htonl(mask);
2312 	rt->rt_mask = mask;
2313 	rt->rt_spares[0] = *new;
2314 	rt->rt_state = state;
2315 	rt->rt_time = now.tv_sec;
2316 	rt->rt_poison_metric = HOPCNT_INFINITY;
2317 	rt->rt_seqno = update_seqno;
2318 
2319 	if (TRACEACTIONS)
2320 		trace_add_del("Add", rt);
2321 
2322 	need_kern.tv_sec = now.tv_sec;
2323 	set_need_flash();
2324 
2325 	if (NULL == rhead->rnh_addaddr(&rt->rt_dst_sock, &mask_sock, rhead,
2326 	    rt->rt_nodes)) {
2327 		msglog("rnh_addaddr() failed for %s mask=%s",
2328 		    naddr_ntoa(dst), naddr_ntoa(htonl(mask)));
2329 		free(rt);
2330 	}
2331 
2332 	total_routes++;
2333 }
2334 
2335 
2336 /* notice a changed route */
2337 void
2338 rtchange(struct rt_entry *rt,
2339     uint16_t	state,			/* new state bits */
2340     struct rt_spare *new,
2341     char	*label)
2342 {
2343 	if (rt->rt_metric != new->rts_metric) {
2344 		/*
2345 		 * Fix the kernel immediately if it seems the route
2346 		 * has gone bad, since there may be a working route that
2347 		 * aggregates this route.
2348 		 */
2349 		if (new->rts_metric == HOPCNT_INFINITY) {
2350 			need_kern.tv_sec = now.tv_sec;
2351 			if (new->rts_time >= now.tv_sec - EXPIRE_TIME)
2352 				new->rts_time = now.tv_sec - EXPIRE_TIME;
2353 		}
2354 		rt->rt_seqno = update_seqno;
2355 		set_need_flash();
2356 	}
2357 
2358 	if (rt->rt_gate != new->rts_gate) {
2359 		need_kern.tv_sec = now.tv_sec;
2360 		rt->rt_seqno = update_seqno;
2361 		set_need_flash();
2362 	}
2363 
2364 	state |= (rt->rt_state & RS_SUBNET);
2365 
2366 	/* Keep various things from deciding ageless routes are stale. */
2367 	if (!AGE_RT(state, rt->rt_spares[0].rts_origin, new->rts_ifp))
2368 		new->rts_time = now.tv_sec;
2369 
2370 	if (TRACEACTIONS)
2371 		trace_change(rt, state, new,
2372 		    label ? label : "Chg   ");
2373 
2374 	rt->rt_state = state;
2375 	/*
2376 	 * If the interface state of the new primary route is good,
2377 	 * turn off RS_BADIF flag
2378 	 */
2379 	if ((rt->rt_state & RS_BADIF) &&
2380 	    IS_IFF_UP(new->rts_ifp->int_if_flags) &&
2381 	    !(new->rts_ifp->int_state & (IS_BROKE | IS_SICK)))
2382 		rt->rt_state &= ~(RS_BADIF);
2383 
2384 	rt->rt_spares[0] = *new;
2385 }
2386 
2387 
2388 /* check for a better route among the spares */
2389 static struct rt_spare *
2390 rts_better(struct rt_entry *rt)
2391 {
2392 	struct rt_spare *rts, *rts1;
2393 	int i;
2394 
2395 	/* find the best alternative among the spares */
2396 	rts = rt->rt_spares+1;
2397 	for (i = rt->rt_num_spares, rts1 = rts+1; i > 2; i--, rts1++) {
2398 		if (BETTER_LINK(rt, rts1, rts))
2399 			rts = rts1;
2400 	}
2401 
2402 	return (rts);
2403 }
2404 
2405 
2406 /* switch to a backup route */
2407 void
2408 rtswitch(struct rt_entry *rt,
2409     struct rt_spare *rts)
2410 {
2411 	struct rt_spare swap;
2412 	char label[10];
2413 
2414 	/* Do not change permanent routes */
2415 	if (0 != (rt->rt_state & (RS_MHOME | RS_STATIC |
2416 	    RS_NET_SYN | RS_IF)))
2417 		return;
2418 
2419 	/* find the best alternative among the spares */
2420 	if (rts == NULL)
2421 		rts = rts_better(rt);
2422 
2423 	/* Do not bother if it is not worthwhile. */
2424 	if (!BETTER_LINK(rt, rts, rt->rt_spares))
2425 		return;
2426 
2427 	swap = rt->rt_spares[0];
2428 	(void) snprintf(label, sizeof (label), "Use #%d",
2429 	    (int)(rts - rt->rt_spares));
2430 	rtchange(rt, rt->rt_state & ~(RS_NET_SYN), rts, label);
2431 
2432 	if (swap.rts_metric == HOPCNT_INFINITY) {
2433 		*rts = rts_empty;
2434 	} else {
2435 		*rts = swap;
2436 	}
2437 
2438 }
2439 
2440 
2441 void
2442 rtdelete(struct rt_entry *rt)
2443 {
2444 	struct rt_entry *deleted_rt;
2445 	struct rt_spare *rts;
2446 	int i;
2447 	in_addr_t gate = rt->rt_gate; /* for debugging */
2448 
2449 	if (TRACEACTIONS)
2450 		trace_add_del("Del", rt);
2451 
2452 	for (i = 0; i < rt->rt_num_spares; i++) {
2453 		rts = &rt->rt_spares[i];
2454 		rts_delete(rt, rts);
2455 	}
2456 
2457 	dst_sock.sin_addr.s_addr = rt->rt_dst;
2458 	mask_sock.sin_addr.s_addr = htonl(rt->rt_mask);
2459 	if (rt != (deleted_rt =
2460 	    ((struct rt_entry *)rhead->rnh_deladdr(&dst_sock, &mask_sock,
2461 	    rhead)))) {
2462 		msglog("rnh_deladdr(%s) failed; found rt 0x%lx",
2463 		    rtname(rt->rt_dst, rt->rt_mask, gate), deleted_rt);
2464 		if (deleted_rt != NULL)
2465 			free(deleted_rt);
2466 	}
2467 	total_routes--;
2468 	free(rt);
2469 
2470 	if (dst_sock.sin_addr.s_addr == RIP_DEFAULT) {
2471 		/*
2472 		 * we just deleted the default route. Trigger rdisc_sort
2473 		 * so that we can recover from any rdisc information that
2474 		 * is valid
2475 		 */
2476 		rdisc_timer.tv_sec = 0;
2477 	}
2478 }
2479 
2480 void
2481 rts_delete(struct rt_entry *rt, struct rt_spare *rts)
2482 {
2483 	struct khash *k;
2484 
2485 	trace_upslot(rt, rts, &rts_empty);
2486 	k = kern_find(rt->rt_dst, rt->rt_mask,
2487 	    rts->rts_gate, rts->rts_ifp, NULL);
2488 	if (k != NULL &&
2489 	    !(k->k_state & KS_DEPRE_IF) &&
2490 	    ((k->k_state & (KS_IF|KS_PASSIVE)) != KS_IF)) {
2491 		k->k_state |= KS_DELETE;
2492 		need_kern.tv_sec = now.tv_sec;
2493 	}
2494 
2495 	*rts = rts_empty;
2496 }
2497 
2498 /*
2499  * Get rid of a bad route, and try to switch to a replacement.
2500  * If the route has gone bad because of a bad interface,
2501  * the information about the dead interface is available in badifp
2502  * for the purpose of sanity checks, if_flags checks etc.
2503  */
2504 static void
2505 rtbad(struct rt_entry *rt, struct interface *badifp)
2506 {
2507 	struct rt_spare new;
2508 	uint16_t rt_state;
2509 
2510 
2511 	if (badifp == NULL || (rt->rt_spares[0].rts_ifp == badifp)) {
2512 		/* Poison the route */
2513 		new = rt->rt_spares[0];
2514 		new.rts_metric = HOPCNT_INFINITY;
2515 		rt_state = rt->rt_state & ~(RS_IF | RS_LOCAL | RS_STATIC);
2516 	}
2517 
2518 	if (badifp != NULL) {
2519 		/*
2520 		 * Dont mark the rtentry bad unless the ifp for the primary
2521 		 * route is the bad ifp
2522 		 */
2523 		if (rt->rt_spares[0].rts_ifp != badifp)
2524 			return;
2525 		/*
2526 		 * badifp has just gone bad. We want to keep this
2527 		 * rt_entry around so that we tell our rip-neighbors
2528 		 * about the bad route, but we can't do anything
2529 		 * to the kernel itself, so mark it as RS_BADIF
2530 		 */
2531 		trace_misc("rtbad:Setting RS_BADIF (%s)", badifp->int_name);
2532 		rt_state |= RS_BADIF;
2533 		new.rts_ifp = &dummy_ifp;
2534 	}
2535 	rtchange(rt, rt_state, &new, 0);
2536 	rtswitch(rt, 0);
2537 }
2538 
2539 
2540 /*
2541  * Junk a RS_NET_SYN or RS_LOCAL route,
2542  *	unless it is needed by another interface.
2543  */
2544 void
2545 rtbad_sub(struct rt_entry *rt, struct interface *badifp)
2546 {
2547 	struct interface *ifp, *ifp1;
2548 	struct intnet *intnetp;
2549 	uint_t state;
2550 
2551 
2552 	ifp1 = NULL;
2553 	state = 0;
2554 
2555 	if (rt->rt_state & RS_LOCAL) {
2556 		/*
2557 		 * Is this the route through loopback for the interface?
2558 		 * If so, see if it is used by any other interfaces, such
2559 		 * as a point-to-point interface with the same local address.
2560 		 */
2561 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2562 			/* Retain it if another interface needs it. */
2563 			if (ifp->int_addr == rt->rt_ifp->int_addr) {
2564 				state |= RS_LOCAL;
2565 				ifp1 = ifp;
2566 				break;
2567 			}
2568 		}
2569 
2570 	}
2571 
2572 	if (!(state & RS_LOCAL)) {
2573 		/*
2574 		 * Retain RIPv1 logical network route if there is another
2575 		 * interface that justifies it.
2576 		 */
2577 		if (rt->rt_state & RS_NET_SYN) {
2578 			for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2579 				if ((ifp->int_state & IS_NEED_NET_SYN) &&
2580 				    rt->rt_mask == ifp->int_std_mask &&
2581 				    rt->rt_dst == ifp->int_std_addr) {
2582 					state |= RS_NET_SYN;
2583 					ifp1 = ifp;
2584 					break;
2585 				}
2586 			}
2587 		}
2588 
2589 		/* or if there is an authority route that needs it. */
2590 		for (intnetp = intnets; intnetp != NULL;
2591 		    intnetp = intnetp->intnet_next) {
2592 			if (intnetp->intnet_addr == rt->rt_dst &&
2593 			    intnetp->intnet_mask == rt->rt_mask) {
2594 				state |= (RS_NET_SYN | RS_NET_INT);
2595 				break;
2596 			}
2597 		}
2598 	}
2599 
2600 	if (ifp1 != NULL || (state & RS_NET_SYN)) {
2601 		struct rt_spare new = rt->rt_spares[0];
2602 		new.rts_ifp = ifp1;
2603 		rtchange(rt, ((rt->rt_state & ~(RS_NET_SYN|RS_LOCAL)) | state),
2604 		    &new, 0);
2605 	} else {
2606 		rtbad(rt, badifp);
2607 	}
2608 }
2609 
2610 /*
2611  * Called while walking the table looking for sick interfaces
2612  * or after a time change.
2613  */
2614 int
2615 walk_bad(struct radix_node *rn,
2616     void *argp)
2617 {
2618 #define	RT ((struct rt_entry *)rn)
2619 	struct rt_spare *rts;
2620 	int i, j = -1;
2621 
2622 	/* fix any spare routes through the interface */
2623 	for (i = 1; i < RT->rt_num_spares; i++) {
2624 		rts = &((struct rt_entry *)rn)->rt_spares[i];
2625 
2626 		if (rts->rts_metric < HOPCNT_INFINITY &&
2627 		    (rts->rts_ifp == NULL ||
2628 		    (rts->rts_ifp->int_state & IS_BROKE)))
2629 			rts_delete(RT, rts);
2630 		else {
2631 			if (rts->rts_origin != RO_NONE)
2632 				j = i;
2633 		}
2634 	}
2635 
2636 	/*
2637 	 * Deal with the main route
2638 	 * finished if it has been handled before or if its interface is ok
2639 	 */
2640 	if (RT->rt_ifp == NULL || !(RT->rt_ifp->int_state & IS_BROKE))
2641 		return (0);
2642 
2643 	/* Bad routes for other than interfaces are easy. */
2644 	if (!(RT->rt_state & (RS_IF | RS_NET_SYN | RS_LOCAL))) {
2645 		if (j > 0) {
2646 			RT->rt_spares[0].rts_metric = HOPCNT_INFINITY;
2647 			rtswitch(RT, NULL);
2648 		} else {
2649 			rtbad(RT, (struct interface *)argp);
2650 		}
2651 		return (0);
2652 	}
2653 
2654 	rtbad_sub(RT, (struct interface *)argp);
2655 	return (0);
2656 #undef RT
2657 }
2658 
2659 /*
2660  * Called while walking the table to replace a duplicate interface
2661  * with a backup.
2662  */
2663 int
2664 walk_rewire(struct radix_node *rn, void *argp)
2665 {
2666 	struct rt_entry *RT = (struct rt_entry *)rn;
2667 	struct rewire_data *wire = (struct rewire_data *)argp;
2668 	struct rt_spare *rts;
2669 	int i;
2670 
2671 	/* fix any spare routes through the interface */
2672 	rts = RT->rt_spares;
2673 	for (i = RT->rt_num_spares; i > 0; i--, rts++) {
2674 		if (rts->rts_ifp == wire->if_old) {
2675 			rts->rts_ifp = wire->if_new;
2676 			if ((RT->rt_dst == RIP_DEFAULT) &&
2677 			    (wire->if_old->int_state & IS_SUPPRESS_RDISC))
2678 				rdisc_suppress(rts->rts_ifp);
2679 			if ((rts->rts_metric += wire->metric_delta) >
2680 			    HOPCNT_INFINITY)
2681 				rts->rts_metric = HOPCNT_INFINITY;
2682 
2683 			/*
2684 			 * If the main route is getting a worse metric,
2685 			 * then it may be time to switch to a backup.
2686 			 */
2687 			if (i == RT->rt_num_spares && wire->metric_delta > 0) {
2688 				rtswitch(RT, NULL);
2689 			}
2690 		}
2691 	}
2692 
2693 	return (0);
2694 }
2695 
2696 /* Check the age of an individual route. */
2697 static int
2698 walk_age(struct radix_node *rn, void *argp)
2699 {
2700 #define	RT ((struct rt_entry *)rn)
2701 	struct interface *ifp;
2702 	struct rt_spare *rts;
2703 	int i;
2704 	in_addr_t age_bad_gate = *(in_addr_t *)argp;
2705 
2706 
2707 	/*
2708 	 * age all of the spare routes, including the primary route
2709 	 * currently in use
2710 	 */
2711 	rts = RT->rt_spares;
2712 	for (i = RT->rt_num_spares; i != 0; i--, rts++) {
2713 
2714 		ifp = rts->rts_ifp;
2715 		if (i == RT->rt_num_spares) {
2716 			if (!AGE_RT(RT->rt_state, rts->rts_origin, ifp)) {
2717 				/*
2718 				 * Keep various things from deciding ageless
2719 				 * routes are stale
2720 				 */
2721 				rts->rts_time = now.tv_sec;
2722 				continue;
2723 			}
2724 
2725 			/* forget RIP routes after RIP has been turned off. */
2726 			if (rip_sock < 0) {
2727 				rts->rts_time = now_stale + 1;
2728 			}
2729 		}
2730 
2731 		/* age failing routes */
2732 		if (age_bad_gate == rts->rts_gate &&
2733 		    rts->rts_time >= now_stale) {
2734 			rts->rts_time -= SUPPLY_INTERVAL;
2735 		}
2736 
2737 		/* trash the spare routes when they go bad */
2738 		if (rts->rts_origin == RO_RIP &&
2739 		    ((rip_sock < 0) ||
2740 		    (rts->rts_metric < HOPCNT_INFINITY &&
2741 		    now_garbage > rts->rts_time)) &&
2742 		    i != RT->rt_num_spares) {
2743 			rts_delete(RT, rts);
2744 		}
2745 	}
2746 
2747 
2748 	/* finished if the active route is still fresh */
2749 	if (now_stale <= RT->rt_time)
2750 		return (0);
2751 
2752 	/* try to switch to an alternative */
2753 	rtswitch(RT, NULL);
2754 
2755 	/* Delete a dead route after it has been publically mourned. */
2756 	if (now_garbage > RT->rt_time) {
2757 		rtdelete(RT);
2758 		return (0);
2759 	}
2760 
2761 	/* Start poisoning a bad route before deleting it. */
2762 	if (now.tv_sec - RT->rt_time > EXPIRE_TIME) {
2763 		struct rt_spare new = RT->rt_spares[0];
2764 
2765 		new.rts_metric = HOPCNT_INFINITY;
2766 		rtchange(RT, RT->rt_state, &new, 0);
2767 	}
2768 	return (0);
2769 }
2770 
2771 
2772 /* Watch for dead routes and interfaces. */
2773 void
2774 age(in_addr_t bad_gate)
2775 {
2776 	struct interface *ifp;
2777 	int need_query = 0;
2778 
2779 	/*
2780 	 * If not listening to RIP, there is no need to age the routes in
2781 	 * the table.
2782 	 */
2783 	age_timer.tv_sec = (now.tv_sec
2784 	    + ((rip_sock < 0) ? NEVER : SUPPLY_INTERVAL));
2785 
2786 	/*
2787 	 * Check for dead IS_REMOTE interfaces by timing their
2788 	 * transmissions.
2789 	 */
2790 	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
2791 		if (!(ifp->int_state & IS_REMOTE))
2792 			continue;
2793 
2794 		/* ignore unreachable remote interfaces */
2795 		if (!check_remote(ifp))
2796 			continue;
2797 
2798 		/* Restore remote interface that has become reachable */
2799 		if (ifp->int_state & IS_BROKE)
2800 			if_ok(ifp, "remote ", _B_FALSE);
2801 
2802 		if (ifp->int_act_time != NEVER &&
2803 		    now.tv_sec - ifp->int_act_time > EXPIRE_TIME) {
2804 			writelog(LOG_NOTICE,
2805 			    "remote interface %s to %s timed out after"
2806 			    " %ld:%ld",
2807 			    ifp->int_name,
2808 			    naddr_ntoa(ifp->int_dstaddr),
2809 			    (now.tv_sec - ifp->int_act_time)/60,
2810 			    (now.tv_sec - ifp->int_act_time)%60);
2811 			if_sick(ifp, _B_FALSE);
2812 		}
2813 
2814 		/*
2815 		 * If we have not heard from the other router
2816 		 * recently, ask it.
2817 		 */
2818 		if (now.tv_sec >= ifp->int_query_time) {
2819 			ifp->int_query_time = NEVER;
2820 			need_query = 1;
2821 		}
2822 	}
2823 
2824 	/* Age routes. */
2825 	(void) rn_walktree(rhead, walk_age, &bad_gate);
2826 
2827 	/*
2828 	 * delete old redirected routes to keep the kernel table small
2829 	 * and prevent blackholes
2830 	 */
2831 	del_redirects(bad_gate, now.tv_sec-STALE_TIME);
2832 
2833 	/* Update the kernel routing table. */
2834 	fix_kern();
2835 
2836 	/* poke reticent remote gateways */
2837 	if (need_query)
2838 		rip_query();
2839 }
2840 
2841 void
2842 kern_dump(void)
2843 {
2844 	int i;
2845 	struct khash *k;
2846 
2847 	for (i = 0; i < KHASH_SIZE; i++) {
2848 		for (k = khash_bins[i]; k != NULL; k = k->k_next)
2849 			trace_khash(k);
2850 	}
2851 }
2852 
2853 
2854 static struct interface *
2855 gwkludge_iflookup(in_addr_t dstaddr, in_addr_t addr, in_addr_t mask)
2856 {
2857 	uint32_t int_state;
2858 	struct interface *ifp;
2859 
2860 	for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2861 		int_state = ifp->int_state;
2862 
2863 		if (!(int_state & IS_REMOTE))
2864 			continue;
2865 
2866 		if (ifp->int_dstaddr == dstaddr && ifp->int_addr == addr &&
2867 		    ifp->int_mask == mask)
2868 			return (ifp);
2869 	}
2870 	return (NULL);
2871 }
2872