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