xref: /freebsd/sbin/routed/radix.c (revision 380a989b3223d455375b4fae70fd0b9bdd43bafb)
1 /*
2  * Copyright (c) 1988, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  */
34 
35 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)radix.c	8.4 (Berkeley) 11/2/94";
38 #endif
39 static const char rcsid[] =
40 	"$Id$";
41 #endif /* not lint */
42 
43 /*
44  * Routines to build and maintain radix trees for routing lookups.
45  */
46 
47 #include "defs.h"
48 
49 #define log(x, msg) syslog(x, msg)
50 #define panic(s) {log(LOG_ERR,s); exit(1);}
51 #define min(a,b) (((a)<(b))?(a):(b))
52 
53 int	max_keylen;
54 struct radix_mask *rn_mkfreelist;
55 struct radix_node_head *mask_rnhead;
56 static char *addmask_key;
57 static char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, -1};
58 static char *rn_zeros, *rn_ones;
59 
60 #define rn_masktop (mask_rnhead->rnh_treetop)
61 #undef Bcmp
62 #define Bcmp(a, b, l) (l == 0 ? 0 : bcmp((caddr_t)(a), (caddr_t)(b), (u_long)l))
63 
64 static int rn_satsifies_leaf(char *, struct radix_node *, int);
65 
66 /*
67  * The data structure for the keys is a radix tree with one way
68  * branching removed.  The index rn_b at an internal node n represents a bit
69  * position to be tested.  The tree is arranged so that all descendants
70  * of a node n have keys whose bits all agree up to position rn_b - 1.
71  * (We say the index of n is rn_b.)
72  *
73  * There is at least one descendant which has a one bit at position rn_b,
74  * and at least one with a zero there.
75  *
76  * A route is determined by a pair of key and mask.  We require that the
77  * bit-wise logical and of the key and mask to be the key.
78  * We define the index of a route to associated with the mask to be
79  * the first bit number in the mask where 0 occurs (with bit number 0
80  * representing the highest order bit).
81  *
82  * We say a mask is normal if every bit is 0, past the index of the mask.
83  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b,
84  * and m is a normal mask, then the route applies to every descendant of n.
85  * If the index(m) < rn_b, this implies the trailing last few bits of k
86  * before bit b are all 0, (and hence consequently true of every descendant
87  * of n), so the route applies to all descendants of the node as well.
88  *
89  * Similar logic shows that a non-normal mask m such that
90  * index(m) <= index(n) could potentially apply to many children of n.
91  * Thus, for each non-host route, we attach its mask to a list at an internal
92  * node as high in the tree as we can go.
93  *
94  * The present version of the code makes use of normal routes in short-
95  * circuiting an explict mask and compare operation when testing whether
96  * a key satisfies a normal route, and also in remembering the unique leaf
97  * that governs a subtree.
98  */
99 
100 struct radix_node *
101 rn_search(void *v_arg,
102 	  struct radix_node *head)
103 {
104 	register struct radix_node *x;
105 	register caddr_t v;
106 
107 	for (x = head, v = v_arg; x->rn_b >= 0;) {
108 		if (x->rn_bmask & v[x->rn_off])
109 			x = x->rn_r;
110 		else
111 			x = x->rn_l;
112 	}
113 	return (x);
114 }
115 
116 struct radix_node *
117 rn_search_m(void *v_arg,
118 	    struct radix_node *head,
119 	    void *m_arg)
120 {
121 	register struct radix_node *x;
122 	register caddr_t v = v_arg, m = m_arg;
123 
124 	for (x = head; x->rn_b >= 0;) {
125 		if ((x->rn_bmask & m[x->rn_off]) &&
126 		    (x->rn_bmask & v[x->rn_off]))
127 			x = x->rn_r;
128 		else
129 			x = x->rn_l;
130 	}
131 	return x;
132 }
133 
134 int
135 rn_refines(void* m_arg, void *n_arg)
136 {
137 	register caddr_t m = m_arg, n = n_arg;
138 	register caddr_t lim, lim2 = lim = n + *(u_char *)n;
139 	int longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
140 	int masks_are_equal = 1;
141 
142 	if (longer > 0)
143 		lim -= longer;
144 	while (n < lim) {
145 		if (*n & ~(*m))
146 			return 0;
147 		if (*n++ != *m++)
148 			masks_are_equal = 0;
149 	}
150 	while (n < lim2)
151 		if (*n++)
152 			return 0;
153 	if (masks_are_equal && (longer < 0))
154 		for (lim2 = m - longer; m < lim2; )
155 			if (*m++)
156 				return 1;
157 	return (!masks_are_equal);
158 }
159 
160 struct radix_node *
161 rn_lookup(v_arg, m_arg, head)
162 	void *v_arg, *m_arg;
163 	struct radix_node_head *head;
164 {
165 	register struct radix_node *x;
166 	caddr_t netmask = 0;
167 
168 	if (m_arg) {
169 		if ((x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_off)) == 0)
170 			return (0);
171 		netmask = x->rn_key;
172 	}
173 	x = rn_match(v_arg, head);
174 	if (x && netmask) {
175 		while (x && x->rn_mask != netmask)
176 			x = x->rn_dupedkey;
177 	}
178 	return x;
179 }
180 
181 static int
182 rn_satsifies_leaf(char *trial,
183 		  register struct radix_node *leaf,
184 		  int skip)
185 {
186 	register char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
187 	char *cplim;
188 	int length = min(*(u_char *)cp, *(u_char *)cp2);
189 
190 	if (cp3 == 0)
191 		cp3 = rn_ones;
192 	else
193 		length = min(length, *(u_char *)cp3);
194 	cplim = cp + length; cp3 += skip; cp2 += skip;
195 	for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
196 		if ((*cp ^ *cp2) & *cp3)
197 			return 0;
198 	return 1;
199 }
200 
201 struct radix_node *
202 rn_match(void *v_arg,
203 	 struct radix_node_head *head)
204 {
205 	caddr_t v = v_arg;
206 	register struct radix_node *t = head->rnh_treetop, *x;
207 	register caddr_t cp = v, cp2;
208 	caddr_t cplim;
209 	struct radix_node *saved_t, *top = t;
210 	int off = t->rn_off, vlen = *(u_char *)cp, matched_off;
211 	register int test, b, rn_b;
212 
213 	/*
214 	 * Open code rn_search(v, top) to avoid overhead of extra
215 	 * subroutine call.
216 	 */
217 	for (; t->rn_b >= 0; ) {
218 		if (t->rn_bmask & cp[t->rn_off])
219 			t = t->rn_r;
220 		else
221 			t = t->rn_l;
222 	}
223 	/*
224 	 * See if we match exactly as a host destination
225 	 * or at least learn how many bits match, for normal mask finesse.
226 	 *
227 	 * It doesn't hurt us to limit how many bytes to check
228 	 * to the length of the mask, since if it matches we had a genuine
229 	 * match and the leaf we have is the most specific one anyway;
230 	 * if it didn't match with a shorter length it would fail
231 	 * with a long one.  This wins big for class B&C netmasks which
232 	 * are probably the most common case...
233 	 */
234 	if (t->rn_mask)
235 		vlen = *(u_char *)t->rn_mask;
236 	cp += off; cp2 = t->rn_key + off; cplim = v + vlen;
237 	for (; cp < cplim; cp++, cp2++)
238 		if (*cp != *cp2)
239 			goto on1;
240 	/*
241 	 * This extra grot is in case we are explicitly asked
242 	 * to look up the default.  Ugh!
243 	 * Or 255.255.255.255
244 	 *
245 	 * In this case, we have a complete match of the key.  Unless
246 	 * the node is one of the roots, we are finished.
247 	 * If it is the zeros root, then take what we have, prefering
248 	 * any real data.
249 	 * If it is the ones root, then pretend the target key was followed
250 	 * by a byte of zeros.
251 	 */
252 	if (!(t->rn_flags & RNF_ROOT))
253 		return t;		/* not a root */
254 	if (t->rn_dupedkey) {
255 		t = t->rn_dupedkey;
256 		return t;		/* have some real data */
257 	}
258 	if (*(cp-1) == 0)
259 		return t;		/* not the ones root */
260 	b = 0;				/* fake a zero after 255.255.255.255 */
261 	goto on2;
262 on1:
263 	test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
264 	for (b = 7; (test >>= 1) > 0;)
265 		b--;
266 on2:
267 	matched_off = cp - v;
268 	b += matched_off << 3;
269 	rn_b = -1 - b;
270 	/*
271 	 * If there is a host route in a duped-key chain, it will be first.
272 	 */
273 	if ((saved_t = t)->rn_mask == 0)
274 		t = t->rn_dupedkey;
275 	for (; t; t = t->rn_dupedkey)
276 		/*
277 		 * Even if we don't match exactly as a host,
278 		 * we may match if the leaf we wound up at is
279 		 * a route to a net.
280 		 */
281 		if (t->rn_flags & RNF_NORMAL) {
282 			if (rn_b <= t->rn_b)
283 				return t;
284 		} else if (rn_satsifies_leaf(v, t, matched_off))
285 				return t;
286 	t = saved_t;
287 	/* start searching up the tree */
288 	do {
289 		register struct radix_mask *m;
290 		t = t->rn_p;
291 		if ((m = t->rn_mklist)) {
292 			/*
293 			 * If non-contiguous masks ever become important
294 			 * we can restore the masking and open coding of
295 			 * the search and satisfaction test and put the
296 			 * calculation of "off" back before the "do".
297 			 */
298 			do {
299 				if (m->rm_flags & RNF_NORMAL) {
300 					if (rn_b <= m->rm_b)
301 						return (m->rm_leaf);
302 				} else {
303 					off = min(t->rn_off, matched_off);
304 					x = rn_search_m(v, t, m->rm_mask);
305 					while (x && x->rn_mask != m->rm_mask)
306 						x = x->rn_dupedkey;
307 					if (x && rn_satsifies_leaf(v, x, off))
308 						    return x;
309 				}
310 			} while ((m = m->rm_mklist));
311 		}
312 	} while (t != top);
313 	return 0;
314 }
315 
316 #ifdef RN_DEBUG
317 int	rn_nodenum;
318 struct	radix_node *rn_clist;
319 int	rn_saveinfo;
320 int	rn_debug =  1;
321 #endif
322 
323 struct radix_node *
324 rn_newpair(void *v, int b, struct radix_node nodes[2])
325 {
326 	register struct radix_node *tt = nodes, *t = tt + 1;
327 	t->rn_b = b; t->rn_bmask = 0x80 >> (b & 7);
328 	t->rn_l = tt; t->rn_off = b >> 3;
329 	tt->rn_b = -1; tt->rn_key = (caddr_t)v; tt->rn_p = t;
330 	tt->rn_flags = t->rn_flags = RNF_ACTIVE;
331 #ifdef RN_DEBUG
332 	tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
333 	tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
334 #endif
335 	return t;
336 }
337 
338 struct radix_node *
339 rn_insert(void* v_arg,
340 	  struct radix_node_head *head,
341 	  int *dupentry,
342 	  struct radix_node nodes[2])
343 {
344 	caddr_t v = v_arg;
345 	struct radix_node *top = head->rnh_treetop;
346 	int head_off = top->rn_off, vlen = (int)*((u_char *)v);
347 	register struct radix_node *t = rn_search(v_arg, top);
348 	register caddr_t cp = v + head_off;
349 	register int b;
350 	struct radix_node *tt;
351 
352 	/*
353 	 * Find first bit at which v and t->rn_key differ
354 	 */
355     {
356 	register caddr_t cp2 = t->rn_key + head_off;
357 	register int cmp_res;
358 	caddr_t cplim = v + vlen;
359 
360 	while (cp < cplim)
361 		if (*cp2++ != *cp++)
362 			goto on1;
363 	/* handle adding 255.255.255.255 */
364 	if (!(t->rn_flags & RNF_ROOT) || *(cp2-1) == 0) {
365 		*dupentry = 1;
366 		return t;
367 	}
368 on1:
369 	*dupentry = 0;
370 	cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
371 	for (b = (cp - v) << 3; cmp_res; b--)
372 		cmp_res >>= 1;
373     }
374     {
375 	register struct radix_node *p, *x = top;
376 	cp = v;
377 	do {
378 		p = x;
379 		if (cp[x->rn_off] & x->rn_bmask)
380 			x = x->rn_r;
381 		else x = x->rn_l;
382 	} while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
383 #ifdef RN_DEBUG
384 	if (rn_debug)
385 		log(LOG_DEBUG, "rn_insert: Going In:\n"), traverse(p);
386 #endif
387 	t = rn_newpair(v_arg, b, nodes); tt = t->rn_l;
388 	if ((cp[p->rn_off] & p->rn_bmask) == 0)
389 		p->rn_l = t;
390 	else
391 		p->rn_r = t;
392 	x->rn_p = t; t->rn_p = p; /* frees x, p as temp vars below */
393 	if ((cp[t->rn_off] & t->rn_bmask) == 0) {
394 		t->rn_r = x;
395 	} else {
396 		t->rn_r = tt; t->rn_l = x;
397 	}
398 #ifdef RN_DEBUG
399 	if (rn_debug)
400 		log(LOG_DEBUG, "rn_insert: Coming Out:\n"), traverse(p);
401 #endif
402     }
403 	return (tt);
404 }
405 
406 struct radix_node *
407 rn_addmask(void *n_arg, int search, int skip)
408 {
409 	caddr_t netmask = (caddr_t)n_arg;
410 	register struct radix_node *x;
411 	register caddr_t cp, cplim;
412 	register int b = 0, mlen, j;
413 	int maskduplicated, m0, isnormal;
414 	struct radix_node *saved_x;
415 	static int last_zeroed = 0;
416 
417 	if ((mlen = *(u_char *)netmask) > max_keylen)
418 		mlen = max_keylen;
419 	if (skip == 0)
420 		skip = 1;
421 	if (mlen <= skip)
422 		return (mask_rnhead->rnh_nodes);
423 	if (skip > 1)
424 		Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
425 	if ((m0 = mlen) > skip)
426 		Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
427 	/*
428 	 * Trim trailing zeroes.
429 	 */
430 	for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
431 		cp--;
432 	mlen = cp - addmask_key;
433 	if (mlen <= skip) {
434 		if (m0 >= last_zeroed)
435 			last_zeroed = mlen;
436 		return (mask_rnhead->rnh_nodes);
437 	}
438 	if (m0 < last_zeroed)
439 		Bzero(addmask_key + m0, last_zeroed - m0);
440 	*addmask_key = last_zeroed = mlen;
441 	x = rn_search(addmask_key, rn_masktop);
442 	if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
443 		x = 0;
444 	if (x || search)
445 		return (x);
446 	x = (struct radix_node *)
447 			rtmalloc(max_keylen + 2 * sizeof (*x), "rn_addmask");
448 	if ((saved_x = x) == 0)
449 		return (0);
450 	Bzero(x, max_keylen + 2 * sizeof (*x));
451 	netmask = cp = (caddr_t)(x + 2);
452 	Bcopy(addmask_key, cp, mlen);
453 	x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
454 	if (maskduplicated) {
455 		log(LOG_ERR, "rn_addmask: mask impossibly already in tree");
456 		Free(saved_x);
457 		return (x);
458 	}
459 	/*
460 	 * Calculate index of mask, and check for normalcy.
461 	 */
462 	cplim = netmask + mlen; isnormal = 1;
463 	for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
464 		cp++;
465 	if (cp != cplim) {
466 		for (j = 0x80; (j & *cp) != 0; j >>= 1)
467 			b++;
468 		if (*cp != normal_chars[b] || cp != (cplim - 1))
469 			isnormal = 0;
470 	}
471 	b += (cp - netmask) << 3;
472 	x->rn_b = -1 - b;
473 	if (isnormal)
474 		x->rn_flags |= RNF_NORMAL;
475 	return (x);
476 }
477 
478 static int	/* XXX: arbitrary ordering for non-contiguous masks */
479 rn_lexobetter(void *m_arg, void *n_arg)
480 {
481 	register u_char *mp = m_arg, *np = n_arg, *lim;
482 
483 	if (*mp > *np)
484 		return 1;  /* not really, but need to check longer one first */
485 	if (*mp == *np)
486 		for (lim = mp + *mp; mp < lim;)
487 			if (*mp++ > *np++)
488 				return 1;
489 	return 0;
490 }
491 
492 static struct radix_mask *
493 rn_new_radix_mask(register struct radix_node *tt,
494 		  register struct radix_mask *next)
495 {
496 	register struct radix_mask *m;
497 
498 	MKGet(m);
499 	if (m == 0) {
500 		log(LOG_ERR, "Mask for route not entered\n");
501 		return (0);
502 	}
503 	Bzero(m, sizeof *m);
504 	m->rm_b = tt->rn_b;
505 	m->rm_flags = tt->rn_flags;
506 	if (tt->rn_flags & RNF_NORMAL)
507 		m->rm_leaf = tt;
508 	else
509 		m->rm_mask = tt->rn_mask;
510 	m->rm_mklist = next;
511 	tt->rn_mklist = m;
512 	return m;
513 }
514 
515 struct radix_node *
516 rn_addroute(void *v_arg,
517 	    void *n_arg,
518 	    struct radix_node_head *head,
519 	    struct radix_node treenodes[2])
520 {
521 	caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
522 	register struct radix_node *t, *x = 0, *tt;
523 	struct radix_node *saved_tt, *top = head->rnh_treetop;
524 	short b = 0, b_leaf = 0;
525 	int keyduplicated;
526 	caddr_t mmask;
527 	struct radix_mask *m, **mp;
528 
529 	/*
530 	 * In dealing with non-contiguous masks, there may be
531 	 * many different routes which have the same mask.
532 	 * We will find it useful to have a unique pointer to
533 	 * the mask to speed avoiding duplicate references at
534 	 * nodes and possibly save time in calculating indices.
535 	 */
536 	if (netmask)  {
537 		if ((x = rn_addmask(netmask, 0, top->rn_off)) == 0)
538 			return (0);
539 		b_leaf = x->rn_b;
540 		b = -1 - x->rn_b;
541 		netmask = x->rn_key;
542 	}
543 	/*
544 	 * Deal with duplicated keys: attach node to previous instance
545 	 */
546 	saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
547 	if (keyduplicated) {
548 		for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
549 			if (tt->rn_mask == netmask)
550 				return (0);
551 			if (netmask == 0 ||
552 			    (tt->rn_mask &&
553 			     ((b_leaf < tt->rn_b) || /* index(netmask) > node */
554 			       rn_refines(netmask, tt->rn_mask) ||
555 			       rn_lexobetter(netmask, tt->rn_mask))))
556 				break;
557 		}
558 		/*
559 		 * If the mask is not duplicated, we wouldn't
560 		 * find it among possible duplicate key entries
561 		 * anyway, so the above test doesn't hurt.
562 		 *
563 		 * We sort the masks for a duplicated key the same way as
564 		 * in a masklist -- most specific to least specific.
565 		 * This may require the unfortunate nuisance of relocating
566 		 * the head of the list.
567 		 */
568 		if (tt == saved_tt) {
569 			struct	radix_node *xx = x;
570 			/* link in at head of list */
571 			(tt = treenodes)->rn_dupedkey = t;
572 			tt->rn_flags = t->rn_flags;
573 			tt->rn_p = x = t->rn_p;
574 			if (x->rn_l == t) x->rn_l = tt; else x->rn_r = tt;
575 			saved_tt = tt; x = xx;
576 		} else {
577 			(tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
578 			t->rn_dupedkey = tt;
579 		}
580 #ifdef RN_DEBUG
581 		t=tt+1; tt->rn_info = rn_nodenum++; t->rn_info = rn_nodenum++;
582 		tt->rn_twin = t; tt->rn_ybro = rn_clist; rn_clist = tt;
583 #endif
584 		tt->rn_key = (caddr_t) v;
585 		tt->rn_b = -1;
586 		tt->rn_flags = RNF_ACTIVE;
587 	}
588 	/*
589 	 * Put mask in tree.
590 	 */
591 	if (netmask) {
592 		tt->rn_mask = netmask;
593 		tt->rn_b = x->rn_b;
594 		tt->rn_flags |= x->rn_flags & RNF_NORMAL;
595 	}
596 	t = saved_tt->rn_p;
597 	if (keyduplicated)
598 		goto on2;
599 	b_leaf = -1 - t->rn_b;
600 	if (t->rn_r == saved_tt) x = t->rn_l; else x = t->rn_r;
601 	/* Promote general routes from below */
602 	if (x->rn_b < 0) {
603 	    for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
604 		if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) {
605 			if ((*mp = m = rn_new_radix_mask(x, 0)))
606 				mp = &m->rm_mklist;
607 		}
608 	} else if (x->rn_mklist) {
609 		/*
610 		 * Skip over masks whose index is > that of new node
611 		 */
612 		for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
613 			if (m->rm_b >= b_leaf)
614 				break;
615 		t->rn_mklist = m; *mp = 0;
616 	}
617 on2:
618 	/* Add new route to highest possible ancestor's list */
619 	if ((netmask == 0) || (b > t->rn_b ))
620 		return tt; /* can't lift at all */
621 	b_leaf = tt->rn_b;
622 	do {
623 		x = t;
624 		t = t->rn_p;
625 	} while (b <= t->rn_b && x != top);
626 	/*
627 	 * Search through routes associated with node to
628 	 * insert new route according to index.
629 	 * Need same criteria as when sorting dupedkeys to avoid
630 	 * double loop on deletion.
631 	 */
632 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) {
633 		if (m->rm_b < b_leaf)
634 			continue;
635 		if (m->rm_b > b_leaf)
636 			break;
637 		if (m->rm_flags & RNF_NORMAL) {
638 			mmask = m->rm_leaf->rn_mask;
639 			if (tt->rn_flags & RNF_NORMAL) {
640 				log(LOG_ERR,
641 				   "Non-unique normal route, mask not entered");
642 				return tt;
643 			}
644 		} else
645 			mmask = m->rm_mask;
646 		if (mmask == netmask) {
647 			m->rm_refs++;
648 			tt->rn_mklist = m;
649 			return tt;
650 		}
651 		if (rn_refines(netmask, mmask) || rn_lexobetter(netmask, mmask))
652 			break;
653 	}
654 	*mp = rn_new_radix_mask(tt, *mp);
655 	return tt;
656 }
657 
658 struct radix_node *
659 rn_delete(void *v_arg,
660 	  void *netmask_arg,
661 	  struct radix_node_head *head)
662 {
663 	register struct radix_node *t, *p, *x, *tt;
664 	struct radix_mask *m, *saved_m, **mp;
665 	struct radix_node *dupedkey, *saved_tt, *top;
666 	caddr_t v, netmask;
667 	int b, head_off, vlen;
668 
669 	v = v_arg;
670 	netmask = netmask_arg;
671 	x = head->rnh_treetop;
672 	tt = rn_search(v, x);
673 	head_off = x->rn_off;
674 	vlen =  *(u_char *)v;
675 	saved_tt = tt;
676 	top = x;
677 	if (tt == 0 ||
678 	    Bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
679 		return (0);
680 	/*
681 	 * Delete our route from mask lists.
682 	 */
683 	if (netmask) {
684 		if ((x = rn_addmask(netmask, 1, head_off)) == 0)
685 			return (0);
686 		netmask = x->rn_key;
687 		while (tt->rn_mask != netmask)
688 			if ((tt = tt->rn_dupedkey) == 0)
689 				return (0);
690 	}
691 	if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
692 		goto on1;
693 	if (tt->rn_flags & RNF_NORMAL) {
694 		if (m->rm_leaf != tt || m->rm_refs > 0) {
695 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
696 			return 0;  /* dangling ref could cause disaster */
697 		}
698 	} else {
699 		if (m->rm_mask != tt->rn_mask) {
700 			log(LOG_ERR, "rn_delete: inconsistent annotation\n");
701 			goto on1;
702 		}
703 		if (--m->rm_refs >= 0)
704 			goto on1;
705 	}
706 	b = -1 - tt->rn_b;
707 	t = saved_tt->rn_p;
708 	if (b > t->rn_b)
709 		goto on1; /* Wasn't lifted at all */
710 	do {
711 		x = t;
712 		t = t->rn_p;
713 	} while (b <= t->rn_b && x != top);
714 	for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist)
715 		if (m == saved_m) {
716 			*mp = m->rm_mklist;
717 			MKFree(m);
718 			break;
719 		}
720 	if (m == 0) {
721 		log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
722 		if (tt->rn_flags & RNF_NORMAL)
723 			return (0); /* Dangling ref to us */
724 	}
725 on1:
726 	/*
727 	 * Eliminate us from tree
728 	 */
729 	if (tt->rn_flags & RNF_ROOT)
730 		return (0);
731 #ifdef RN_DEBUG
732 	/* Get us out of the creation list */
733 	for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro) {}
734 	if (t) t->rn_ybro = tt->rn_ybro;
735 #endif
736 	t = tt->rn_p;
737 	if ((dupedkey = saved_tt->rn_dupedkey)) {
738 		if (tt == saved_tt) {
739 			x = dupedkey; x->rn_p = t;
740 			if (t->rn_l == tt) t->rn_l = x; else t->rn_r = x;
741 		} else {
742 			for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
743 				p = p->rn_dupedkey;
744 			if (p) p->rn_dupedkey = tt->rn_dupedkey;
745 			else log(LOG_ERR, "rn_delete: couldn't find us\n");
746 		}
747 		t = tt + 1;
748 		if  (t->rn_flags & RNF_ACTIVE) {
749 #ifndef RN_DEBUG
750 			*++x = *t; p = t->rn_p;
751 #else
752 			b = t->rn_info; *++x = *t; t->rn_info = b; p = t->rn_p;
753 #endif
754 			if (p->rn_l == t) p->rn_l = x; else p->rn_r = x;
755 			x->rn_l->rn_p = x; x->rn_r->rn_p = x;
756 		}
757 		goto out;
758 	}
759 	if (t->rn_l == tt) x = t->rn_r; else x = t->rn_l;
760 	p = t->rn_p;
761 	if (p->rn_r == t) p->rn_r = x; else p->rn_l = x;
762 	x->rn_p = p;
763 	/*
764 	 * Demote routes attached to us.
765 	 */
766 	if (t->rn_mklist) {
767 		if (x->rn_b >= 0) {
768 			for (mp = &x->rn_mklist; (m = *mp);)
769 				mp = &m->rm_mklist;
770 			*mp = t->rn_mklist;
771 		} else {
772 			/* If there are any key,mask pairs in a sibling
773 			   duped-key chain, some subset will appear sorted
774 			   in the same order attached to our mklist */
775 			for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
776 				if (m == x->rn_mklist) {
777 					struct radix_mask *mm = m->rm_mklist;
778 					x->rn_mklist = 0;
779 					if (--(m->rm_refs) < 0)
780 						MKFree(m);
781 					m = mm;
782 				}
783 			if (m)
784 				syslog(LOG_ERR, "%s %lx at %lx\n",
785 				       "rn_delete: Orphaned Mask",
786 				       (unsigned long)m,
787 				       (unsigned long)x);
788 		}
789 	}
790 	/*
791 	 * We may be holding an active internal node in the tree.
792 	 */
793 	x = tt + 1;
794 	if (t != x) {
795 #ifndef RN_DEBUG
796 		*t = *x;
797 #else
798 		b = t->rn_info; *t = *x; t->rn_info = b;
799 #endif
800 		t->rn_l->rn_p = t; t->rn_r->rn_p = t;
801 		p = x->rn_p;
802 		if (p->rn_l == x) p->rn_l = t; else p->rn_r = t;
803 	}
804 out:
805 	tt->rn_flags &= ~RNF_ACTIVE;
806 	tt[1].rn_flags &= ~RNF_ACTIVE;
807 	return (tt);
808 }
809 
810 int
811 rn_walktree(struct radix_node_head *h,
812 	    register int (*f)(struct radix_node *, struct walkarg*),
813 	    struct walkarg *w)
814 {
815 	int error;
816 	struct radix_node *base, *next;
817 	register struct radix_node *rn = h->rnh_treetop;
818 	/*
819 	 * This gets complicated because we may delete the node
820 	 * while applying the function f to it, so we need to calculate
821 	 * the successor node in advance.
822 	 */
823 	/* First time through node, go left */
824 	while (rn->rn_b >= 0)
825 		rn = rn->rn_l;
826 	for (;;) {
827 		base = rn;
828 		/* If at right child go back up, otherwise, go right */
829 		while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0)
830 			rn = rn->rn_p;
831 		/* Find the next *leaf* since next node might vanish, too */
832 		for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;)
833 			rn = rn->rn_l;
834 		next = rn;
835 		/* Process leaves */
836 		while ((rn = base)) {
837 			base = rn->rn_dupedkey;
838 			if (!(rn->rn_flags & RNF_ROOT) && (error = (*f)(rn, w)))
839 				return (error);
840 		}
841 		rn = next;
842 		if (rn->rn_flags & RNF_ROOT)
843 			return (0);
844 	}
845 	/* NOTREACHED */
846 }
847 
848 int
849 rn_inithead(void **head, int off)
850 {
851 	register struct radix_node_head *rnh;
852 	register struct radix_node *t, *tt, *ttt;
853 	if (*head)
854 		return (1);
855 	rnh = (struct radix_node_head *)rtmalloc(sizeof (*rnh), "rn_inithead");
856 	if (rnh == 0)
857 		return (0);
858 	Bzero(rnh, sizeof (*rnh));
859 	*head = rnh;
860 	t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
861 	ttt = rnh->rnh_nodes + 2;
862 	t->rn_r = ttt;
863 	t->rn_p = t;
864 	tt = t->rn_l;
865 	tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
866 	tt->rn_b = -1 - off;
867 	*ttt = *tt;
868 	ttt->rn_key = rn_ones;
869 	rnh->rnh_addaddr = rn_addroute;
870 	rnh->rnh_deladdr = rn_delete;
871 	rnh->rnh_matchaddr = rn_match;
872 	rnh->rnh_lookup = rn_lookup;
873 	rnh->rnh_walktree = rn_walktree;
874 	rnh->rnh_treetop = t;
875 	return (1);
876 }
877 
878 void
879 rn_init(void)
880 {
881 	char *cp, *cplim;
882 	if (max_keylen == 0) {
883 		printf("rn_init: radix functions require max_keylen be set\n");
884 		return;
885 	}
886 	rn_zeros = (char *)rtmalloc(3 * max_keylen, "rn_init");
887 	if (rn_zeros == NULL)
888 		panic("rn_init");
889 	Bzero(rn_zeros, 3 * max_keylen);
890 	rn_ones = cp = rn_zeros + max_keylen;
891 	addmask_key = cplim = rn_ones + max_keylen;
892 	while (cp < cplim)
893 		*cp++ = -1;
894 	if (rn_inithead((void **)&mask_rnhead, 0) == 0)
895 		panic("rn_init 2");
896 }
897 
898