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