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