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