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