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