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