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