xref: /freebsd/sbin/routed/table.c (revision d93a896ef95946b0bf1219866fcb324b78543444)
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 		/*
1237 		 * Only messages that use the struct rt_msghdr format are
1238 		 * allowed beyond this point.
1239 		 */
1240 		if (m.r.rtm.rtm_type > RTM_RESOLVE) {
1241 			trace_act("ignore %s", str);
1242 			continue;
1243 		}
1244 
1245 		rt_xaddrs(&info, m.r.addrs, &m.r.addrs[RTAX_MAX],
1246 			  m.r.rtm.rtm_addrs);
1247 
1248 		if (INFO_DST(&info) == 0) {
1249 			trace_act("ignore %s without dst", str);
1250 			continue;
1251 		}
1252 
1253 		if (INFO_DST(&info)->sa_family != AF_INET) {
1254 			trace_act("ignore %s for AF %d", str,
1255 				  INFO_DST(&info)->sa_family);
1256 			continue;
1257 		}
1258 
1259 		mask = ((INFO_MASK(&info) != 0)
1260 			? ntohl(S_ADDR(INFO_MASK(&info)))
1261 			: (m.r.rtm.rtm_flags & RTF_HOST)
1262 			? HOST_MASK
1263 			: std_mask(S_ADDR(INFO_DST(&info))));
1264 
1265 		strp += sprintf(strp, ": %s",
1266 				addrname(S_ADDR(INFO_DST(&info)), mask, 0));
1267 
1268 		if (IN_MULTICAST(ntohl(S_ADDR(INFO_DST(&info))))) {
1269 			trace_act("ignore multicast %s", str);
1270 			continue;
1271 		}
1272 
1273 #if defined(RTF_LLINFO)
1274 		if (m.r.rtm.rtm_flags & RTF_LLINFO) {
1275 			trace_act("ignore ARP %s", str);
1276 			continue;
1277 		}
1278 #endif
1279 
1280 #if defined(RTF_WASCLONED) && defined(__FreeBSD__)
1281 		if (m.r.rtm.rtm_flags & RTF_WASCLONED) {
1282 			trace_act("ignore cloned %s", str);
1283 			continue;
1284 		}
1285 #endif
1286 
1287 		if (get_info_gate(&INFO_GATE(&info), &gate_sin)) {
1288 			gate = S_ADDR(INFO_GATE(&info));
1289 			strp += sprintf(strp, " --> %s", naddr_ntoa(gate));
1290 		} else {
1291 			gate = 0;
1292 		}
1293 
1294 		if (INFO_AUTHOR(&info) != 0)
1295 			strp += sprintf(strp, " by authority of %s",
1296 					saddr_ntoa(INFO_AUTHOR(&info)));
1297 
1298 		switch (m.r.rtm.rtm_type) {
1299 		case RTM_ADD:
1300 		case RTM_CHANGE:
1301 		case RTM_REDIRECT:
1302 			if (m.r.rtm.rtm_errno != 0) {
1303 				trace_act("ignore %s with \"%s\" error",
1304 					  str, strerror(m.r.rtm.rtm_errno));
1305 			} else {
1306 				trace_act("%s", str);
1307 				rtm_add(&m.r.rtm,&info,0);
1308 			}
1309 			break;
1310 
1311 		case RTM_DELETE:
1312 			if (m.r.rtm.rtm_errno != 0
1313 			    && m.r.rtm.rtm_errno != ESRCH) {
1314 				trace_act("ignore %s with \"%s\" error",
1315 					  str, strerror(m.r.rtm.rtm_errno));
1316 			} else {
1317 				trace_act("%s", str);
1318 				del_static(S_ADDR(INFO_DST(&info)), mask,
1319 					   gate, 1);
1320 			}
1321 			break;
1322 
1323 		case RTM_LOSING:
1324 			trace_act("%s", str);
1325 			rtm_lose(&m.r.rtm,&info);
1326 			break;
1327 
1328 		default:
1329 			trace_act("ignore %s", str);
1330 			break;
1331 		}
1332 	}
1333 }
1334 
1335 
1336 /* after aggregating, note routes that belong in the kernel
1337  */
1338 static void
1339 kern_out(struct ag_info *ag)
1340 {
1341 	struct khash *k;
1342 
1343 
1344 	/* Do not install bad routes if they are not already present.
1345 	 * This includes routes that had RS_NET_SYN for interfaces that
1346 	 * recently died.
1347 	 */
1348 	if (ag->ag_metric == HOPCNT_INFINITY) {
1349 		k = kern_find(htonl(ag->ag_dst_h), ag->ag_mask, 0);
1350 		if (k == NULL)
1351 			return;
1352 	} else {
1353 		k = kern_add(htonl(ag->ag_dst_h), ag->ag_mask);
1354 	}
1355 
1356 	if (k->k_state & KS_NEW) {
1357 		/* will need to add new entry to the kernel table */
1358 		k->k_state = KS_ADD;
1359 		if (ag->ag_state & AGS_GATEWAY)
1360 			k->k_state |= KS_GATEWAY;
1361 		k->k_gate = ag->ag_gate;
1362 		k->k_metric = ag->ag_metric;
1363 		return;
1364 	}
1365 
1366 	if (k->k_state & KS_STATIC)
1367 		return;
1368 
1369 	/* modify existing kernel entry if necessary */
1370 	if (k->k_gate != ag->ag_gate
1371 	    || k->k_metric != ag->ag_metric) {
1372 		/* Must delete bad interface routes etc. to change them. */
1373 		if (k->k_metric == HOPCNT_INFINITY)
1374 			k->k_state |= KS_DEL_ADD;
1375 		k->k_gate = ag->ag_gate;
1376 		k->k_metric = ag->ag_metric;
1377 		k->k_state |= KS_CHANGE;
1378 	}
1379 
1380 	/* If the daemon thinks the route should exist, forget
1381 	 * about any redirections.
1382 	 * If the daemon thinks the route should exist, eventually
1383 	 * override manual intervention by the operator.
1384 	 */
1385 	if ((k->k_state & (KS_DYNAMIC | KS_DELETED)) != 0) {
1386 		k->k_state &= ~KS_DYNAMIC;
1387 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1388 	}
1389 
1390 	if ((k->k_state & KS_GATEWAY)
1391 	    && !(ag->ag_state & AGS_GATEWAY)) {
1392 		k->k_state &= ~KS_GATEWAY;
1393 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1394 	} else if (!(k->k_state & KS_GATEWAY)
1395 		   && (ag->ag_state & AGS_GATEWAY)) {
1396 		k->k_state |= KS_GATEWAY;
1397 		k->k_state |= (KS_ADD | KS_DEL_ADD);
1398 	}
1399 
1400 	/* Deleting-and-adding is necessary to change aspects of a route.
1401 	 * Just delete instead of deleting and then adding a bad route.
1402 	 * Otherwise, we want to keep the route in the kernel.
1403 	 */
1404 	if (k->k_metric == HOPCNT_INFINITY
1405 	    && (k->k_state & KS_DEL_ADD))
1406 		k->k_state |= KS_DELETE;
1407 	else
1408 		k->k_state &= ~KS_DELETE;
1409 #undef RT
1410 }
1411 
1412 
1413 /* ARGSUSED */
1414 static int
1415 walk_kern(struct radix_node *rn,
1416 	  struct walkarg *argp UNUSED)
1417 {
1418 #define RT ((struct rt_entry *)rn)
1419 	char metric, pref;
1420 	u_int ags = 0;
1421 
1422 
1423 	/* Do not install synthetic routes */
1424 	if (RT->rt_state & RS_NET_SYN)
1425 		return 0;
1426 
1427 	if (!(RT->rt_state & RS_IF)) {
1428 		/* This is an ordinary route, not for an interface.
1429 		 */
1430 
1431 		/* aggregate, ordinary good routes without regard to
1432 		 * their metric
1433 		 */
1434 		pref = 1;
1435 		ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1436 
1437 		/* Do not install host routes directly to hosts, to avoid
1438 		 * interfering with ARP entries in the kernel table.
1439 		 */
1440 		if (RT_ISHOST(RT)
1441 		    && ntohl(RT->rt_dst) == RT->rt_gate)
1442 			return 0;
1443 
1444 	} else {
1445 		/* This is an interface route.
1446 		 * Do not install routes for "external" remote interfaces.
1447 		 */
1448 		if (RT->rt_ifp != 0 && (RT->rt_ifp->int_state & IS_EXTERNAL))
1449 			return 0;
1450 
1451 		/* Interfaces should override received routes.
1452 		 */
1453 		pref = 0;
1454 		ags |= (AGS_IF | AGS_CORS_GATE);
1455 
1456 		/* If it is not an interface, or an alias for an interface,
1457 		 * it must be a "gateway."
1458 		 *
1459 		 * If it is a "remote" interface, it is also a "gateway" to
1460 		 * the kernel if is not an alias.
1461 		 */
1462 		if (RT->rt_ifp == 0
1463 		    || (RT->rt_ifp->int_state & IS_REMOTE))
1464 			ags |= (AGS_GATEWAY | AGS_SUPPRESS | AGS_AGGREGATE);
1465 	}
1466 
1467 	/* If RIP is off and IRDP is on, let the route to the discovered
1468 	 * route suppress any RIP routes.  Eventually the RIP routes
1469 	 * will time-out and be deleted.  This reaches the steady-state
1470 	 * quicker.
1471 	 */
1472 	if ((RT->rt_state & RS_RDISC) && rip_sock < 0)
1473 		ags |= AGS_CORS_GATE;
1474 
1475 	metric = RT->rt_metric;
1476 	if (metric == HOPCNT_INFINITY) {
1477 		/* if the route is dead, so try hard to aggregate. */
1478 		pref = HOPCNT_INFINITY;
1479 		ags |= (AGS_FINE_GATE | AGS_SUPPRESS);
1480 		ags &= ~(AGS_IF | AGS_CORS_GATE);
1481 	}
1482 
1483 	ag_check(RT->rt_dst, RT->rt_mask, RT->rt_gate, 0,
1484 		 metric,pref, 0, 0, ags, kern_out);
1485 	return 0;
1486 #undef RT
1487 }
1488 
1489 
1490 /* Update the kernel table to match the daemon table.
1491  */
1492 static void
1493 fix_kern(void)
1494 {
1495 	int i;
1496 	struct khash *k, **pk;
1497 
1498 
1499 	need_kern = age_timer;
1500 
1501 	/* Walk daemon table, updating the copy of the kernel table.
1502 	 */
1503 	(void)rn_walktree(rhead, walk_kern, 0);
1504 	ag_flush(0,0,kern_out);
1505 
1506 	for (i = 0; i < KHASH_SIZE; i++) {
1507 		for (pk = &khash_bins[i]; (k = *pk) != NULL; ) {
1508 			/* Do not touch static routes */
1509 			if (k->k_state & KS_STATIC) {
1510 				kern_check_static(k,0);
1511 				pk = &k->k_next;
1512 				continue;
1513 			}
1514 
1515 			/* check hold on routes deleted by the operator */
1516 			if (k->k_keep > now.tv_sec) {
1517 				/* ensure we check when the hold is over */
1518 				LIM_SEC(need_kern, k->k_keep);
1519 				/* mark for the next cycle */
1520 				k->k_state |= KS_DELETE;
1521 				pk = &k->k_next;
1522 				continue;
1523 			}
1524 
1525 			if ((k->k_state & KS_DELETE)
1526 			    && !(k->k_state & KS_DYNAMIC)) {
1527 				kern_ioctl(k, RTM_DELETE, 0);
1528 				*pk = k->k_next;
1529 				free(k);
1530 				continue;
1531 			}
1532 
1533 			if (k->k_state & KS_DEL_ADD)
1534 				kern_ioctl(k, RTM_DELETE, 0);
1535 
1536 			if (k->k_state & KS_ADD) {
1537 				kern_ioctl(k, RTM_ADD,
1538 					   ((0 != (k->k_state & (KS_GATEWAY
1539 							| KS_DYNAMIC)))
1540 					    ? RTF_GATEWAY : 0));
1541 			} else if (k->k_state & KS_CHANGE) {
1542 				kern_ioctl(k,  RTM_CHANGE,
1543 					   ((0 != (k->k_state & (KS_GATEWAY
1544 							| KS_DYNAMIC)))
1545 					    ? RTF_GATEWAY : 0));
1546 			}
1547 			k->k_state &= ~(KS_ADD|KS_CHANGE|KS_DEL_ADD);
1548 
1549 			/* Mark this route to be deleted in the next cycle.
1550 			 * This deletes routes that disappear from the
1551 			 * daemon table, since the normal aging code
1552 			 * will clear the bit for routes that have not
1553 			 * disappeared from the daemon table.
1554 			 */
1555 			k->k_state |= KS_DELETE;
1556 			pk = &k->k_next;
1557 		}
1558 	}
1559 }
1560 
1561 
1562 /* Delete a static route in the image of the kernel table.
1563  */
1564 void
1565 del_static(naddr dst,
1566 	   naddr mask,
1567 	   naddr gate,
1568 	   int gone)
1569 {
1570 	struct khash *k;
1571 	struct rt_entry *rt;
1572 
1573 	/* Just mark it in the table to be deleted next time the kernel
1574 	 * table is updated.
1575 	 * If it has already been deleted, mark it as such, and set its
1576 	 * keep-timer so that it will not be deleted again for a while.
1577 	 * This lets the operator delete a route added by the daemon
1578 	 * and add a replacement.
1579 	 */
1580 	k = kern_find(dst, mask, 0);
1581 	if (k != NULL && (gate == 0 || k->k_gate == gate)) {
1582 		k->k_state &= ~(KS_STATIC | KS_DYNAMIC | KS_CHECK);
1583 		k->k_state |= KS_DELETE;
1584 		if (gone) {
1585 			k->k_state |= KS_DELETED;
1586 			k->k_keep = now.tv_sec + K_KEEP_LIM;
1587 		}
1588 	}
1589 
1590 	rt = rtget(dst, mask);
1591 	if (rt != NULL && (rt->rt_state & RS_STATIC))
1592 		rtbad(rt);
1593 }
1594 
1595 
1596 /* Delete all routes generated from ICMP Redirects that use a given gateway,
1597  * as well as old redirected routes.
1598  */
1599 void
1600 del_redirects(naddr bad_gate,
1601 	      time_t old)
1602 {
1603 	int i;
1604 	struct khash *k;
1605 
1606 
1607 	for (i = 0; i < KHASH_SIZE; i++) {
1608 		for (k = khash_bins[i]; k != NULL; k = k->k_next) {
1609 			if (!(k->k_state & KS_DYNAMIC)
1610 			    || (k->k_state & KS_STATIC))
1611 				continue;
1612 
1613 			if (k->k_gate != bad_gate
1614 			    && k->k_redirect_time > old
1615 			    && !supplier)
1616 				continue;
1617 
1618 			k->k_state |= KS_DELETE;
1619 			k->k_state &= ~KS_DYNAMIC;
1620 			need_kern.tv_sec = now.tv_sec;
1621 			trace_act("mark redirected %s --> %s for deletion",
1622 				  addrname(k->k_dst, k->k_mask, 0),
1623 				  naddr_ntoa(k->k_gate));
1624 		}
1625 	}
1626 }
1627 
1628 
1629 /* Start the daemon tables.
1630  */
1631 extern int max_keylen;
1632 
1633 void
1634 rtinit(void)
1635 {
1636 	int i;
1637 	struct ag_info *ag;
1638 
1639 	/* Initialize the radix trees */
1640 	max_keylen = sizeof(struct sockaddr_in);
1641 	rn_init();
1642 	rn_inithead(&rhead, 32);
1643 
1644 	/* mark all of the slots in the table free */
1645 	ag_avail = ag_slots;
1646 	for (ag = ag_slots, i = 1; i < NUM_AG_SLOTS; i++) {
1647 		ag->ag_fine = ag+1;
1648 		ag++;
1649 	}
1650 }
1651 
1652 
1653 #ifdef _HAVE_SIN_LEN
1654 static struct sockaddr_in dst_sock = {sizeof(dst_sock), AF_INET, 0, {0}, {0}};
1655 static struct sockaddr_in mask_sock = {sizeof(mask_sock), AF_INET, 0, {0}, {0}};
1656 #else
1657 static struct sockaddr_in_new dst_sock = {_SIN_ADDR_SIZE, AF_INET};
1658 static struct sockaddr_in_new mask_sock = {_SIN_ADDR_SIZE, AF_INET};
1659 #endif
1660 
1661 
1662 static void
1663 set_need_flash(void)
1664 {
1665 	if (!need_flash) {
1666 		need_flash = 1;
1667 		/* Do not send the flash update immediately.  Wait a little
1668 		 * while to hear from other routers.
1669 		 */
1670 		no_flash.tv_sec = now.tv_sec + MIN_WAITTIME;
1671 	}
1672 }
1673 
1674 
1675 /* Get a particular routing table entry
1676  */
1677 struct rt_entry *
1678 rtget(naddr dst, naddr mask)
1679 {
1680 	struct rt_entry *rt;
1681 
1682 	dst_sock.sin_addr.s_addr = dst;
1683 	mask_sock.sin_addr.s_addr = htonl(mask);
1684 	masktrim(&mask_sock);
1685 	rt = (struct rt_entry *)rhead->rnh_lookup(&dst_sock,&mask_sock,rhead);
1686 	if (!rt
1687 	    || rt->rt_dst != dst
1688 	    || rt->rt_mask != mask)
1689 		return 0;
1690 
1691 	return rt;
1692 }
1693 
1694 
1695 /* Find a route to dst as the kernel would.
1696  */
1697 struct rt_entry *
1698 rtfind(naddr dst)
1699 {
1700 	dst_sock.sin_addr.s_addr = dst;
1701 	return (struct rt_entry *)rhead->rnh_matchaddr(&dst_sock, rhead);
1702 }
1703 
1704 
1705 /* add a route to the table
1706  */
1707 void
1708 rtadd(naddr	dst,
1709       naddr	mask,
1710       u_int	state,			/* rt_state for the entry */
1711       struct	rt_spare *new)
1712 {
1713 	struct rt_entry *rt;
1714 	naddr smask;
1715 	int i;
1716 	struct rt_spare *rts;
1717 
1718 	rt = (struct rt_entry *)rtmalloc(sizeof (*rt), "rtadd");
1719 	memset(rt, 0, sizeof(*rt));
1720 	for (rts = rt->rt_spares, i = NUM_SPARES; i != 0; i--, rts++)
1721 		rts->rts_metric = HOPCNT_INFINITY;
1722 
1723 	rt->rt_nodes->rn_key = (caddr_t)&rt->rt_dst_sock;
1724 	rt->rt_dst = dst;
1725 	rt->rt_dst_sock.sin_family = AF_INET;
1726 #ifdef _HAVE_SIN_LEN
1727 	rt->rt_dst_sock.sin_len = dst_sock.sin_len;
1728 #endif
1729 	if (mask != HOST_MASK) {
1730 		smask = std_mask(dst);
1731 		if ((smask & ~mask) == 0 && mask > smask)
1732 			state |= RS_SUBNET;
1733 	}
1734 	mask_sock.sin_addr.s_addr = htonl(mask);
1735 	masktrim(&mask_sock);
1736 	rt->rt_mask = mask;
1737 	rt->rt_state = state;
1738 	rt->rt_spares[0] = *new;
1739 	rt->rt_time = now.tv_sec;
1740 	rt->rt_poison_metric = HOPCNT_INFINITY;
1741 	rt->rt_seqno = update_seqno;
1742 
1743 	if (++total_routes == MAX_ROUTES)
1744 		msglog("have maximum (%d) routes", total_routes);
1745 	if (TRACEACTIONS)
1746 		trace_add_del("Add", rt);
1747 
1748 	need_kern.tv_sec = now.tv_sec;
1749 	set_need_flash();
1750 
1751 	if (0 == rhead->rnh_addaddr(&rt->rt_dst_sock, &mask_sock,
1752 				    rhead, rt->rt_nodes)) {
1753 		msglog("rnh_addaddr() failed for %s mask=%#lx",
1754 		       naddr_ntoa(dst), (u_long)mask);
1755 		free(rt);
1756 	}
1757 }
1758 
1759 
1760 /* notice a changed route
1761  */
1762 void
1763 rtchange(struct rt_entry *rt,
1764 	 u_int	state,			/* new state bits */
1765 	 struct rt_spare *new,
1766 	 char	*label)
1767 {
1768 	if (rt->rt_metric != new->rts_metric) {
1769 		/* Fix the kernel immediately if it seems the route
1770 		 * has gone bad, since there may be a working route that
1771 		 * aggregates this route.
1772 		 */
1773 		if (new->rts_metric == HOPCNT_INFINITY) {
1774 			need_kern.tv_sec = now.tv_sec;
1775 			if (new->rts_time >= now.tv_sec - EXPIRE_TIME)
1776 				new->rts_time = now.tv_sec - EXPIRE_TIME;
1777 		}
1778 		rt->rt_seqno = update_seqno;
1779 		set_need_flash();
1780 	}
1781 
1782 	if (rt->rt_gate != new->rts_gate) {
1783 		need_kern.tv_sec = now.tv_sec;
1784 		rt->rt_seqno = update_seqno;
1785 		set_need_flash();
1786 	}
1787 
1788 	state |= (rt->rt_state & RS_SUBNET);
1789 
1790 	/* Keep various things from deciding ageless routes are stale.
1791 	 */
1792 	if (!AGE_RT(state, new->rts_ifp))
1793 		new->rts_time = now.tv_sec;
1794 
1795 	if (TRACEACTIONS)
1796 		trace_change(rt, state, new,
1797 			     label ? label : "Chg   ");
1798 
1799 	rt->rt_state = state;
1800 	rt->rt_spares[0] = *new;
1801 }
1802 
1803 
1804 /* check for a better route among the spares
1805  */
1806 static struct rt_spare *
1807 rts_better(struct rt_entry *rt)
1808 {
1809 	struct rt_spare *rts, *rts1;
1810 	int i;
1811 
1812 	/* find the best alternative among the spares */
1813 	rts = rt->rt_spares+1;
1814 	for (i = NUM_SPARES, rts1 = rts+1; i > 2; i--, rts1++) {
1815 		if (BETTER_LINK(rt,rts1,rts))
1816 			rts = rts1;
1817 	}
1818 
1819 	return rts;
1820 }
1821 
1822 
1823 /* switch to a backup route
1824  */
1825 void
1826 rtswitch(struct rt_entry *rt,
1827 	 struct rt_spare *rts)
1828 {
1829 	struct rt_spare swap;
1830 	char label[10];
1831 
1832 
1833 	/* Do not change permanent routes */
1834 	if (0 != (rt->rt_state & (RS_MHOME | RS_STATIC | RS_RDISC
1835 				  | RS_NET_SYN | RS_IF)))
1836 		return;
1837 
1838 	/* find the best alternative among the spares */
1839 	if (rts == NULL)
1840 		rts = rts_better(rt);
1841 
1842 	/* Do not bother if it is not worthwhile.
1843 	 */
1844 	if (!BETTER_LINK(rt, rts, rt->rt_spares))
1845 		return;
1846 
1847 	swap = rt->rt_spares[0];
1848 	(void)sprintf(label, "Use #%d", (int)(rts - rt->rt_spares));
1849 	rtchange(rt, rt->rt_state & ~(RS_NET_SYN | RS_RDISC), rts, label);
1850 	if (swap.rts_metric == HOPCNT_INFINITY) {
1851 		*rts = rts_empty;
1852 	} else {
1853 		*rts = swap;
1854 	}
1855 }
1856 
1857 
1858 void
1859 rtdelete(struct rt_entry *rt)
1860 {
1861 	struct khash *k;
1862 
1863 
1864 	if (TRACEACTIONS)
1865 		trace_add_del("Del", rt);
1866 
1867 	k = kern_find(rt->rt_dst, rt->rt_mask, 0);
1868 	if (k != NULL) {
1869 		k->k_state |= KS_DELETE;
1870 		need_kern.tv_sec = now.tv_sec;
1871 	}
1872 
1873 	dst_sock.sin_addr.s_addr = rt->rt_dst;
1874 	mask_sock.sin_addr.s_addr = htonl(rt->rt_mask);
1875 	masktrim(&mask_sock);
1876 	if (rt != (struct rt_entry *)rhead->rnh_deladdr(&dst_sock, &mask_sock,
1877 							rhead)) {
1878 		msglog("rnh_deladdr() failed");
1879 	} else {
1880 		free(rt);
1881 		total_routes--;
1882 	}
1883 }
1884 
1885 
1886 void
1887 rts_delete(struct rt_entry *rt,
1888 	   struct rt_spare *rts)
1889 {
1890 	trace_upslot(rt, rts, &rts_empty);
1891 	*rts = rts_empty;
1892 }
1893 
1894 
1895 /* Get rid of a bad route, and try to switch to a replacement.
1896  */
1897 static void
1898 rtbad(struct rt_entry *rt)
1899 {
1900 	struct rt_spare new;
1901 
1902 	/* Poison the route */
1903 	new = rt->rt_spares[0];
1904 	new.rts_metric = HOPCNT_INFINITY;
1905 	rtchange(rt, rt->rt_state & ~(RS_IF | RS_LOCAL | RS_STATIC), &new, 0);
1906 	rtswitch(rt, 0);
1907 }
1908 
1909 
1910 /* Junk a RS_NET_SYN or RS_LOCAL route,
1911  *	unless it is needed by another interface.
1912  */
1913 void
1914 rtbad_sub(struct rt_entry *rt)
1915 {
1916 	struct interface *ifp, *ifp1;
1917 	struct intnet *intnetp;
1918 	u_int state;
1919 
1920 
1921 	ifp1 = NULL;
1922 	state = 0;
1923 
1924 	if (rt->rt_state & RS_LOCAL) {
1925 		/* Is this the route through loopback for the interface?
1926 		 * If so, see if it is used by any other interfaces, such
1927 		 * as a point-to-point interface with the same local address.
1928 		 */
1929 		LIST_FOREACH(ifp, &ifnet, int_list) {
1930 			/* Retain it if another interface needs it.
1931 			 */
1932 			if (ifp->int_addr == rt->rt_ifp->int_addr) {
1933 				state |= RS_LOCAL;
1934 				ifp1 = ifp;
1935 				break;
1936 			}
1937 		}
1938 
1939 	}
1940 
1941 	if (!(state & RS_LOCAL)) {
1942 		/* Retain RIPv1 logical network route if there is another
1943 		 * interface that justifies it.
1944 		 */
1945 		if (rt->rt_state & RS_NET_SYN) {
1946 			LIST_FOREACH(ifp, &ifnet, int_list) {
1947 				if ((ifp->int_state & IS_NEED_NET_SYN)
1948 				    && rt->rt_mask == ifp->int_std_mask
1949 				    && rt->rt_dst == ifp->int_std_addr) {
1950 					state |= RS_NET_SYN;
1951 					ifp1 = ifp;
1952 					break;
1953 				}
1954 			}
1955 		}
1956 
1957 		/* or if there is an authority route that needs it. */
1958 		for (intnetp = intnets;
1959 		     intnetp != NULL;
1960 		     intnetp = intnetp->intnet_next) {
1961 			if (intnetp->intnet_addr == rt->rt_dst
1962 			    && intnetp->intnet_mask == rt->rt_mask) {
1963 				state |= (RS_NET_SYN | RS_NET_INT);
1964 				break;
1965 			}
1966 		}
1967 	}
1968 
1969 	if (ifp1 != NULL || (state & RS_NET_SYN)) {
1970 		struct rt_spare new = rt->rt_spares[0];
1971 		new.rts_ifp = ifp1;
1972 		rtchange(rt, ((rt->rt_state & ~(RS_NET_SYN|RS_LOCAL)) | state),
1973 			 &new, 0);
1974 	} else {
1975 		rtbad(rt);
1976 	}
1977 }
1978 
1979 
1980 /* Called while walking the table looking for sick interfaces
1981  * or after a time change.
1982  */
1983 /* ARGSUSED */
1984 int
1985 walk_bad(struct radix_node *rn,
1986 	 struct walkarg *argp UNUSED)
1987 {
1988 #define RT ((struct rt_entry *)rn)
1989 	struct rt_spare *rts;
1990 	int i;
1991 
1992 
1993 	/* fix any spare routes through the interface
1994 	 */
1995 	rts = RT->rt_spares;
1996 	for (i = NUM_SPARES; i != 1; i--) {
1997 		rts++;
1998 		if (rts->rts_metric < HOPCNT_INFINITY
1999 		    && (rts->rts_ifp == NULL
2000 			|| (rts->rts_ifp->int_state & IS_BROKE)))
2001 			rts_delete(RT, rts);
2002 	}
2003 
2004 	/* Deal with the main route
2005 	 */
2006 	/* finished if it has been handled before or if its interface is ok
2007 	 */
2008 	if (RT->rt_ifp == 0 || !(RT->rt_ifp->int_state & IS_BROKE))
2009 		return 0;
2010 
2011 	/* Bad routes for other than interfaces are easy.
2012 	 */
2013 	if (0 == (RT->rt_state & (RS_IF | RS_NET_SYN | RS_LOCAL))) {
2014 		rtbad(RT);
2015 		return 0;
2016 	}
2017 
2018 	rtbad_sub(RT);
2019 	return 0;
2020 #undef RT
2021 }
2022 
2023 
2024 /* Check the age of an individual route.
2025  */
2026 /* ARGSUSED */
2027 static int
2028 walk_age(struct radix_node *rn,
2029 	   struct walkarg *argp UNUSED)
2030 {
2031 #define RT ((struct rt_entry *)rn)
2032 	struct interface *ifp;
2033 	struct rt_spare *rts;
2034 	int i;
2035 
2036 
2037 	/* age all of the spare routes, including the primary route
2038 	 * currently in use
2039 	 */
2040 	rts = RT->rt_spares;
2041 	for (i = NUM_SPARES; i != 0; i--, rts++) {
2042 
2043 		ifp = rts->rts_ifp;
2044 		if (i == NUM_SPARES) {
2045 			if (!AGE_RT(RT->rt_state, ifp)) {
2046 				/* Keep various things from deciding ageless
2047 				 * routes are stale
2048 				 */
2049 				rts->rts_time = now.tv_sec;
2050 				continue;
2051 			}
2052 
2053 			/* forget RIP routes after RIP has been turned off.
2054 			 */
2055 			if (rip_sock < 0) {
2056 				rtdelete(RT);
2057 				return 0;
2058 			}
2059 		}
2060 
2061 		/* age failing routes
2062 		 */
2063 		if (age_bad_gate == rts->rts_gate
2064 		    && rts->rts_time >= now_stale) {
2065 			rts->rts_time -= SUPPLY_INTERVAL;
2066 		}
2067 
2068 		/* trash the spare routes when they go bad */
2069 		if (rts->rts_metric < HOPCNT_INFINITY
2070 		    && now_garbage > rts->rts_time
2071 		    && i != NUM_SPARES)
2072 			rts_delete(RT, rts);
2073 	}
2074 
2075 
2076 	/* finished if the active route is still fresh */
2077 	if (now_stale <= RT->rt_time)
2078 		return 0;
2079 
2080 	/* try to switch to an alternative */
2081 	rtswitch(RT, 0);
2082 
2083 	/* Delete a dead route after it has been publicly mourned. */
2084 	if (now_garbage > RT->rt_time) {
2085 		rtdelete(RT);
2086 		return 0;
2087 	}
2088 
2089 	/* Start poisoning a bad route before deleting it. */
2090 	if (now.tv_sec - RT->rt_time > EXPIRE_TIME) {
2091 		struct rt_spare new = RT->rt_spares[0];
2092 		new.rts_metric = HOPCNT_INFINITY;
2093 		rtchange(RT, RT->rt_state, &new, 0);
2094 	}
2095 	return 0;
2096 }
2097 
2098 
2099 /* Watch for dead routes and interfaces.
2100  */
2101 void
2102 age(naddr bad_gate)
2103 {
2104 	struct interface *ifp;
2105 	int need_query = 0;
2106 
2107 	/* If not listening to RIP, there is no need to age the routes in
2108 	 * the table.
2109 	 */
2110 	age_timer.tv_sec = (now.tv_sec
2111 			    + ((rip_sock < 0) ? NEVER : SUPPLY_INTERVAL));
2112 
2113 	/* Check for dead IS_REMOTE interfaces by timing their
2114 	 * transmissions.
2115 	 */
2116 	LIST_FOREACH(ifp, &ifnet, int_list) {
2117 		if (!(ifp->int_state & IS_REMOTE))
2118 			continue;
2119 
2120 		/* ignore unreachable remote interfaces */
2121 		if (!check_remote(ifp))
2122 			continue;
2123 
2124 		/* Restore remote interface that has become reachable
2125 		 */
2126 		if (ifp->int_state & IS_BROKE)
2127 			if_ok(ifp, "remote ");
2128 
2129 		if (ifp->int_act_time != NEVER
2130 		    && now.tv_sec - ifp->int_act_time > EXPIRE_TIME) {
2131 			msglog("remote interface %s to %s timed out after"
2132 			       " %ld:%ld",
2133 			       ifp->int_name,
2134 			       naddr_ntoa(ifp->int_dstaddr),
2135 			       (long)(now.tv_sec - ifp->int_act_time)/60,
2136 			       (long)(now.tv_sec - ifp->int_act_time)%60);
2137 			if_sick(ifp);
2138 		}
2139 
2140 		/* If we have not heard from the other router
2141 		 * recently, ask it.
2142 		 */
2143 		if (now.tv_sec >= ifp->int_query_time) {
2144 			ifp->int_query_time = NEVER;
2145 			need_query = 1;
2146 		}
2147 	}
2148 
2149 	/* Age routes. */
2150 	age_bad_gate = bad_gate;
2151 	(void)rn_walktree(rhead, walk_age, 0);
2152 
2153 	/* delete old redirected routes to keep the kernel table small
2154 	 * and prevent blackholes
2155 	 */
2156 	del_redirects(bad_gate, now.tv_sec-STALE_TIME);
2157 
2158 	/* Update the kernel routing table. */
2159 	fix_kern();
2160 
2161 	/* poke reticent remote gateways */
2162 	if (need_query)
2163 		rip_query();
2164 }
2165