xref: /titanic_51/usr/src/cmd/cmd-inet/usr.sbin/in.routed/table.c (revision d485aa23b5e424dd136afdf657683389f93f72d6)
1 /*
2  * Copyright 2005 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 	for (pk = &KHASH(dst, mask); (k = *pk) != NULL; pk = &k->k_next) {
907 		if (k->k_dst == dst && k->k_mask == mask &&
908 		    (gate == 0 || k->k_gate == gate) &&
909 		    (ifp == NULL || k->k_ifp == ifp)) {
910 			break;
911 		}
912 	}
913 	if (ppk != NULL)
914 		*ppk = pk;
915 	return (k);
916 }
917 
918 
919 /*
920  * Find out if there is an alternate route to a given destination
921  * off of a given interface.
922  */
923 static struct khash *
924 kern_alternate(in_addr_t dst, in_addr_t mask, in_addr_t gate,
925     struct interface *ifp, struct khash ***ppk)
926 {
927 	struct khash *k, **pk;
928 
929 	for (pk = &KHASH(dst, mask); (k = *pk) != NULL; pk = &k->k_next) {
930 		if (k->k_dst == dst && k->k_mask == mask &&
931 		    (k->k_gate != gate) &&
932 		    (k->k_ifp == ifp)) {
933 			break;
934 		}
935 	}
936 	if (ppk != NULL)
937 		*ppk = pk;
938 	return (k);
939 }
940 
941 static struct khash *
942 kern_add(in_addr_t dst, uint32_t mask, in_addr_t gate, struct interface *ifp)
943 {
944 	struct khash *k, **pk;
945 
946 	k = kern_find(dst, mask, gate, ifp, &pk);
947 	if (k != NULL)
948 		return (k);
949 
950 	k = rtmalloc(sizeof (*k), "kern_add");
951 
952 	(void) memset(k, 0, sizeof (*k));
953 	k->k_dst = dst;
954 	k->k_mask = mask;
955 	k->k_state = KS_NEW;
956 	k->k_keep = now.tv_sec;
957 	k->k_gate = gate;
958 	k->k_ifp = ifp;
959 	*pk = k;
960 
961 	return (k);
962 }
963 
964 /* delete all khash entries that are wired through the interface ifp */
965 void
966 kern_flush_ifp(struct interface *ifp)
967 {
968 	struct khash *k, *kprev, *knext;
969 	int i;
970 
971 	for (i = 0; i < KHASH_SIZE; i++) {
972 		kprev = NULL;
973 		for (k = khash_bins[i]; k != NULL; k = knext) {
974 			knext = k->k_next;
975 			if (k->k_ifp == ifp) {
976 				if (kprev != NULL)
977 					kprev->k_next = k->k_next;
978 				else
979 					khash_bins[i] = k->k_next;
980 				free(k);
981 				continue;
982 			}
983 			kprev = k;
984 		}
985 	}
986 }
987 
988 /*
989  * rewire khash entries that currently go through oldifp to
990  * go through newifp.
991  */
992 void
993 kern_rewire_ifp(struct interface *oldifp, struct interface *newifp)
994 {
995 	struct khash *k;
996 	int i;
997 
998 	for (i = 0; i < KHASH_SIZE; i++) {
999 		for (k = khash_bins[i]; k; k = k->k_next) {
1000 			if (k->k_ifp == oldifp) {
1001 				k->k_ifp = newifp;
1002 				trace_misc("kern_rewire_ifp k 0x%lx "
1003 				    "from %s to %s", k, oldifp->int_name,
1004 				    newifp->int_name);
1005 			}
1006 		}
1007 	}
1008 }
1009 
1010 
1011 /*
1012  * Check that a static route it is still in the daemon table, and not
1013  * deleted by interfaces coming and going.  This is also the routine
1014  * responsible for adding new static routes to the daemon table.
1015  */
1016 static void
1017 kern_check_static(struct khash *k, struct interface *ifp)
1018 {
1019 	struct rt_entry *rt;
1020 	struct rt_spare new;
1021 	uint16_t rt_state = RS_STATIC;
1022 
1023 	(void) memset(&new, 0, sizeof (new));
1024 	new.rts_ifp = ifp;
1025 	new.rts_gate = k->k_gate;
1026 	new.rts_router = (ifp != NULL) ? ifp->int_addr : loopaddr;
1027 	new.rts_metric = k->k_metric;
1028 	new.rts_time = now.tv_sec;
1029 	new.rts_origin = RO_STATIC;
1030 
1031 	rt = rtget(k->k_dst, k->k_mask);
1032 	if ((ifp != NULL && !IS_IFF_ROUTING(ifp->int_if_flags)) ||
1033 	    (k->k_state & KS_PRIVATE))
1034 		rt_state |= RS_NOPROPAGATE;
1035 
1036 	if (rt != NULL) {
1037 		if ((rt->rt_state & RS_STATIC) == 0) {
1038 			/*
1039 			 * We are already tracking this dest/mask
1040 			 * via RIP/RDISC. Ignore the static route,
1041 			 * because we don't currently have a good
1042 			 * way to compare metrics on static routes
1043 			 * with rip metrics, and therefore cannot
1044 			 * mix and match the two.
1045 			 */
1046 			return;
1047 		}
1048 		rt_state |= rt->rt_state;
1049 		if (rt->rt_state != rt_state)
1050 			rtchange(rt, rt_state, &new, 0);
1051 	} else {
1052 		rtadd(k->k_dst, k->k_mask, rt_state, &new);
1053 	}
1054 }
1055 
1056 
1057 /* operate on a kernel entry */
1058 static void
1059 kern_ioctl(struct khash *k,
1060     int action,			/* RTM_DELETE, etc */
1061     int flags)
1062 {
1063 	if (((k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF) ||
1064 	    (k->k_state & KS_DEPRE_IF)) {
1065 		/*
1066 		 * Prevent execution of RTM_DELETE, RTM_ADD or
1067 		 * RTM_CHANGE of interface routes
1068 		 */
1069 		trace_act("Blocking execution of %s  %s --> %s ",
1070 		    rtm_type_name(action),
1071 		    addrname(k->k_dst, k->k_mask, 0), naddr_ntoa(k->k_gate));
1072 		return;
1073 	}
1074 
1075 	switch (action) {
1076 	case RTM_DELETE:
1077 		k->k_state &= ~KS_DYNAMIC;
1078 		if (k->k_state & KS_DELETED)
1079 			return;
1080 		k->k_state |= KS_DELETED;
1081 		break;
1082 	case RTM_ADD:
1083 		k->k_state &= ~KS_DELETED;
1084 		break;
1085 	case RTM_CHANGE:
1086 		if (k->k_state & KS_DELETED) {
1087 			action = RTM_ADD;
1088 			k->k_state &= ~KS_DELETED;
1089 		}
1090 		break;
1091 	}
1092 
1093 	rtioctl(action, k->k_dst, k->k_gate, k->k_mask, k->k_ifp,
1094 	    k->k_metric, flags);
1095 }
1096 
1097 
1098 /* add a route the kernel told us */
1099 static void
1100 rtm_add(struct rt_msghdr *rtm,
1101     struct rt_addrinfo *info,
1102     time_t keep,
1103     boolean_t interf_route,
1104     struct interface *ifptr)
1105 {
1106 	struct khash *k;
1107 	struct interface *ifp = ifptr;
1108 	in_addr_t mask, gate = 0;
1109 	static struct msg_limit msg_no_ifp;
1110 
1111 	if (rtm->rtm_flags & RTF_HOST) {
1112 		mask = HOST_MASK;
1113 	} else if (INFO_MASK(info) != 0) {
1114 		mask = ntohl(S_ADDR(INFO_MASK(info)));
1115 	} else {
1116 		writelog(LOG_WARNING,
1117 		    "ignore %s without mask", rtm_type_name(rtm->rtm_type));
1118 		return;
1119 	}
1120 
1121 	/*
1122 	 * Find the interface toward the gateway.
1123 	 */
1124 	if (INFO_GATE(info) != NULL)
1125 		gate = S_ADDR(INFO_GATE(info));
1126 
1127 	if (ifp == NULL) {
1128 		if (INFO_GATE(info) != NULL)
1129 			ifp = iflookup(gate);
1130 		if (ifp == NULL)
1131 			msglim(&msg_no_ifp, gate,
1132 			    "route %s --> %s nexthop is not directly connected",
1133 			    addrname(S_ADDR(INFO_DST(info)), mask, 0),
1134 			    naddr_ntoa(gate));
1135 	}
1136 
1137 	k = kern_add(S_ADDR(INFO_DST(info)), mask, gate, ifp);
1138 
1139 	if (k->k_state & KS_NEW)
1140 		k->k_keep = now.tv_sec+keep;
1141 	if (INFO_GATE(info) == 0) {
1142 		trace_act("note %s without gateway",
1143 		    rtm_type_name(rtm->rtm_type));
1144 		k->k_metric = HOPCNT_INFINITY;
1145 	} else if (INFO_GATE(info)->ss_family != AF_INET) {
1146 		trace_act("note %s with gateway AF=%d",
1147 		    rtm_type_name(rtm->rtm_type),
1148 		    INFO_GATE(info)->ss_family);
1149 		k->k_metric = HOPCNT_INFINITY;
1150 	} else {
1151 		k->k_gate = S_ADDR(INFO_GATE(info));
1152 		k->k_metric = rtm->rtm_rmx.rmx_hopcount;
1153 		if (k->k_metric < 0)
1154 			k->k_metric = 0;
1155 		else if (k->k_metric > HOPCNT_INFINITY-1)
1156 			k->k_metric = HOPCNT_INFINITY-1;
1157 	}
1158 
1159 	if ((k->k_state & KS_NEW) && interf_route) {
1160 		if (k->k_gate != 0 && findifaddr(k->k_gate) == NULL)
1161 			k->k_state |= KS_DEPRE_IF;
1162 		else
1163 			k->k_state |= KS_IF;
1164 	}
1165 
1166 	k->k_state &= ~(KS_NEW | KS_DELETE | KS_ADD | KS_CHANGE | KS_DEL_ADD |
1167 	    KS_STATIC | KS_GATEWAY | KS_DELETED | KS_PRIVATE | KS_CHECK);
1168 	if (rtm->rtm_flags & RTF_GATEWAY)
1169 		k->k_state |= KS_GATEWAY;
1170 	if (rtm->rtm_flags & RTF_STATIC)
1171 		k->k_state |= KS_STATIC;
1172 	if (rtm->rtm_flags & RTF_PRIVATE)
1173 		k->k_state |= KS_PRIVATE;
1174 
1175 
1176 	if (rtm->rtm_flags & (RTF_DYNAMIC | RTF_MODIFIED)) {
1177 		if (INFO_AUTHOR(info) != 0 &&
1178 		    INFO_AUTHOR(info)->ss_family == AF_INET)
1179 			ifp = iflookup(S_ADDR(INFO_AUTHOR(info)));
1180 		else
1181 			ifp = NULL;
1182 		if (should_supply(ifp) && (ifp == NULL ||
1183 		    !(ifp->int_state & IS_REDIRECT_OK))) {
1184 			/*
1185 			 * Routers are not supposed to listen to redirects,
1186 			 * so delete it if it came via an unknown interface
1187 			 * or the interface does not have special permission.
1188 			 */
1189 			k->k_state &= ~KS_DYNAMIC;
1190 			k->k_state |= KS_DELETE;
1191 			LIM_SEC(need_kern, 0);
1192 			trace_act("mark for deletion redirected %s --> %s"
1193 			    " via %s",
1194 			    addrname(k->k_dst, k->k_mask, 0),
1195 			    naddr_ntoa(k->k_gate),
1196 			    ifp ? ifp->int_name : "unknown interface");
1197 		} else {
1198 			k->k_state |= KS_DYNAMIC;
1199 			k->k_redirect_time = now.tv_sec;
1200 			trace_act("accept redirected %s --> %s via %s",
1201 			    addrname(k->k_dst, k->k_mask, 0),
1202 			    naddr_ntoa(k->k_gate),
1203 			    ifp ? ifp->int_name : "unknown interface");
1204 		}
1205 		return;
1206 	}
1207 
1208 	/*
1209 	 * If it is not a static route, quit until the next comparison
1210 	 * between the kernel and daemon tables, when it will be deleted.
1211 	 */
1212 	if (!(k->k_state & KS_STATIC)) {
1213 		if (!(k->k_state & (KS_IF|KS_DEPRE_IF|KS_FILE)))
1214 			k->k_state |= KS_DELETE;
1215 		LIM_SEC(need_kern, k->k_keep);
1216 		return;
1217 	}
1218 
1219 	/*
1220 	 * Put static routes with real metrics into the daemon table so
1221 	 * they can be advertised.
1222 	 */
1223 
1224 	kern_check_static(k, ifp);
1225 }
1226 
1227 
1228 /* deal with packet loss */
1229 static void
1230 rtm_lose(struct rt_msghdr *rtm, struct rt_addrinfo *info)
1231 {
1232 	if (INFO_GATE(info) == NULL || INFO_GATE(info)->ss_family != AF_INET) {
1233 		trace_act("ignore %s without gateway",
1234 		    rtm_type_name(rtm->rtm_type));
1235 		age(0);
1236 		return;
1237 	}
1238 
1239 	if (rdisc_ok)
1240 		rdisc_age(S_ADDR(INFO_GATE(info)));
1241 	age(S_ADDR(INFO_GATE(info)));
1242 }
1243 
1244 
1245 /*
1246  * Make the gateway slot of an info structure point to something
1247  * useful.  If it is not already useful, but it specifies an interface,
1248  * then fill in the sockaddr_in provided and point it there.
1249  */
1250 static int
1251 get_info_gate(struct sockaddr_storage **ssp, struct sockaddr_in *sin)
1252 {
1253 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)*ssp;
1254 	struct interface *ifp;
1255 
1256 	if (sdl == NULL)
1257 		return (0);
1258 	if ((sdl)->sdl_family == AF_INET)
1259 		return (1);
1260 	if ((sdl)->sdl_family != AF_LINK)
1261 		return (0);
1262 
1263 	ifp = ifwithindex(sdl->sdl_index, _B_TRUE);
1264 	if (ifp == NULL)
1265 		return (0);
1266 
1267 	sin->sin_addr.s_addr = ifp->int_addr;
1268 	sin->sin_family = AF_INET;
1269 	/* LINTED */
1270 	*ssp = (struct sockaddr_storage *)sin;
1271 
1272 	return (1);
1273 }
1274 
1275 
1276 /*
1277  * Clean the kernel table by copying it to the daemon image.
1278  * Eventually the daemon will delete any extra routes.
1279  */
1280 void
1281 sync_kern(void)
1282 {
1283 	int i;
1284 	struct khash *k;
1285 	struct {
1286 		struct T_optmgmt_req req;
1287 		struct opthdr hdr;
1288 	} req;
1289 	union {
1290 		struct T_optmgmt_ack ack;
1291 		unsigned char space[64];
1292 	} ack;
1293 	struct opthdr *rh;
1294 	struct strbuf cbuf, dbuf;
1295 	int ipfd, nroutes, flags, r;
1296 	mib2_ipRouteEntry_t routes[8];
1297 	mib2_ipRouteEntry_t *rp;
1298 	struct rt_msghdr rtm;
1299 	struct rt_addrinfo info;
1300 	struct sockaddr_in sin_dst;
1301 	struct sockaddr_in sin_gate;
1302 	struct sockaddr_in sin_mask;
1303 	struct sockaddr_in sin_author;
1304 	struct interface *ifp;
1305 	char ifname[LIFNAMSIZ + 1];
1306 
1307 	for (i = 0; i < KHASH_SIZE; i++) {
1308 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
1309 			if (!(k->k_state & (KS_IF|KS_DEPRE_IF)))
1310 				k->k_state |= KS_CHECK;
1311 		}
1312 	}
1313 
1314 	ipfd = open(IP_DEV_NAME, O_RDWR);
1315 	if (ipfd == -1) {
1316 		msglog("open " IP_DEV_NAME ": %s", rip_strerror(errno));
1317 		goto hash_clean;
1318 	}
1319 
1320 	req.req.PRIM_type = T_OPTMGMT_REQ;
1321 	req.req.OPT_offset = (caddr_t)&req.hdr - (caddr_t)&req;
1322 	req.req.OPT_length = sizeof (req.hdr);
1323 	req.req.MGMT_flags = T_CURRENT;
1324 
1325 	req.hdr.level = MIB2_IP;
1326 	req.hdr.name = 0;
1327 	req.hdr.len = 0;
1328 
1329 	cbuf.buf = (caddr_t)&req;
1330 	cbuf.len = sizeof (req);
1331 
1332 	if (putmsg(ipfd, &cbuf, NULL, 0) == -1) {
1333 		msglog("T_OPTMGMT_REQ putmsg: %s", rip_strerror(errno));
1334 		goto hash_clean;
1335 	}
1336 
1337 	for (;;) {
1338 		cbuf.buf = (caddr_t)&ack;
1339 		cbuf.maxlen = sizeof (ack);
1340 		dbuf.buf = (caddr_t)routes;
1341 		dbuf.maxlen = sizeof (routes);
1342 		flags = 0;
1343 		r = getmsg(ipfd, &cbuf, &dbuf, &flags);
1344 		if (r == -1) {
1345 			msglog("T_OPTMGMT_REQ getmsg: %s", rip_strerror(errno));
1346 			goto hash_clean;
1347 		}
1348 
1349 		if (cbuf.len < sizeof (struct T_optmgmt_ack) ||
1350 		    ack.ack.PRIM_type != T_OPTMGMT_ACK ||
1351 		    ack.ack.MGMT_flags != T_SUCCESS ||
1352 		    ack.ack.OPT_length < sizeof (struct opthdr)) {
1353 			msglog("bad T_OPTMGMT response; len=%d prim=%d "
1354 			    "flags=%d optlen=%d", cbuf.len, ack.ack.PRIM_type,
1355 			    ack.ack.MGMT_flags, ack.ack.OPT_length);
1356 			goto hash_clean;
1357 		}
1358 		/* LINTED */
1359 		rh = (struct opthdr *)((caddr_t)&ack + ack.ack.OPT_offset);
1360 		if (rh->level == 0 && rh->name == 0) {
1361 			break;
1362 		}
1363 		if (rh->level != MIB2_IP || rh->name != MIB2_IP_21) {
1364 			while (r == MOREDATA) {
1365 				r = getmsg(ipfd, NULL, &dbuf, &flags);
1366 			}
1367 			continue;
1368 		}
1369 		break;
1370 	}
1371 
1372 	(void) memset(&rtm, 0, sizeof (rtm));
1373 	(void) memset(&info, 0, sizeof (info));
1374 	(void) memset(&sin_dst, 0, sizeof (sin_dst));
1375 	(void) memset(&sin_gate, 0, sizeof (sin_gate));
1376 	(void) memset(&sin_mask, 0, sizeof (sin_mask));
1377 	(void) memset(&sin_author, 0, sizeof (sin_author));
1378 	sin_dst.sin_family = AF_INET;
1379 	/* LINTED */
1380 	info.rti_info[RTAX_DST] = (struct sockaddr_storage *)&sin_dst;
1381 	sin_gate.sin_family = AF_INET;
1382 	/* LINTED */
1383 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr_storage *)&sin_gate;
1384 	sin_mask.sin_family = AF_INET;
1385 	/* LINTED */
1386 	info.rti_info[RTAX_NETMASK] = (struct sockaddr_storage *)&sin_mask;
1387 	sin_dst.sin_family = AF_INET;
1388 	/* LINTED */
1389 	info.rti_info[RTAX_AUTHOR] = (struct sockaddr_storage *)&sin_author;
1390 
1391 	for (;;) {
1392 		nroutes = dbuf.len / sizeof (mib2_ipRouteEntry_t);
1393 		for (rp = routes; nroutes > 0; ++rp, nroutes--) {
1394 
1395 			/*
1396 			 * Ignore IRE cache, broadcast, and local address
1397 			 * entries; they're not subject to routing socket
1398 			 * control.
1399 			 */
1400 			if (rp->ipRouteInfo.re_ire_type &
1401 			    (IRE_BROADCAST | IRE_CACHE | IRE_LOCAL))
1402 				continue;
1403 
1404 			/* ignore multicast addresses */
1405 			if (IN_MULTICAST(ntohl(rp->ipRouteDest)))
1406 				continue;
1407 
1408 
1409 #ifdef DEBUG_KERNEL_ROUTE_READ
1410 			(void) fprintf(stderr, "route type %d, ire type %08X, "
1411 			    "flags %08X: %s", rp->ipRouteType,
1412 			    rp->ipRouteInfo.re_ire_type,
1413 			    rp->ipRouteInfo.re_flags,
1414 			    naddr_ntoa(rp->ipRouteDest));
1415 			(void) fprintf(stderr, " %s",
1416 			    naddr_ntoa(rp->ipRouteMask));
1417 			(void) fprintf(stderr, " %s\n",
1418 			    naddr_ntoa(rp->ipRouteNextHop));
1419 #endif
1420 
1421 			/* Fake up the needed entries */
1422 			rtm.rtm_flags = rp->ipRouteInfo.re_flags;
1423 			rtm.rtm_type = RTM_GET;
1424 			rtm.rtm_rmx.rmx_hopcount = rp->ipRouteMetric1;
1425 
1426 			(void) memset(ifname, 0, sizeof (ifname));
1427 			if (rp->ipRouteIfIndex.o_length <
1428 			    sizeof (rp->ipRouteIfIndex.o_bytes))
1429 				rp->ipRouteIfIndex.o_bytes[
1430 				    rp->ipRouteIfIndex.o_length] = '\0';
1431 				(void) strncpy(ifname,
1432 				    rp->ipRouteIfIndex.o_bytes,
1433 				    sizeof (ifname));
1434 
1435 			/*
1436 			 * First try to match up on gwkludge entries
1437 			 * before trying to match ifp by name.
1438 			 */
1439 			if ((ifp = gwkludge_iflookup(rp->ipRouteDest,
1440 			    rp->ipRouteNextHop,
1441 			    ntohl(rp->ipRouteMask))) == NULL)
1442 				ifp = ifwithname(ifname);
1443 
1444 			info.rti_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
1445 			if (rp->ipRouteInfo.re_ire_type & IRE_HOST_REDIRECT)
1446 				info.rti_addrs |= RTA_AUTHOR;
1447 			sin_dst.sin_addr.s_addr = rp->ipRouteDest;
1448 			sin_gate.sin_addr.s_addr = rp->ipRouteNextHop;
1449 			sin_mask.sin_addr.s_addr = rp->ipRouteMask;
1450 			sin_author.sin_addr.s_addr =
1451 			    rp->ipRouteInfo.re_src_addr;
1452 
1453 			/*
1454 			 * Note static routes and interface routes, and also
1455 			 * preload the image of the kernel table so that
1456 			 * we can later clean it, as well as avoid making
1457 			 * unneeded changes.  Keep the old kernel routes for a
1458 			 * few seconds to allow a RIP or router-discovery
1459 			 * response to be heard.
1460 			 */
1461 			rtm_add(&rtm, &info, MAX_WAITTIME,
1462 			    ((rp->ipRouteInfo.re_ire_type &
1463 			    (IRE_INTERFACE|IRE_LOOPBACK)) != 0), ifp);
1464 		}
1465 		if (r == 0) {
1466 			break;
1467 		}
1468 		r = getmsg(ipfd, NULL, &dbuf, &flags);
1469 	}
1470 
1471 hash_clean:
1472 	if (ipfd != -1)
1473 		(void) close(ipfd);
1474 	for (i = 0; i < KHASH_SIZE; i++) {
1475 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
1476 
1477 			/*
1478 			 * KS_DELETED routes have been removed from the
1479 			 * kernel, but we keep them around for reasons
1480 			 * stated in del_static(), so we skip the check
1481 			 * for KS_DELETED routes here.
1482 			 */
1483 			if ((k->k_state & (KS_CHECK|KS_DELETED)) == KS_CHECK) {
1484 
1485 				if (!(k->k_state & KS_DYNAMIC))
1486 				    writelog(LOG_WARNING,
1487 					"%s --> %s disappeared from kernel",
1488 					addrname(k->k_dst, k->k_mask, 0),
1489 					naddr_ntoa(k->k_gate));
1490 				del_static(k->k_dst, k->k_mask, k->k_gate,
1491 				    k->k_ifp, 1);
1492 
1493 			}
1494 		}
1495 	}
1496 }
1497 
1498 
1499 /* Listen to announcements from the kernel */
1500 void
1501 read_rt(void)
1502 {
1503 	long cc;
1504 	struct interface *ifp;
1505 	struct sockaddr_in gate_sin;
1506 	in_addr_t mask, gate;
1507 	union {
1508 		struct {
1509 			struct rt_msghdr rtm;
1510 			struct sockaddr_storage addrs[RTA_NUMBITS];
1511 		} r;
1512 		struct if_msghdr ifm;
1513 	} m;
1514 	char str[100], *strp;
1515 	struct rt_addrinfo info;
1516 
1517 
1518 	for (;;) {
1519 		cc = read(rt_sock, &m, sizeof (m));
1520 		if (cc <= 0) {
1521 			if (cc < 0 && errno != EWOULDBLOCK)
1522 				LOGERR("read(rt_sock)");
1523 			return;
1524 		}
1525 
1526 		if (TRACERTS)
1527 			dump_rt_msg("read", &m.r.rtm, cc);
1528 
1529 		if (cc < m.r.rtm.rtm_msglen) {
1530 			msglog("routing message truncated (%d < %d)",
1531 			    cc, m.r.rtm.rtm_msglen);
1532 		}
1533 
1534 		if (m.r.rtm.rtm_version != RTM_VERSION) {
1535 			msglog("bogus routing message version %d",
1536 			    m.r.rtm.rtm_version);
1537 			continue;
1538 		}
1539 
1540 		ifp = NULL;
1541 
1542 		if (m.r.rtm.rtm_type == RTM_IFINFO ||
1543 		    m.r.rtm.rtm_type == RTM_NEWADDR ||
1544 		    m.r.rtm.rtm_type == RTM_DELADDR) {
1545 			strp = if_bit_string(m.ifm.ifm_flags, _B_TRUE);
1546 			if (strp == NULL) {
1547 				strp = str;
1548 				(void) sprintf(str, "%#x", m.ifm.ifm_flags);
1549 			}
1550 			ifp = ifwithindex(m.ifm.ifm_index,
1551 			    m.r.rtm.rtm_type != RTM_DELADDR);
1552 			if (ifp == NULL) {
1553 				char ifname[LIFNAMSIZ], *ifnamep;
1554 
1555 				ifnamep = if_indextoname(m.ifm.ifm_index,
1556 				    ifname);
1557 				if (ifnamep == NULL) {
1558 					trace_act("note %s with flags %s"
1559 					    " for unknown interface index #%d",
1560 					    rtm_type_name(m.r.rtm.rtm_type),
1561 					    strp, m.ifm.ifm_index);
1562 				} else {
1563 					trace_act("note %s with flags %s"
1564 					    " for unknown interface %s",
1565 					    rtm_type_name(m.r.rtm.rtm_type),
1566 					    strp, ifnamep);
1567 				}
1568 			} else {
1569 				trace_act("note %s with flags %s for %s",
1570 				    rtm_type_name(m.r.rtm.rtm_type),
1571 				    strp, ifp->int_name);
1572 			}
1573 			if (strp != str)
1574 				free(strp);
1575 
1576 			/*
1577 			 * After being informed of a change to an interface,
1578 			 * check them all now if the check would otherwise
1579 			 * be a long time from now, if the interface is
1580 			 * not known, or if the interface has been turned
1581 			 * off or on.
1582 			 */
1583 			if (ifscan_timer.tv_sec-now.tv_sec >=
1584 			    CHECK_BAD_INTERVAL || ifp == NULL ||
1585 			    ((ifp->int_if_flags ^ m.ifm.ifm_flags) &
1586 				IFF_UP) != 0)
1587 				ifscan_timer.tv_sec = now.tv_sec;
1588 			continue;
1589 		} else {
1590 			if (m.r.rtm.rtm_index != 0)
1591 				ifp = ifwithindex(m.r.rtm.rtm_index, 1);
1592 		}
1593 
1594 		(void) strlcpy(str, rtm_type_name(m.r.rtm.rtm_type),
1595 		    sizeof (str));
1596 		strp = &str[strlen(str)];
1597 		if (m.r.rtm.rtm_type <= RTM_CHANGE)
1598 			strp += snprintf(strp, sizeof (str) - (strp - str),
1599 			    " from pid %d", (int)m.r.rtm.rtm_pid);
1600 
1601 		/* LINTED */
1602 		(void) rt_xaddrs(&info, (struct sockaddr_storage *)(&m.r.rtm +
1603 		    1), (char *)&m + cc, m.r.rtm.rtm_addrs);
1604 
1605 		if (INFO_DST(&info) == 0) {
1606 			trace_act("ignore %s without dst", str);
1607 			continue;
1608 		}
1609 
1610 		if (INFO_DST(&info)->ss_family != AF_INET) {
1611 			trace_act("ignore %s for AF %d", str,
1612 			    INFO_DST(&info)->ss_family);
1613 			continue;
1614 		}
1615 
1616 		mask = ((INFO_MASK(&info) != 0) ?
1617 		    ntohl(S_ADDR(INFO_MASK(&info))) :
1618 		    (m.r.rtm.rtm_flags & RTF_HOST) ?
1619 		    HOST_MASK : std_mask(S_ADDR(INFO_DST(&info))));
1620 
1621 		strp += snprintf(strp, sizeof (str) - (strp - str), ": %s",
1622 		    addrname(S_ADDR(INFO_DST(&info)), mask, 0));
1623 
1624 		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info))))) {
1625 			trace_act("ignore multicast %s", str);
1626 			continue;
1627 		}
1628 
1629 		if (m.r.rtm.rtm_flags & RTF_LLINFO) {
1630 			trace_act("ignore ARP %s", str);
1631 			continue;
1632 		}
1633 
1634 		if (get_info_gate(&INFO_GATE(&info), &gate_sin)) {
1635 			gate = S_ADDR(INFO_GATE(&info));
1636 			strp += snprintf(strp, sizeof (str) - (strp - str),
1637 			    " --> %s", naddr_ntoa(gate));
1638 		} else {
1639 			gate = 0;
1640 		}
1641 
1642 		if (INFO_AUTHOR(&info) != 0)
1643 			strp += snprintf(strp, sizeof (str) - (strp - str),
1644 			    " by authority of %s",
1645 			    saddr_ntoa(INFO_AUTHOR(&info)));
1646 
1647 		switch (m.r.rtm.rtm_type) {
1648 		case RTM_ADD:
1649 		case RTM_CHANGE:
1650 		case RTM_REDIRECT:
1651 			if (m.r.rtm.rtm_errno != 0) {
1652 				trace_act("ignore %s with \"%s\" error",
1653 				    str, rip_strerror(m.r.rtm.rtm_errno));
1654 			} else {
1655 				trace_act("%s", str);
1656 				rtm_add(&m.r.rtm, &info, 0,
1657 				    !(m.r.rtm.rtm_flags & RTF_GATEWAY) &&
1658 				    m.r.rtm.rtm_type != RTM_REDIRECT, ifp);
1659 
1660 			}
1661 			break;
1662 
1663 		case RTM_DELETE:
1664 			if (m.r.rtm.rtm_errno != 0 &&
1665 			    m.r.rtm.rtm_errno != ESRCH) {
1666 				trace_act("ignore %s with \"%s\" error",
1667 				    str, rip_strerror(m.r.rtm.rtm_errno));
1668 			} else {
1669 				trace_act("%s", str);
1670 				del_static(S_ADDR(INFO_DST(&info)), mask,
1671 				    gate, ifp, 1);
1672 			}
1673 			break;
1674 
1675 		case RTM_LOSING:
1676 			trace_act("%s", str);
1677 			rtm_lose(&m.r.rtm, &info);
1678 			break;
1679 
1680 		default:
1681 			trace_act("ignore %s", str);
1682 			break;
1683 		}
1684 	}
1685 }
1686 
1687 
1688 /*
1689  * Disassemble a routing message.  The result is an array of pointers
1690  * to sockaddr_storage structures stored in the info argument.
1691  *
1692  * ss is a pointer to the beginning of the data following the
1693  * rt_msghdr contained in the routing socket message, which consists
1694  * of a string of concatenated sockaddr structure of different types.
1695  */
1696 static int
1697 rt_xaddrs(struct rt_addrinfo *info,
1698     struct sockaddr_storage *ss,
1699     char *lim,
1700     int addrs)
1701 {
1702 	int retv = 0;
1703 	int i;
1704 	int abit;
1705 	int complaints;
1706 	static int prev_complaints;
1707 
1708 #define	XBAD_AF		0x1
1709 #define	XBAD_SHORT	0x2
1710 #define	XBAD_LONG	0x4
1711 
1712 	(void) memset(info, 0, sizeof (*info));
1713 	info->rti_addrs = addrs;
1714 	complaints = 0;
1715 	for (i = 0, abit = 1; i < RTAX_MAX && (char *)ss < lim;
1716 	    i++, abit <<= 1) {
1717 		if ((addrs & abit) == 0)
1718 			continue;
1719 		info->rti_info[i] = ss;
1720 		/* Horrible interface here */
1721 		switch (ss->ss_family) {
1722 		case AF_UNIX:
1723 			/* LINTED */
1724 			ss = (struct sockaddr_storage *)(
1725 			    (struct sockaddr_un *)ss + 1);
1726 			break;
1727 		case AF_INET:
1728 			/* LINTED */
1729 			ss = (struct sockaddr_storage *)(
1730 			    (struct sockaddr_in *)ss + 1);
1731 			break;
1732 		case AF_LINK:
1733 			/* LINTED */
1734 			ss = (struct sockaddr_storage *)(
1735 			    (struct sockaddr_dl *)ss + 1);
1736 			break;
1737 		case AF_INET6:
1738 			/* LINTED */
1739 			ss = (struct sockaddr_storage *)(
1740 			    (struct sockaddr_in6 *)ss + 1);
1741 			break;
1742 		default:
1743 			if (!(prev_complaints & XBAD_AF))
1744 				writelog(LOG_WARNING,
1745 				    "unknown address family %d "
1746 				    "encountered", ss->ss_family);
1747 			if (complaints & XBAD_AF)
1748 				goto xaddr_done;
1749 			/* LINTED */
1750 			ss = (struct sockaddr_storage *)(
1751 			    (struct sockaddr *)ss + 1);
1752 			complaints |= XBAD_AF;
1753 			info->rti_addrs &= abit - 1;
1754 			addrs = info->rti_addrs;
1755 			retv = -1;
1756 			break;
1757 		}
1758 		if ((char *)ss > lim) {
1759 			if (!(prev_complaints & XBAD_SHORT))
1760 				msglog("sockaddr %d too short by %d "
1761 				    "bytes", i + 1, (char *)ss - lim);
1762 			complaints |= XBAD_SHORT;
1763 			info->rti_info[i] = NULL;
1764 			info->rti_addrs &= abit - 1;
1765 			retv = -1;
1766 			goto xaddr_done;
1767 		}
1768 	}
1769 	if ((char *)ss != lim) {
1770 		if (!(prev_complaints & XBAD_LONG))
1771 			msglog("%d bytes of routing message left over",
1772 			    lim - (char *)ss);
1773 		complaints |= XBAD_LONG;
1774 		retv = -1;
1775 	}
1776 xaddr_done:
1777 	prev_complaints = complaints;
1778 	return (retv);
1779 }
1780 
1781 
1782 /* after aggregating, note routes that belong in the kernel */
1783 static void
1784 kern_out(struct ag_info *ag)
1785 {
1786 	struct khash *k;
1787 
1788 	/*
1789 	 * Do not install bad routes if they are not already present.
1790 	 * This includes routes that had RS_NET_SYN for interfaces that
1791 	 * recently died.
1792 	 */
1793 	if (ag->ag_metric == HOPCNT_INFINITY) {
1794 		k = kern_find(htonl(ag->ag_dst_h), ag->ag_mask,
1795 		    ag->ag_nhop, ag->ag_ifp, NULL);
1796 		if (k == NULL)
1797 			return;
1798 	} else {
1799 		k = kern_add(htonl(ag->ag_dst_h), ag->ag_mask, ag->ag_nhop,
1800 		    ag->ag_ifp);
1801 	}
1802 
1803 	if (k->k_state & KS_NEW) {
1804 		/* will need to add new entry to the kernel table */
1805 		k->k_state = KS_ADD;
1806 		if (ag->ag_state & AGS_GATEWAY)
1807 			k->k_state |= KS_GATEWAY;
1808 		if (ag->ag_state & AGS_IF)
1809 			k->k_state |= KS_IF;
1810 		if (ag->ag_state & AGS_PASSIVE)
1811 			k->k_state |= KS_PASSIVE;
1812 		if (ag->ag_state & AGS_FILE)
1813 			k->k_state |= KS_FILE;
1814 		k->k_gate = ag->ag_nhop;
1815 		k->k_ifp = ag->ag_ifp;
1816 		k->k_metric = ag->ag_metric;
1817 		return;
1818 	}
1819 
1820 	if ((k->k_state & (KS_STATIC|KS_DEPRE_IF)) ||
1821 	    ((k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF)) {
1822 		return;
1823 	}
1824 
1825 	/* modify existing kernel entry if necessary */
1826 	if (k->k_gate == ag->ag_nhop && k->k_ifp == ag->ag_ifp &&
1827 	    k->k_metric != ag->ag_metric) {
1828 			/*
1829 			 * Must delete bad interface routes etc.
1830 			 * to change them.
1831 			 */
1832 			if (k->k_metric == HOPCNT_INFINITY)
1833 				k->k_state |= KS_DEL_ADD;
1834 			k->k_gate = ag->ag_nhop;
1835 			k->k_metric = ag->ag_metric;
1836 			k->k_state |= KS_CHANGE;
1837 	}
1838 
1839 	/*
1840 	 * If the daemon thinks the route should exist, forget
1841 	 * about any redirections.
1842 	 * If the daemon thinks the route should exist, eventually
1843 	 * override manual intervention by the operator.
1844 	 */
1845 	if ((k->k_state & (KS_DYNAMIC | KS_DELETED)) != 0) {
1846 		k->k_state &= ~KS_DYNAMIC;
1847 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1848 	}
1849 
1850 	if ((k->k_state & KS_GATEWAY) && !(ag->ag_state & AGS_GATEWAY)) {
1851 		k->k_state &= ~KS_GATEWAY;
1852 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1853 	} else if (!(k->k_state & KS_GATEWAY) && (ag->ag_state & AGS_GATEWAY)) {
1854 		k->k_state |= KS_GATEWAY;
1855 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1856 	}
1857 
1858 	/*
1859 	 * Deleting-and-adding is necessary to change aspects of a route.
1860 	 * Just delete instead of deleting and then adding a bad route.
1861 	 * Otherwise, we want to keep the route in the kernel.
1862 	 */
1863 	if (k->k_metric == HOPCNT_INFINITY && (k->k_state & KS_DEL_ADD))
1864 		k->k_state |= KS_DELETE;
1865 	else
1866 		k->k_state &= ~KS_DELETE;
1867 #undef RT
1868 }
1869 
1870 /*
1871  * Update our image of the kernel forwarding table using the given
1872  * route from our internal routing table.
1873  */
1874 
1875 /*ARGSUSED1*/
1876 static int
1877 walk_kern(struct radix_node *rn, void *argp)
1878 {
1879 #define	RT ((struct rt_entry *)rn)
1880 	uint8_t metric, pref;
1881 	uint_t ags = 0;
1882 	int i;
1883 	struct rt_spare *rts;
1884 
1885 	/* Do not install synthetic routes */
1886 	if (RT->rt_state & RS_NET_SYN)
1887 		return (0);
1888 
1889 	/*
1890 	 * Do not install static routes here. Only
1891 	 * read_rt->rtm_add->kern_add should install those
1892 	 */
1893 	if ((RT->rt_state & RS_STATIC) &&
1894 	    (RT->rt_spares[0].rts_origin != RO_FILE))
1895 		return (0);
1896 
1897 	/* Do not clobber kernel if this is a route for a dead interface */
1898 	if (RT->rt_state & RS_BADIF)
1899 		return (0);
1900 
1901 	if (!(RT->rt_state & RS_IF)) {
1902 		/* This is an ordinary route, not for an interface. */
1903 
1904 		/*
1905 		 * aggregate, ordinary good routes without regard to
1906 		 * their metric
1907 		 */
1908 		pref = 1;
1909 		ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1910 
1911 		/*
1912 		 * Do not install host routes directly to hosts, to avoid
1913 		 * interfering with ARP entries in the kernel table.
1914 		 */
1915 		if (RT_ISHOST(RT) && ntohl(RT->rt_dst) == RT->rt_gate)
1916 			return (0);
1917 
1918 	} else {
1919 		/*
1920 		 * This is an interface route.
1921 		 * Do not install routes for "external" remote interfaces.
1922 		 */
1923 		if (RT->rt_ifp != NULL && (RT->rt_ifp->int_state & IS_EXTERNAL))
1924 			return (0);
1925 
1926 		/* Interfaces should override received routes. */
1927 		pref = 0;
1928 		ags |= (AGS_IF | AGS_CORS_GATE);
1929 		if (RT->rt_ifp != NULL &&
1930 		    !(RT->rt_ifp->int_if_flags & IFF_LOOPBACK) &&
1931 		    (RT->rt_ifp->int_state & (IS_PASSIVE|IS_ALIAS)) ==
1932 		    IS_PASSIVE) {
1933 			ags |= AGS_PASSIVE;
1934 		}
1935 
1936 		/*
1937 		 * If it is not an interface, or an alias for an interface,
1938 		 * it must be a "gateway."
1939 		 *
1940 		 * If it is a "remote" interface, it is also a "gateway" to
1941 		 * the kernel if is not a alias.
1942 		 */
1943 		if (RT->rt_ifp == NULL || (RT->rt_ifp->int_state & IS_REMOTE)) {
1944 
1945 			ags |= (AGS_GATEWAY | AGS_SUPPRESS);
1946 
1947 			/*
1948 			 * Do not aggregate IS_PASSIVE routes.
1949 			 */
1950 			if (!(RT->rt_ifp->int_state & IS_PASSIVE))
1951 				ags |= AGS_AGGREGATE;
1952 		}
1953 	}
1954 
1955 	metric = RT->rt_metric;
1956 	if (metric == HOPCNT_INFINITY) {
1957 		/* If the route is dead, try hard to aggregate. */
1958 		pref = HOPCNT_INFINITY;
1959 		ags |= (AGS_FINE_GATE | AGS_SUPPRESS);
1960 		ags &= ~(AGS_IF | AGS_CORS_GATE);
1961 	}
1962 
1963 	/*
1964 	 * dump all routes that have the same metric as rt_spares[0]
1965 	 * into the kern_table, to be added to the kernel.
1966 	 */
1967 	for (i = 0; i < RT->rt_num_spares; i++) {
1968 		rts = &RT->rt_spares[i];
1969 
1970 		/* Do not install external routes */
1971 		if (rts->rts_flags & RTS_EXTERNAL)
1972 			continue;
1973 
1974 		if (rts->rts_metric == metric) {
1975 			ag_check(RT->rt_dst, RT->rt_mask,
1976 			    rts->rts_router, rts->rts_ifp, rts->rts_gate,
1977 			    metric, pref, 0, 0,
1978 			    (rts->rts_origin & RO_FILE) ? (ags|AGS_FILE) : ags,
1979 			    kern_out);
1980 		}
1981 	}
1982 	return (0);
1983 #undef RT
1984 }
1985 
1986 
1987 /* Update the kernel table to match the daemon table. */
1988 static void
1989 fix_kern(void)
1990 {
1991 	int i;
1992 	struct khash *k, *pk, *knext;
1993 
1994 
1995 	need_kern = age_timer;
1996 
1997 	/* Walk daemon table, updating the copy of the kernel table. */
1998 	(void) rn_walktree(rhead, walk_kern, NULL);
1999 	ag_flush(0, 0, kern_out);
2000 
2001 	for (i = 0; i < KHASH_SIZE; i++) {
2002 		pk = NULL;
2003 		for (k = khash_bins[i]; k != NULL;  k = knext) {
2004 			knext = k->k_next;
2005 
2006 			/* Do not touch local interface routes */
2007 			if ((k->k_state & KS_DEPRE_IF) ||
2008 			    (k->k_state & (KS_IF|KS_PASSIVE)) == KS_IF) {
2009 				pk = k;
2010 				continue;
2011 			}
2012 
2013 			/* Do not touch static routes */
2014 			if (k->k_state & KS_STATIC) {
2015 				kern_check_static(k, 0);
2016 				pk = k;
2017 				continue;
2018 			}
2019 
2020 			/* check hold on routes deleted by the operator */
2021 			if (k->k_keep > now.tv_sec) {
2022 				/* ensure we check when the hold is over */
2023 				LIM_SEC(need_kern, k->k_keep);
2024 				pk = k;
2025 				continue;
2026 			}
2027 
2028 			if ((k->k_state & KS_DELETE) &&
2029 			    !(k->k_state & KS_DYNAMIC)) {
2030 				if ((k->k_dst == RIP_DEFAULT) &&
2031 				    (k->k_ifp != NULL) &&
2032 				    (kern_alternate(RIP_DEFAULT,
2033 				    k->k_mask, k->k_gate, k->k_ifp,
2034 				    NULL) == NULL))
2035 					rdisc_restore(k->k_ifp);
2036 				kern_ioctl(k, RTM_DELETE, 0);
2037 				if (pk != NULL)
2038 					pk->k_next = knext;
2039 				else
2040 					khash_bins[i] = knext;
2041 				free(k);
2042 				continue;
2043 			}
2044 
2045 			if (k->k_state & KS_DEL_ADD)
2046 				kern_ioctl(k, RTM_DELETE, 0);
2047 
2048 			if (k->k_state & KS_ADD) {
2049 				if ((k->k_dst == RIP_DEFAULT) &&
2050 				    (k->k_ifp != NULL))
2051 					rdisc_suppress(k->k_ifp);
2052 				kern_ioctl(k, RTM_ADD,
2053 				    ((0 != (k->k_state & (KS_GATEWAY |
2054 					KS_DYNAMIC))) ? RTF_GATEWAY : 0));
2055 			} else if (k->k_state & KS_CHANGE) {
2056 				/*
2057 				 * Should be using RTM_CHANGE here, but
2058 				 * since RTM_CHANGE is currently
2059 				 * not multipath-aware, and assumes
2060 				 * that RTF_GATEWAY implies the gateway
2061 				 * of the route for dst has to be
2062 				 * changed, we play safe, and do a del + add.
2063 				 */
2064 				kern_ioctl(k,  RTM_DELETE, 0);
2065 				kern_ioctl(k, RTM_ADD,
2066 				    ((0 != (k->k_state & (KS_GATEWAY |
2067 					KS_DYNAMIC))) ? RTF_GATEWAY : 0));
2068 			}
2069 			k->k_state &= ~(KS_ADD|KS_CHANGE|KS_DEL_ADD);
2070 
2071 			/*
2072 			 * Mark this route to be deleted in the next cycle.
2073 			 * This deletes routes that disappear from the
2074 			 * daemon table, since the normal aging code
2075 			 * will clear the bit for routes that have not
2076 			 * disappeared from the daemon table.
2077 			 */
2078 			k->k_state |= KS_DELETE;
2079 			pk = k;
2080 		}
2081 	}
2082 }
2083 
2084 
2085 /* Delete a static route in the image of the kernel table. */
2086 void
2087 del_static(in_addr_t dst, in_addr_t mask, in_addr_t gate,
2088     struct interface *ifp, int gone)
2089 {
2090 	struct khash *k;
2091 	struct rt_entry *rt;
2092 
2093 	/*
2094 	 * Just mark it in the table to be deleted next time the kernel
2095 	 * table is updated.
2096 	 * If it has already been deleted, mark it as such, and set its
2097 	 * keep-timer so that it will not be deleted again for a while.
2098 	 * This lets the operator delete a route added by the daemon
2099 	 * and add a replacement.
2100 	 */
2101 	k = kern_find(dst, mask, gate, ifp, NULL);
2102 	if (k != NULL && (gate == 0 || k->k_gate == gate)) {
2103 		k->k_state &= ~(KS_STATIC | KS_DYNAMIC | KS_CHECK);
2104 		k->k_state |= KS_DELETE;
2105 		if (gone) {
2106 			k->k_state |= KS_DELETED;
2107 			k->k_keep = now.tv_sec + K_KEEP_LIM;
2108 		}
2109 	}
2110 
2111 	rt = rtget(dst, mask);
2112 	if (rt != NULL && (rt->rt_state & RS_STATIC))
2113 		rtbad(rt, NULL);
2114 }
2115 
2116 
2117 /*
2118  * Delete all routes generated from ICMP Redirects that use a given gateway,
2119  * as well as old redirected routes.
2120  */
2121 void
2122 del_redirects(in_addr_t bad_gate, time_t old)
2123 {
2124 	int i;
2125 	struct khash *k;
2126 	boolean_t dosupply = should_supply(NULL);
2127 
2128 	for (i = 0; i < KHASH_SIZE; i++) {
2129 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
2130 			if (!(k->k_state & KS_DYNAMIC) ||
2131 			    (k->k_state & (KS_STATIC|KS_IF|KS_DEPRE_IF)))
2132 				continue;
2133 
2134 			if (k->k_gate != bad_gate && k->k_redirect_time > old &&
2135 			    !dosupply)
2136 				continue;
2137 
2138 			k->k_state |= KS_DELETE;
2139 			k->k_state &= ~KS_DYNAMIC;
2140 			need_kern.tv_sec = now.tv_sec;
2141 			trace_act("mark redirected %s --> %s for deletion",
2142 			    addrname(k->k_dst, k->k_mask, 0),
2143 			    naddr_ntoa(k->k_gate));
2144 		}
2145 	}
2146 }
2147 
2148 /* Start the daemon tables. */
2149 void
2150 rtinit(void)
2151 {
2152 	int i;
2153 	struct ag_info *ag;
2154 
2155 	/* Initialize the radix trees */
2156 	rn_init();
2157 	(void) rn_inithead((void**)&rhead, 32);
2158 
2159 	/* mark all of the slots in the table free */
2160 	ag_avail = ag_slots;
2161 	for (ag = ag_slots, i = 1; i < NUM_AG_SLOTS; i++) {
2162 		ag->ag_fine = ag+1;
2163 		ag++;
2164 	}
2165 }
2166 
2167 
2168 static struct sockaddr_in dst_sock = {AF_INET};
2169 static struct sockaddr_in mask_sock = {AF_INET};
2170 
2171 
2172 static void
2173 set_need_flash(void)
2174 {
2175 	if (!need_flash) {
2176 		need_flash = _B_TRUE;
2177 		/*
2178 		 * Do not send the flash update immediately.  Wait a little
2179 		 * while to hear from other routers.
2180 		 */
2181 		no_flash.tv_sec = now.tv_sec + MIN_WAITTIME;
2182 	}
2183 }
2184 
2185 
2186 /* Get a particular routing table entry */
2187 struct rt_entry *
2188 rtget(in_addr_t dst, in_addr_t mask)
2189 {
2190 	struct rt_entry *rt;
2191 
2192 	dst_sock.sin_addr.s_addr = dst;
2193 	mask_sock.sin_addr.s_addr = htonl(mask);
2194 	rt = (struct rt_entry *)rhead->rnh_lookup(&dst_sock, &mask_sock, rhead);
2195 	if (rt == NULL || rt->rt_dst != dst || rt->rt_mask != mask)
2196 		return (NULL);
2197 
2198 	return (rt);
2199 }
2200 
2201 
2202 /* Find a route to dst as the kernel would. */
2203 struct rt_entry *
2204 rtfind(in_addr_t dst)
2205 {
2206 	dst_sock.sin_addr.s_addr = dst;
2207 	return ((struct rt_entry *)rhead->rnh_matchaddr(&dst_sock, rhead));
2208 }
2209 
2210 
2211 /* add a route to the table */
2212 void
2213 rtadd(in_addr_t	dst,
2214     in_addr_t	mask,
2215     uint16_t	state,			/* rt_state for the entry */
2216     struct	rt_spare *new)
2217 {
2218 	struct rt_entry *rt;
2219 	in_addr_t smask;
2220 	int i;
2221 	struct rt_spare *rts;
2222 
2223 	/* This is the only function that increments total_routes. */
2224 	if (total_routes == MAX_ROUTES) {
2225 		msglog("have maximum (%d) routes", total_routes);
2226 		return;
2227 	}
2228 
2229 	rt = rtmalloc(sizeof (*rt), "rtadd");
2230 	(void) memset(rt, 0, sizeof (*rt));
2231 	rt->rt_spares = rtmalloc(SPARE_INC  * sizeof (struct rt_spare),
2232 	    "rtadd");
2233 	rt->rt_num_spares = SPARE_INC;
2234 	(void) memset(rt->rt_spares, 0, SPARE_INC  * sizeof (struct rt_spare));
2235 	for (rts = rt->rt_spares, i = rt->rt_num_spares; i != 0; i--, rts++)
2236 		rts->rts_metric = HOPCNT_INFINITY;
2237 
2238 	rt->rt_nodes->rn_key = (uint8_t *)&rt->rt_dst_sock;
2239 	rt->rt_dst = dst;
2240 	rt->rt_dst_sock.sin_family = AF_INET;
2241 	if (mask != HOST_MASK) {
2242 		smask = std_mask(dst);
2243 		if ((smask & ~mask) == 0 && mask > smask)
2244 			state |= RS_SUBNET;
2245 	}
2246 	mask_sock.sin_addr.s_addr = htonl(mask);
2247 	rt->rt_mask = mask;
2248 	rt->rt_spares[0] = *new;
2249 	rt->rt_state = state;
2250 	rt->rt_time = now.tv_sec;
2251 	rt->rt_poison_metric = HOPCNT_INFINITY;
2252 	rt->rt_seqno = update_seqno;
2253 
2254 	if (TRACEACTIONS)
2255 		trace_add_del("Add", rt);
2256 
2257 	need_kern.tv_sec = now.tv_sec;
2258 	set_need_flash();
2259 
2260 	if (NULL == rhead->rnh_addaddr(&rt->rt_dst_sock, &mask_sock, rhead,
2261 	    rt->rt_nodes)) {
2262 		msglog("rnh_addaddr() failed for %s mask=%s",
2263 		    naddr_ntoa(dst), naddr_ntoa(htonl(mask)));
2264 		free(rt);
2265 	}
2266 
2267 	total_routes++;
2268 }
2269 
2270 
2271 /* notice a changed route */
2272 void
2273 rtchange(struct rt_entry *rt,
2274     uint16_t	state,			/* new state bits */
2275     struct rt_spare *new,
2276     char	*label)
2277 {
2278 	if (rt->rt_metric != new->rts_metric) {
2279 		/*
2280 		 * Fix the kernel immediately if it seems the route
2281 		 * has gone bad, since there may be a working route that
2282 		 * aggregates this route.
2283 		 */
2284 		if (new->rts_metric == HOPCNT_INFINITY) {
2285 			need_kern.tv_sec = now.tv_sec;
2286 			if (new->rts_time >= now.tv_sec - EXPIRE_TIME)
2287 				new->rts_time = now.tv_sec - EXPIRE_TIME;
2288 		}
2289 		rt->rt_seqno = update_seqno;
2290 		set_need_flash();
2291 	}
2292 
2293 	if (rt->rt_gate != new->rts_gate) {
2294 		need_kern.tv_sec = now.tv_sec;
2295 		rt->rt_seqno = update_seqno;
2296 		set_need_flash();
2297 	}
2298 
2299 	state |= (rt->rt_state & RS_SUBNET);
2300 
2301 	/* Keep various things from deciding ageless routes are stale. */
2302 	if (!AGE_RT(state, rt->rt_spares[0].rts_origin, new->rts_ifp))
2303 		new->rts_time = now.tv_sec;
2304 
2305 	if (TRACEACTIONS)
2306 		trace_change(rt, state, new,
2307 		    label ? label : "Chg   ");
2308 
2309 	rt->rt_state = state;
2310 	/*
2311 	 * If the interface state of the new primary route is good,
2312 	 * turn off RS_BADIF flag
2313 	 */
2314 	if ((rt->rt_state & RS_BADIF) &&
2315 	    IS_IFF_UP(new->rts_ifp->int_if_flags) &&
2316 	    !(new->rts_ifp->int_state & (IS_BROKE | IS_SICK)))
2317 		rt->rt_state &= ~(RS_BADIF);
2318 
2319 	rt->rt_spares[0] = *new;
2320 }
2321 
2322 
2323 /* check for a better route among the spares */
2324 static struct rt_spare *
2325 rts_better(struct rt_entry *rt)
2326 {
2327 	struct rt_spare *rts, *rts1;
2328 	int i;
2329 
2330 	/* find the best alternative among the spares */
2331 	rts = rt->rt_spares+1;
2332 	for (i = rt->rt_num_spares, rts1 = rts+1; i > 2; i--, rts1++) {
2333 		if (BETTER_LINK(rt, rts1, rts))
2334 			rts = rts1;
2335 	}
2336 
2337 	return (rts);
2338 }
2339 
2340 
2341 /* switch to a backup route */
2342 void
2343 rtswitch(struct rt_entry *rt,
2344     struct rt_spare *rts)
2345 {
2346 	struct rt_spare swap;
2347 	char label[10];
2348 
2349 	/* Do not change permanent routes */
2350 	if (0 != (rt->rt_state & (RS_MHOME | RS_STATIC |
2351 	    RS_NET_SYN | RS_IF)))
2352 		return;
2353 
2354 	/* find the best alternative among the spares */
2355 	if (rts == NULL)
2356 		rts = rts_better(rt);
2357 
2358 	/* Do not bother if it is not worthwhile. */
2359 	if (!BETTER_LINK(rt, rts, rt->rt_spares))
2360 		return;
2361 
2362 	swap = rt->rt_spares[0];
2363 	(void) snprintf(label, sizeof (label), "Use #%d",
2364 	    (int)(rts - rt->rt_spares));
2365 	rtchange(rt, rt->rt_state & ~(RS_NET_SYN), rts, label);
2366 
2367 	if (swap.rts_metric == HOPCNT_INFINITY) {
2368 		*rts = rts_empty;
2369 	} else {
2370 		*rts = swap;
2371 	}
2372 
2373 }
2374 
2375 
2376 void
2377 rtdelete(struct rt_entry *rt)
2378 {
2379 	struct rt_entry *deleted_rt;
2380 	struct rt_spare *rts;
2381 	int i;
2382 	in_addr_t gate = rt->rt_gate; /* for debugging */
2383 
2384 	if (TRACEACTIONS)
2385 		trace_add_del("Del", rt);
2386 
2387 	for (i = 0; i < rt->rt_num_spares; i++) {
2388 		rts = &rt->rt_spares[i];
2389 		rts_delete(rt, rts);
2390 	}
2391 
2392 	dst_sock.sin_addr.s_addr = rt->rt_dst;
2393 	mask_sock.sin_addr.s_addr = htonl(rt->rt_mask);
2394 	if (rt != (deleted_rt =
2395 	    ((struct rt_entry *)rhead->rnh_deladdr(&dst_sock, &mask_sock,
2396 	    rhead)))) {
2397 		msglog("rnh_deladdr(%s) failed; found rt 0x%lx",
2398 		    rtname(rt->rt_dst, rt->rt_mask, gate), deleted_rt);
2399 		if (deleted_rt != NULL)
2400 			free(deleted_rt);
2401 	}
2402 	total_routes--;
2403 	free(rt);
2404 
2405 	if (dst_sock.sin_addr.s_addr == RIP_DEFAULT) {
2406 		/*
2407 		 * we just deleted the default route. Trigger rdisc_sort
2408 		 * so that we can recover from any rdisc information that
2409 		 * is valid
2410 		 */
2411 		rdisc_timer.tv_sec = 0;
2412 	}
2413 }
2414 
2415 void
2416 rts_delete(struct rt_entry *rt, struct rt_spare *rts)
2417 {
2418 	struct khash *k;
2419 
2420 	trace_upslot(rt, rts, &rts_empty);
2421 	k = kern_find(rt->rt_dst, rt->rt_mask,
2422 	    rts->rts_gate, rts->rts_ifp, NULL);
2423 	if (k != NULL &&
2424 	    !(k->k_state & KS_DEPRE_IF) &&
2425 	    ((k->k_state & (KS_IF|KS_PASSIVE)) != KS_IF)) {
2426 		k->k_state |= KS_DELETE;
2427 		need_kern.tv_sec = now.tv_sec;
2428 	}
2429 
2430 	*rts = rts_empty;
2431 }
2432 
2433 /*
2434  * Get rid of a bad route, and try to switch to a replacement.
2435  * If the route has gone bad because of a bad interface,
2436  * the information about the dead interface is available in badifp
2437  * for the purpose of sanity checks, if_flags checks etc.
2438  */
2439 static void
2440 rtbad(struct rt_entry *rt, struct interface *badifp)
2441 {
2442 	struct rt_spare new;
2443 	uint16_t rt_state;
2444 
2445 
2446 	if (badifp == NULL || (rt->rt_spares[0].rts_ifp == badifp)) {
2447 		/* Poison the route */
2448 		new = rt->rt_spares[0];
2449 		new.rts_metric = HOPCNT_INFINITY;
2450 		rt_state = rt->rt_state & ~(RS_IF | RS_LOCAL | RS_STATIC);
2451 	}
2452 
2453 	if (badifp != NULL) {
2454 		/*
2455 		 * Dont mark the rtentry bad unless the ifp for the primary
2456 		 * route is the bad ifp
2457 		 */
2458 		if (rt->rt_spares[0].rts_ifp != badifp)
2459 			return;
2460 		/*
2461 		 * badifp has just gone bad. We want to keep this
2462 		 * rt_entry around so that we tell our rip-neighbors
2463 		 * about the bad route, but we can't do anything
2464 		 * to the kernel itself, so mark it as RS_BADIF
2465 		 */
2466 		trace_misc("rtbad:Setting RS_BADIF (%s)", badifp->int_name);
2467 		rt_state |= RS_BADIF;
2468 		new.rts_ifp = &dummy_ifp;
2469 	}
2470 	rtchange(rt, rt_state, &new, 0);
2471 	rtswitch(rt, 0);
2472 }
2473 
2474 
2475 /*
2476  * Junk a RS_NET_SYN or RS_LOCAL route,
2477  *	unless it is needed by another interface.
2478  */
2479 void
2480 rtbad_sub(struct rt_entry *rt, struct interface *badifp)
2481 {
2482 	struct interface *ifp, *ifp1;
2483 	struct intnet *intnetp;
2484 	uint_t state;
2485 
2486 
2487 	ifp1 = NULL;
2488 	state = 0;
2489 
2490 	if (rt->rt_state & RS_LOCAL) {
2491 		/*
2492 		 * Is this the route through loopback for the interface?
2493 		 * If so, see if it is used by any other interfaces, such
2494 		 * as a point-to-point interface with the same local address.
2495 		 */
2496 		for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2497 			/* Retain it if another interface needs it. */
2498 			if (ifp->int_addr == rt->rt_ifp->int_addr) {
2499 				state |= RS_LOCAL;
2500 				ifp1 = ifp;
2501 				break;
2502 			}
2503 		}
2504 
2505 	}
2506 
2507 	if (!(state & RS_LOCAL)) {
2508 		/*
2509 		 * Retain RIPv1 logical network route if there is another
2510 		 * interface that justifies it.
2511 		 */
2512 		if (rt->rt_state & RS_NET_SYN) {
2513 			for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2514 				if ((ifp->int_state & IS_NEED_NET_SYN) &&
2515 				    rt->rt_mask == ifp->int_std_mask &&
2516 				    rt->rt_dst == ifp->int_std_addr) {
2517 					state |= RS_NET_SYN;
2518 					ifp1 = ifp;
2519 					break;
2520 				}
2521 			}
2522 		}
2523 
2524 		/* or if there is an authority route that needs it. */
2525 		for (intnetp = intnets; intnetp != NULL;
2526 		    intnetp = intnetp->intnet_next) {
2527 			if (intnetp->intnet_addr == rt->rt_dst &&
2528 			    intnetp->intnet_mask == rt->rt_mask) {
2529 				state |= (RS_NET_SYN | RS_NET_INT);
2530 				break;
2531 			}
2532 		}
2533 	}
2534 
2535 	if (ifp1 != NULL || (state & RS_NET_SYN)) {
2536 		struct rt_spare new = rt->rt_spares[0];
2537 		new.rts_ifp = ifp1;
2538 		rtchange(rt, ((rt->rt_state & ~(RS_NET_SYN|RS_LOCAL)) | state),
2539 		    &new, 0);
2540 	} else {
2541 		rtbad(rt, badifp);
2542 	}
2543 }
2544 
2545 /*
2546  * Called while walking the table looking for sick interfaces
2547  * or after a time change.
2548  */
2549 int
2550 walk_bad(struct radix_node *rn,
2551     void *argp)
2552 {
2553 #define	RT ((struct rt_entry *)rn)
2554 	struct rt_spare *rts;
2555 	int i, j = -1;
2556 
2557 	/* fix any spare routes through the interface */
2558 	for (i = 1; i < RT->rt_num_spares; i++) {
2559 		rts = &((struct rt_entry *)rn)->rt_spares[i];
2560 
2561 		if (rts->rts_metric < HOPCNT_INFINITY &&
2562 		    (rts->rts_ifp == NULL ||
2563 		    (rts->rts_ifp->int_state & IS_BROKE)))
2564 			rts_delete(RT, rts);
2565 		else {
2566 			if (rts->rts_origin != RO_NONE)
2567 				j = i;
2568 		}
2569 	}
2570 
2571 	/*
2572 	 * Deal with the main route
2573 	 * finished if it has been handled before or if its interface is ok
2574 	 */
2575 	if (RT->rt_ifp == NULL || !(RT->rt_ifp->int_state & IS_BROKE))
2576 		return (0);
2577 
2578 	/* Bad routes for other than interfaces are easy. */
2579 	if (!(RT->rt_state & (RS_IF | RS_NET_SYN | RS_LOCAL))) {
2580 		if (j > 0) {
2581 			RT->rt_spares[0].rts_metric = HOPCNT_INFINITY;
2582 			rtswitch(RT, NULL);
2583 		} else {
2584 			rtbad(RT, (struct interface *)argp);
2585 		}
2586 		return (0);
2587 	}
2588 
2589 	rtbad_sub(RT, (struct interface *)argp);
2590 	return (0);
2591 #undef RT
2592 }
2593 
2594 /*
2595  * Called while walking the table to replace a duplicate interface
2596  * with a backup.
2597  */
2598 int
2599 walk_rewire(struct radix_node *rn, void *argp)
2600 {
2601 	struct rt_entry *RT = (struct rt_entry *)rn;
2602 	struct rewire_data *wire = (struct rewire_data *)argp;
2603 	struct rt_spare *rts;
2604 	int i;
2605 
2606 	/* fix any spare routes through the interface */
2607 	rts = RT->rt_spares;
2608 	for (i = RT->rt_num_spares; i > 0; i--, rts++) {
2609 		if (rts->rts_ifp == wire->if_old) {
2610 			rts->rts_ifp = wire->if_new;
2611 			if ((RT->rt_dst == RIP_DEFAULT) &&
2612 			    (wire->if_old->int_state & IS_SUPPRESS_RDISC))
2613 				rdisc_suppress(rts->rts_ifp);
2614 			if ((rts->rts_metric += wire->metric_delta) >
2615 			    HOPCNT_INFINITY)
2616 				rts->rts_metric = HOPCNT_INFINITY;
2617 
2618 			/*
2619 			 * If the main route is getting a worse metric,
2620 			 * then it may be time to switch to a backup.
2621 			 */
2622 			if (i == RT->rt_num_spares && wire->metric_delta > 0) {
2623 				rtswitch(RT, NULL);
2624 			}
2625 		}
2626 	}
2627 
2628 	return (0);
2629 }
2630 
2631 /* Check the age of an individual route. */
2632 static int
2633 walk_age(struct radix_node *rn, void *argp)
2634 {
2635 #define	RT ((struct rt_entry *)rn)
2636 	struct interface *ifp;
2637 	struct rt_spare *rts;
2638 	int i;
2639 	in_addr_t age_bad_gate = *(in_addr_t *)argp;
2640 
2641 
2642 	/*
2643 	 * age all of the spare routes, including the primary route
2644 	 * currently in use
2645 	 */
2646 	rts = RT->rt_spares;
2647 	for (i = RT->rt_num_spares; i != 0; i--, rts++) {
2648 
2649 		ifp = rts->rts_ifp;
2650 		if (i == RT->rt_num_spares) {
2651 			if (!AGE_RT(RT->rt_state, rts->rts_origin, ifp)) {
2652 				/*
2653 				 * Keep various things from deciding ageless
2654 				 * routes are stale
2655 				 */
2656 				rts->rts_time = now.tv_sec;
2657 				continue;
2658 			}
2659 
2660 			/* forget RIP routes after RIP has been turned off. */
2661 			if (rip_sock < 0) {
2662 				rts->rts_time = now_stale + 1;
2663 			}
2664 		}
2665 
2666 		/* age failing routes */
2667 		if (age_bad_gate == rts->rts_gate &&
2668 		    rts->rts_time >= now_stale) {
2669 			rts->rts_time -= SUPPLY_INTERVAL;
2670 		}
2671 
2672 		/* trash the spare routes when they go bad */
2673 		if (rts->rts_origin == RO_RIP &&
2674 		    ((rip_sock < 0) ||
2675 		    (rts->rts_metric < HOPCNT_INFINITY &&
2676 		    now_garbage > rts->rts_time)) &&
2677 		    i != RT->rt_num_spares) {
2678 			rts_delete(RT, rts);
2679 		}
2680 	}
2681 
2682 
2683 	/* finished if the active route is still fresh */
2684 	if (now_stale <= RT->rt_time)
2685 		return (0);
2686 
2687 	/* try to switch to an alternative */
2688 	rtswitch(RT, NULL);
2689 
2690 	/* Delete a dead route after it has been publically mourned. */
2691 	if (now_garbage > RT->rt_time) {
2692 		rtdelete(RT);
2693 		return (0);
2694 	}
2695 
2696 	/* Start poisoning a bad route before deleting it. */
2697 	if (now.tv_sec - RT->rt_time > EXPIRE_TIME) {
2698 		struct rt_spare new = RT->rt_spares[0];
2699 
2700 		new.rts_metric = HOPCNT_INFINITY;
2701 		rtchange(RT, RT->rt_state, &new, 0);
2702 	}
2703 	return (0);
2704 }
2705 
2706 
2707 /* Watch for dead routes and interfaces. */
2708 void
2709 age(in_addr_t bad_gate)
2710 {
2711 	struct interface *ifp;
2712 	int need_query = 0;
2713 
2714 	/*
2715 	 * If not listening to RIP, there is no need to age the routes in
2716 	 * the table.
2717 	 */
2718 	age_timer.tv_sec = (now.tv_sec
2719 	    + ((rip_sock < 0) ? NEVER : SUPPLY_INTERVAL));
2720 
2721 	/*
2722 	 * Check for dead IS_REMOTE interfaces by timing their
2723 	 * transmissions.
2724 	 */
2725 	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
2726 		if (!(ifp->int_state & IS_REMOTE))
2727 			continue;
2728 
2729 		/* ignore unreachable remote interfaces */
2730 		if (!check_remote(ifp))
2731 			continue;
2732 
2733 		/* Restore remote interface that has become reachable */
2734 		if (ifp->int_state & IS_BROKE)
2735 			if_ok(ifp, "remote ", _B_FALSE);
2736 
2737 		if (ifp->int_act_time != NEVER &&
2738 		    now.tv_sec - ifp->int_act_time > EXPIRE_TIME) {
2739 			writelog(LOG_NOTICE,
2740 			    "remote interface %s to %s timed out after"
2741 			    " %ld:%ld",
2742 			    ifp->int_name,
2743 			    naddr_ntoa(ifp->int_dstaddr),
2744 			    (now.tv_sec - ifp->int_act_time)/60,
2745 			    (now.tv_sec - ifp->int_act_time)%60);
2746 			if_sick(ifp, _B_FALSE);
2747 		}
2748 
2749 		/*
2750 		 * If we have not heard from the other router
2751 		 * recently, ask it.
2752 		 */
2753 		if (now.tv_sec >= ifp->int_query_time) {
2754 			ifp->int_query_time = NEVER;
2755 			need_query = 1;
2756 		}
2757 	}
2758 
2759 	/* Age routes. */
2760 	(void) rn_walktree(rhead, walk_age, &bad_gate);
2761 
2762 	/*
2763 	 * delete old redirected routes to keep the kernel table small
2764 	 * and prevent blackholes
2765 	 */
2766 	del_redirects(bad_gate, now.tv_sec-STALE_TIME);
2767 
2768 	/* Update the kernel routing table. */
2769 	fix_kern();
2770 
2771 	/* poke reticent remote gateways */
2772 	if (need_query)
2773 		rip_query();
2774 }
2775 
2776 void
2777 kern_dump(void)
2778 {
2779 	int i;
2780 	struct khash *k;
2781 
2782 	for (i = 0; i < KHASH_SIZE; i++) {
2783 		for (k = khash_bins[i]; k != NULL; k = k->k_next)
2784 			trace_khash(k);
2785 	}
2786 }
2787 
2788 
2789 static struct interface *
2790 gwkludge_iflookup(in_addr_t dstaddr, in_addr_t addr, in_addr_t mask)
2791 {
2792 	uint32_t int_state;
2793 	struct interface *ifp;
2794 
2795 	for (ifp = ifnet; ifp != NULL; ifp = ifp->int_next) {
2796 		int_state = ifp->int_state;
2797 
2798 		if (!(int_state & IS_REMOTE))
2799 			continue;
2800 
2801 		if (ifp->int_dstaddr == dstaddr && ifp->int_addr == addr &&
2802 		    ifp->int_mask == mask)
2803 			return (ifp);
2804 	}
2805 	return (NULL);
2806 }
2807