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