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