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