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