]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/ipfilter/radix.c
This commit was generated by cvs2svn to compensate for changes in r168616,
[FreeBSD/FreeBSD.git] / contrib / ipfilter / radix.c
1 /*      $FreeBSD$       */
2
3 /*
4  * Copyright (c) 1988, 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  *      @(#)radix.c     8.6 (Berkeley) 10/17/95
29  */
30
31 /*
32  * Routines to build and maintain radix trees for routing lookups.
33  */
34 #if defined(KERNEL) || defined(_KERNEL)
35 # undef KERNEL
36 # undef _KERNEL
37 # define        KERNEL  1
38 # define        _KERNEL 1
39 #endif
40 #define __SYS_ATOMIC_OPS_H__
41 #if !defined(__svr4__) && !defined(__SVR4) && !defined(__osf__) && \
42     !defined(__hpux) && !defined(__sgi)
43 #include <sys/cdefs.h>
44 #endif
45 #ifndef __P
46 # ifdef __STDC__
47 #  define       __P(x)  x
48 # else
49 #  define       __P(x)  ()
50 # endif
51 #endif
52 #ifdef __osf__
53 # define CONST
54 # define _IPV6_SWTAB_H
55 # define _PROTO_NET_H_
56 # define _PROTO_IPV6_H
57 # include <sys/malloc.h>
58 #endif
59
60 #include <sys/param.h>
61 #ifdef  _KERNEL
62 #include <sys/systm.h>
63 #else
64 void panic __P((char *str));
65 #include <stdlib.h>
66 #include <stdio.h>
67 #include <stdarg.h>
68 #include <string.h>
69 #endif
70 #ifdef __hpux
71 #include <syslog.h>
72 #else
73 #include <sys/syslog.h>
74 #endif
75 #include <sys/time.h>
76 #include <netinet/in.h>
77 #include <sys/socket.h>
78 #include <net/if.h>
79 #include "netinet/ip_compat.h"
80 #include "netinet/ip_fil.h"
81 /* END OF INCLUDES */
82 #include "radix_ipf.h"
83 #ifndef min
84 # define        min     MIN
85 #endif
86 #ifndef max
87 # define        max     MAX
88 #endif
89
90 int     max_keylen = 16;
91 static struct radix_mask *rn_mkfreelist;
92 static struct radix_node_head *mask_rnhead;
93 static char *addmask_key;
94 static u_char normal_chars[] = {0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
95 static char *rn_zeros = NULL, *rn_ones = NULL;
96
97 #define rn_masktop (mask_rnhead->rnh_treetop)
98 #undef Bcmp
99 #define Bcmp(a, b, l) (l == 0 ? 0 : bcmp((caddr_t)(a), (caddr_t)(b), (u_long)l))
100
101 static int rn_satisfies_leaf __P((char *, struct radix_node *, int));
102 static int rn_lexobetter __P((void *, void *));
103 static struct radix_mask *rn_new_radix_mask __P((struct radix_node *,
104     struct radix_mask *));
105 static int rn_freenode __P((struct radix_node *, void *));
106 #if defined(AIX) && !defined(_KERNEL)
107 struct radix_node *rn_match __P((void *, struct radix_node_head *));
108 struct radix_node *rn_addmask __P((int, int, void *));
109 #define FreeS(x, y)     KFREES(x, y)
110 #define Bcopy(x, y, z)  bcopy(x, y, z)
111 #endif
112
113 /*
114  * The data structure for the keys is a radix tree with one way
115  * branching removed.  The index rn_b at an internal node n represents a bit
116  * position to be tested.  The tree is arranged so that all descendants
117  * of a node n have keys whose bits all agree up to position rn_b - 1.
118  * (We say the index of n is rn_b.)
119  *
120  * There is at least one descendant which has a one bit at position rn_b,
121  * and at least one with a zero there.
122  *
123  * A route is determined by a pair of key and mask.  We require that the
124  * bit-wise logical and of the key and mask to be the key.
125  * We define the index of a route to associated with the mask to be
126  * the first bit number in the mask where 0 occurs (with bit number 0
127  * representing the highest order bit).
128  *
129  * We say a mask is normal if every bit is 0, past the index of the mask.
130  * If a node n has a descendant (k, m) with index(m) == index(n) == rn_b,
131  * and m is a normal mask, then the route applies to every descendant of n.
132  * If the index(m) < rn_b, this implies the trailing last few bits of k
133  * before bit b are all 0, (and hence consequently true of every descendant
134  * of n), so the route applies to all descendants of the node as well.
135  *
136  * Similar logic shows that a non-normal mask m such that
137  * index(m) <= index(n) could potentially apply to many children of n.
138  * Thus, for each non-host route, we attach its mask to a list at an internal
139  * node as high in the tree as we can go.
140  *
141  * The present version of the code makes use of normal routes in short-
142  * circuiting an explicit mask and compare operation when testing whether
143  * a key satisfies a normal route, and also in remembering the unique leaf
144  * that governs a subtree.
145  */
146
147 struct radix_node *
148 rn_search(v_arg, head)
149         void *v_arg;
150         struct radix_node *head;
151 {
152         struct radix_node *x;
153         caddr_t v;
154
155         for (x = head, v = v_arg; x->rn_b >= 0;) {
156                 if (x->rn_bmask & v[x->rn_off])
157                         x = x->rn_r;
158                 else
159                         x = x->rn_l;
160         }
161         return (x);
162 }
163
164 struct radix_node *
165 rn_search_m(v_arg, head, m_arg)
166         struct radix_node *head;
167         void *v_arg, *m_arg;
168 {
169         struct radix_node *x;
170         caddr_t v = v_arg, m = m_arg;
171
172         for (x = head; x->rn_b >= 0;) {
173                 if ((x->rn_bmask & m[x->rn_off]) &&
174                     (x->rn_bmask & v[x->rn_off]))
175                         x = x->rn_r;
176                 else
177                         x = x->rn_l;
178         }
179         return x;
180 }
181
182 int
183 rn_refines(m_arg, n_arg)
184         void *m_arg, *n_arg;
185 {
186         caddr_t m = m_arg, n = n_arg;
187         caddr_t lim, lim2 = lim = n + *(u_char *)n;
188         int longer = (*(u_char *)n++) - (int)(*(u_char *)m++);
189         int masks_are_equal = 1;
190
191         if (longer > 0)
192                 lim -= longer;
193         while (n < lim) {
194                 if (*n & ~(*m))
195                         return 0;
196                 if (*n++ != *m++)
197                         masks_are_equal = 0;
198         }
199         while (n < lim2)
200                 if (*n++)
201                         return 0;
202         if (masks_are_equal && (longer < 0))
203                 for (lim2 = m - longer; m < lim2; )
204                         if (*m++)
205                                 return 1;
206         return (!masks_are_equal);
207 }
208
209 struct radix_node *
210 rn_lookup(v_arg, m_arg, head)
211         void *v_arg, *m_arg;
212         struct radix_node_head *head;
213 {
214         struct radix_node *x;
215         caddr_t netmask = 0;
216
217         if (m_arg) {
218                 if ((x = rn_addmask(m_arg, 1, head->rnh_treetop->rn_off)) == 0)
219                         return (0);
220                 netmask = x->rn_key;
221         }
222         x = rn_match(v_arg, head);
223         if (x && netmask) {
224                 while (x && x->rn_mask != netmask)
225                         x = x->rn_dupedkey;
226         }
227         return x;
228 }
229
230 static int
231 rn_satisfies_leaf(trial, leaf, skip)
232         char *trial;
233         struct radix_node *leaf;
234         int skip;
235 {
236         char *cp = trial, *cp2 = leaf->rn_key, *cp3 = leaf->rn_mask;
237         char *cplim;
238         int length = min(*(u_char *)cp, *(u_char *)cp2);
239
240         if (cp3 == 0)
241                 cp3 = rn_ones;
242         else
243                 length = min(length, *(u_char *)cp3);
244         cplim = cp + length;
245         cp3 += skip;
246         cp2 += skip;
247         for (cp += skip; cp < cplim; cp++, cp2++, cp3++)
248                 if ((*cp ^ *cp2) & *cp3)
249                         return 0;
250         return 1;
251 }
252
253 struct radix_node *
254 rn_match(v_arg, head)
255         void *v_arg;
256         struct radix_node_head *head;
257 {
258         caddr_t v = v_arg;
259         struct radix_node *t = head->rnh_treetop, *x;
260         caddr_t cp = v, cp2;
261         caddr_t cplim;
262         struct radix_node *saved_t, *top = t;
263         int off = t->rn_off, vlen = *(u_char *)cp, matched_off;
264         int test, b, rn_b;
265
266         /*
267          * Open code rn_search(v, top) to avoid overhead of extra
268          * subroutine call.
269          */
270         for (; t->rn_b >= 0; ) {
271                 if (t->rn_bmask & cp[t->rn_off])
272                         t = t->rn_r;
273                 else
274                         t = t->rn_l;
275         }
276         /*
277          * See if we match exactly as a host destination
278          * or at least learn how many bits match, for normal mask finesse.
279          *
280          * It doesn't hurt us to limit how many bytes to check
281          * to the length of the mask, since if it matches we had a genuine
282          * match and the leaf we have is the most specific one anyway;
283          * if it didn't match with a shorter length it would fail
284          * with a long one.  This wins big for class B&C netmasks which
285          * are probably the most common case...
286          */
287         if (t->rn_mask)
288                 vlen = *(u_char *)t->rn_mask;
289         cp += off;
290         cp2 = t->rn_key + off;
291         cplim = v + vlen;
292         for (; cp < cplim; cp++, cp2++)
293                 if (*cp != *cp2)
294                         goto on1;
295         /*
296          * This extra grot is in case we are explicitly asked
297          * to look up the default.  Ugh!
298          */
299         if ((t->rn_flags & RNF_ROOT) && t->rn_dupedkey)
300                 t = t->rn_dupedkey;
301         return t;
302 on1:
303         test = (*cp ^ *cp2) & 0xff; /* find first bit that differs */
304         for (b = 7; (test >>= 1) > 0;)
305                 b--;
306         matched_off = cp - v;
307         b += matched_off << 3;
308         rn_b = -1 - b;
309         /*
310          * If there is a host route in a duped-key chain, it will be first.
311          */
312         if ((saved_t = t)->rn_mask == 0)
313                 t = t->rn_dupedkey;
314         for (; t; t = t->rn_dupedkey)
315                 /*
316                  * Even if we don't match exactly as a host,
317                  * we may match if the leaf we wound up at is
318                  * a route to a net.
319                  */
320                 if (t->rn_flags & RNF_NORMAL) {
321                         if (rn_b <= t->rn_b)
322                                 return t;
323                 } else if (rn_satisfies_leaf(v, t, matched_off))
324                                 return t;
325         t = saved_t;
326         /* start searching up the tree */
327         do {
328                 struct radix_mask *m;
329                 t = t->rn_p;
330                 m = t->rn_mklist;
331                 if (m) {
332                         /*
333                          * If non-contiguous masks ever become important
334                          * we can restore the masking and open coding of
335                          * the search and satisfaction test and put the
336                          * calculation of "off" back before the "do".
337                          */
338                         do {
339                                 if (m->rm_flags & RNF_NORMAL) {
340                                         if (rn_b <= m->rm_b)
341                                                 return (m->rm_leaf);
342                                 } else {
343                                         off = min(t->rn_off, matched_off);
344                                         x = rn_search_m(v, t, m->rm_mask);
345                                         while (x && x->rn_mask != m->rm_mask)
346                                                 x = x->rn_dupedkey;
347                                         if (x && rn_satisfies_leaf(v, x, off))
348                                                 return x;
349                                 }
350                                 m = m->rm_mklist;
351                         } while (m);
352                 }
353         } while (t != top);
354         return 0;
355 }
356
357 #ifdef RN_DEBUG
358 int     rn_nodenum;
359 struct  radix_node *rn_clist;
360 int     rn_saveinfo;
361 int     rn_debug =  1;
362 #endif
363
364 struct radix_node *
365 rn_newpair(v, b, nodes)
366         void *v;
367         int b;
368         struct radix_node nodes[2];
369 {
370         struct radix_node *tt = nodes, *t = tt + 1;
371         t->rn_b = b;
372         t->rn_bmask = 0x80 >> (b & 7);
373         t->rn_l = tt;
374         t->rn_off = b >> 3;
375         tt->rn_b = -1;
376         tt->rn_key = (caddr_t)v;
377         tt->rn_p = t;
378         tt->rn_flags = t->rn_flags = RNF_ACTIVE;
379 #ifdef RN_DEBUG
380         tt->rn_info = rn_nodenum++;
381         t->rn_info = rn_nodenum++;
382         tt->rn_twin = t;
383         tt->rn_ybro = rn_clist;
384         rn_clist = tt;
385 #endif
386         return t;
387 }
388
389 struct radix_node *
390 rn_insert(v_arg, head, dupentry, nodes)
391         void *v_arg;
392         struct radix_node_head *head;
393         int *dupentry;
394         struct radix_node nodes[2];
395 {
396         caddr_t v = v_arg;
397         struct radix_node *top = head->rnh_treetop;
398         int head_off = top->rn_off, vlen = (int)*((u_char *)v);
399         struct radix_node *t = rn_search(v_arg, top);
400         caddr_t cp = v + head_off;
401         int b;
402         struct radix_node *tt;
403
404 #ifdef  RN_DEBUG
405         if (rn_debug)
406                 log(LOG_DEBUG, "rn_insert(%p,%p,%p,%p)\n", v_arg, head, dupentry, nodes);
407 #endif
408         /*
409          * Find first bit at which v and t->rn_key differ
410          */
411     {
412         caddr_t cp2 = t->rn_key + head_off;
413         int cmp_res;
414         caddr_t cplim = v + vlen;
415
416         while (cp < cplim)
417                 if (*cp2++ != *cp++)
418                         goto on1;
419         *dupentry = 1;
420         return t;
421 on1:
422         *dupentry = 0;
423         cmp_res = (cp[-1] ^ cp2[-1]) & 0xff;
424         for (b = (cp - v) << 3; cmp_res; b--)
425                 cmp_res >>= 1;
426     }
427     {
428         struct radix_node *p, *x = top;
429         cp = v;
430         do {
431                 p = x;
432                 if (cp[x->rn_off] & x->rn_bmask)
433                         x = x->rn_r;
434                 else
435                         x = x->rn_l;
436         } while (b > (unsigned) x->rn_b); /* x->rn_b < b && x->rn_b >= 0 */
437 #ifdef RN_DEBUG
438         if (rn_debug)
439                 log(LOG_DEBUG, "rn_insert: Going In:\n"); // traverse(p);
440 #endif
441         t = rn_newpair(v_arg, b, nodes);
442         tt = t->rn_l;
443         if ((cp[p->rn_off] & p->rn_bmask) == 0)
444                 p->rn_l = t;
445         else
446                 p->rn_r = t;
447         x->rn_p = t;
448         t->rn_p = p; /* frees x, p as temp vars below */
449         if ((cp[t->rn_off] & t->rn_bmask) == 0) {
450                 t->rn_r = x;
451         } else {
452                 t->rn_r = tt;
453                 t->rn_l = x;
454         }
455 #ifdef RN_DEBUG
456         if (rn_debug)
457                 log(LOG_DEBUG, "rn_insert: Coming Out:\n"); // traverse(p);
458 #endif
459     }
460         return (tt);
461 }
462
463 struct radix_node *
464 rn_addmask(n_arg, search, skip)
465         int search, skip;
466         void *n_arg;
467 {
468         caddr_t netmask = (caddr_t)n_arg;
469         struct radix_node *x;
470         caddr_t cp, cplim;
471         int b = 0, mlen, j;
472         int maskduplicated, m0, isnormal;
473         struct radix_node *saved_x;
474         static int last_zeroed = 0;
475
476 #ifdef  RN_DEBUG
477         if (rn_debug)
478                 log(LOG_DEBUG, "rn_addmask(%p,%d,%d)\n", n_arg, search, skip);
479 #endif
480         mlen = *(u_char *)netmask;
481         if ((mlen = *(u_char *)netmask) > max_keylen)
482                 mlen = max_keylen;
483         if (skip == 0)
484                 skip = 1;
485         if (mlen <= skip)
486                 return (mask_rnhead->rnh_nodes);
487         if (skip > 1)
488                 Bcopy(rn_ones + 1, addmask_key + 1, skip - 1);
489         if ((m0 = mlen) > skip)
490                 Bcopy(netmask + skip, addmask_key + skip, mlen - skip);
491         /*
492          * Trim trailing zeroes.
493          */
494         for (cp = addmask_key + mlen; (cp > addmask_key) && cp[-1] == 0;)
495                 cp--;
496         mlen = cp - addmask_key;
497         if (mlen <= skip) {
498                 if (m0 >= last_zeroed)
499                         last_zeroed = mlen;
500                 return (mask_rnhead->rnh_nodes);
501         }
502         if (m0 < last_zeroed)
503                 Bzero(addmask_key + m0, last_zeroed - m0);
504         *addmask_key = last_zeroed = mlen;
505         x = rn_search(addmask_key, rn_masktop);
506         if (Bcmp(addmask_key, x->rn_key, mlen) != 0)
507                 x = 0;
508         if (x || search)
509                 return (x);
510         R_Malloc(x, struct radix_node *, max_keylen + 2 * sizeof (*x));
511         if ((saved_x = x) == 0)
512                 return (0);
513         Bzero(x, max_keylen + 2 * sizeof (*x));
514         netmask = cp = (caddr_t)(x + 2);
515         Bcopy(addmask_key, cp, mlen);
516         x = rn_insert(cp, mask_rnhead, &maskduplicated, x);
517         if (maskduplicated) {
518 #if 0
519                 log(LOG_ERR, "rn_addmask: mask impossibly already in tree\n");
520 #endif
521                 Free(saved_x);
522                 return (x);
523         }
524         /*
525          * Calculate index of mask, and check for normalcy.
526          */
527         cplim = netmask + mlen;
528         isnormal = 1;
529         for (cp = netmask + skip; (cp < cplim) && *(u_char *)cp == 0xff;)
530                 cp++;
531         if (cp != cplim) {
532                 for (j = 0x80; (j & *cp) != 0; j >>= 1)
533                         b++;
534                 if (*cp != normal_chars[b] || cp != (cplim - 1))
535                         isnormal = 0;
536         }
537         b += (cp - netmask) << 3;
538         x->rn_b = -1 - b;
539         if (isnormal)
540                 x->rn_flags |= RNF_NORMAL;
541         return (x);
542 }
543
544 static int      /* XXX: arbitrary ordering for non-contiguous masks */
545 rn_lexobetter(m_arg, n_arg)
546         void *m_arg, *n_arg;
547 {
548         u_char *mp = m_arg, *np = n_arg, *lim;
549
550         if (*mp > *np)
551                 return 1;  /* not really, but need to check longer one first */
552         if (*mp == *np)
553                 for (lim = mp + *mp; mp < lim;)
554                         if (*mp++ > *np++)
555                                 return 1;
556         return 0;
557 }
558
559 static struct radix_mask *
560 rn_new_radix_mask(tt, next)
561         struct radix_node *tt;
562         struct radix_mask *next;
563 {
564         struct radix_mask *m;
565
566         MKGet(m);
567         if (m == 0) {
568 #if 0
569                 log(LOG_ERR, "Mask for route not entered\n");
570 #endif
571                 return (0);
572         }
573         Bzero(m, sizeof *m);
574         m->rm_b = tt->rn_b;
575         m->rm_flags = tt->rn_flags;
576         if (tt->rn_flags & RNF_NORMAL)
577                 m->rm_leaf = tt;
578         else
579                 m->rm_mask = tt->rn_mask;
580         m->rm_mklist = next;
581         tt->rn_mklist = m;
582         return m;
583 }
584
585 struct radix_node *
586 rn_addroute(v_arg, n_arg, head, treenodes)
587         void *v_arg, *n_arg;
588         struct radix_node_head *head;
589         struct radix_node treenodes[2];
590 {
591         caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg;
592         struct radix_node *t, *x = NULL, *tt;
593         struct radix_node *saved_tt, *top = head->rnh_treetop;
594         short b = 0, b_leaf = 0;
595         int keyduplicated;
596         caddr_t mmask;
597         struct radix_mask *m, **mp;
598
599 #ifdef  RN_DEBUG
600         if (rn_debug)
601                 log(LOG_DEBUG, "rn_addroute(%p,%p,%p,%p)\n", v_arg, n_arg, head, treenodes);
602 #endif
603         /*
604          * In dealing with non-contiguous masks, there may be
605          * many different routes which have the same mask.
606          * We will find it useful to have a unique pointer to
607          * the mask to speed avoiding duplicate references at
608          * nodes and possibly save time in calculating indices.
609          */
610         if (netmask) {
611                 if ((x = rn_addmask(netmask, 0, top->rn_off)) == 0)
612                         return (0);
613                 b_leaf = x->rn_b;
614                 b = -1 - x->rn_b;
615                 netmask = x->rn_key;
616         }
617         /*
618          * Deal with duplicated keys: attach node to previous instance
619          */
620         saved_tt = tt = rn_insert(v, head, &keyduplicated, treenodes);
621         if (keyduplicated) {
622                 for (t = tt; tt; t = tt, tt = tt->rn_dupedkey) {
623                         if (tt->rn_mask == netmask)
624                                 return (0);
625                         if (netmask == 0 ||
626                             (tt->rn_mask &&
627                              ((b_leaf < tt->rn_b) || /* index(netmask) > node */
628                                rn_refines(netmask, tt->rn_mask) ||
629                                rn_lexobetter(netmask, tt->rn_mask))))
630                                 break;
631                 }
632                 /*
633                  * If the mask is not duplicated, we wouldn't
634                  * find it among possible duplicate key entries
635                  * anyway, so the above test doesn't hurt.
636                  *
637                  * We sort the masks for a duplicated key the same way as
638                  * in a masklist -- most specific to least specific.
639                  * This may require the unfortunate nuisance of relocating
640                  * the head of the list.
641                  *
642                  * We also reverse, or doubly link the list through the
643                  * parent pointer.
644                  */
645                 if (tt == saved_tt) {
646                         struct  radix_node *xx = x;
647                         /* link in at head of list */
648                         (tt = treenodes)->rn_dupedkey = t;
649                         tt->rn_flags = t->rn_flags;
650                         tt->rn_p = x = t->rn_p;
651                         t->rn_p = tt;
652                         if (x->rn_l == t)
653                                 x->rn_l = tt;
654                         else
655                                 x->rn_r = tt;
656                         saved_tt = tt;
657                         x = xx;
658                 } else {
659                         (tt = treenodes)->rn_dupedkey = t->rn_dupedkey;
660                         t->rn_dupedkey = tt;
661                         tt->rn_p = t;
662                         if (tt->rn_dupedkey)
663                                 tt->rn_dupedkey->rn_p = tt;
664                 }
665 #ifdef RN_DEBUG
666                 t=tt+1;
667                 tt->rn_info = rn_nodenum++;
668                 t->rn_info = rn_nodenum++;
669                 tt->rn_twin = t;
670                 tt->rn_ybro = rn_clist;
671                 rn_clist = tt;
672 #endif
673                 tt->rn_key = (caddr_t) v;
674                 tt->rn_b = -1;
675                 tt->rn_flags = RNF_ACTIVE;
676         }
677         /*
678          * Put mask in tree.
679          */
680         if (netmask) {
681                 tt->rn_mask = netmask;
682                 tt->rn_b = x->rn_b;
683                 tt->rn_flags |= x->rn_flags & RNF_NORMAL;
684         }
685         t = saved_tt->rn_p;
686         if (keyduplicated)
687                 goto on2;
688         b_leaf = -1 - t->rn_b;
689         if (t->rn_r == saved_tt)
690                 x = t->rn_l;
691         else
692                 x = t->rn_r;
693         /* Promote general routes from below */
694         if (x->rn_b < 0) {
695             for (mp = &t->rn_mklist; x; x = x->rn_dupedkey)
696                 if (x->rn_mask && (x->rn_b >= b_leaf) && x->rn_mklist == 0) {
697                         *mp = m = rn_new_radix_mask(x, 0);
698                         if (m)
699                                 mp = &m->rm_mklist;
700                 }
701         } else if (x->rn_mklist) {
702                 /*
703                  * Skip over masks whose index is > that of new node
704                  */
705                 for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
706                         if (m->rm_b >= b_leaf)
707                                 break;
708                 t->rn_mklist = m;
709                 *mp = 0;
710         }
711 on2:
712         /* Add new route to highest possible ancestor's list */
713         if ((netmask == 0) || (b > t->rn_b ))
714                 return tt; /* can't lift at all */
715         b_leaf = tt->rn_b;
716         do {
717                 x = t;
718                 t = t->rn_p;
719         } while (b <= t->rn_b && x != top);
720         /*
721          * Search through routes associated with node to
722          * insert new route according to index.
723          * Need same criteria as when sorting dupedkeys to avoid
724          * double loop on deletion.
725          */
726         for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist) {
727                 if (m->rm_b < b_leaf)
728                         continue;
729                 if (m->rm_b > b_leaf)
730                         break;
731                 if (m->rm_flags & RNF_NORMAL) {
732                         mmask = m->rm_leaf->rn_mask;
733                         if (tt->rn_flags & RNF_NORMAL) {
734 #if 0
735                                 log(LOG_ERR, "Non-unique normal route,"
736                                     " mask not entered\n");
737 #endif
738                                 return tt;
739                         }
740                 } else
741                         mmask = m->rm_mask;
742                 if (mmask == netmask) {
743                         m->rm_refs++;
744                         tt->rn_mklist = m;
745                         return tt;
746                 }
747                 if (rn_refines(netmask, mmask)
748                     || rn_lexobetter(netmask, mmask))
749                         break;
750         }
751         *mp = rn_new_radix_mask(tt, *mp);
752         return tt;
753 }
754
755 struct radix_node *
756 rn_delete(v_arg, netmask_arg, head)
757         void *v_arg, *netmask_arg;
758         struct radix_node_head *head;
759 {
760         struct radix_node *t, *p, *x, *tt;
761         struct radix_mask *m, *saved_m, **mp;
762         struct radix_node *dupedkey, *saved_tt, *top;
763         caddr_t v, netmask;
764         int b, head_off, vlen;
765
766         v = v_arg;
767         netmask = netmask_arg;
768         x = head->rnh_treetop;
769         tt = rn_search(v, x);
770         head_off = x->rn_off;
771         vlen =  *(u_char *)v;
772         saved_tt = tt;
773         top = x;
774         if (tt == 0 ||
775             Bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off))
776                 return (0);
777         /*
778          * Delete our route from mask lists.
779          */
780         if (netmask) {
781                 if ((x = rn_addmask(netmask, 1, head_off)) == 0)
782                         return (0);
783                 netmask = x->rn_key;
784                 while (tt->rn_mask != netmask)
785                         if ((tt = tt->rn_dupedkey) == 0)
786                                 return (0);
787         }
788         if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0)
789                 goto on1;
790         if (tt->rn_flags & RNF_NORMAL) {
791                 if (m->rm_leaf != tt || m->rm_refs > 0) {
792 #if 0
793                         log(LOG_ERR, "rn_delete: inconsistent annotation\n");
794 #endif
795                         return 0;  /* dangling ref could cause disaster */
796                 }
797         } else {
798                 if (m->rm_mask != tt->rn_mask) {
799 #if 0
800                         log(LOG_ERR, "rn_delete: inconsistent annotation\n");
801 #endif
802                         goto on1;
803                 }
804                 if (--m->rm_refs >= 0)
805                         goto on1;
806         }
807         b = -1 - tt->rn_b;
808         t = saved_tt->rn_p;
809         if (b > t->rn_b)
810                 goto on1; /* Wasn't lifted at all */
811         do {
812                 x = t;
813                 t = t->rn_p;
814         } while (b <= t->rn_b && x != top);
815         for (mp = &x->rn_mklist; (m = *mp) != NULL; mp = &m->rm_mklist)
816                 if (m == saved_m) {
817                         *mp = m->rm_mklist;
818                         MKFree(m);
819                         break;
820                 }
821         if (m == 0) {
822 #if 0
823                 log(LOG_ERR, "rn_delete: couldn't find our annotation\n");
824 #endif
825                 if (tt->rn_flags & RNF_NORMAL)
826                         return (0); /* Dangling ref to us */
827         }
828 on1:
829         /*
830          * Eliminate us from tree
831          */
832         if (tt->rn_flags & RNF_ROOT)
833                 return (0);
834 #ifdef RN_DEBUG
835         /* Get us out of the creation list */
836         for (t = rn_clist; t && t->rn_ybro != tt; t = t->rn_ybro)
837                 ;
838         if (t) t->rn_ybro = tt->rn_ybro;
839 #endif
840         t = tt->rn_p;
841         dupedkey = saved_tt->rn_dupedkey;
842         if (dupedkey) {
843                 /*
844                  * Here, tt is the deletion target and
845                  * saved_tt is the head of the dupedkey chain.
846                  */
847                 if (tt == saved_tt) {
848                         x = dupedkey;
849                         x->rn_p = t;
850                         if (t->rn_l == tt)
851                                 t->rn_l = x;
852                         else
853                                 t->rn_r = x;
854                 } else {
855                         /* find node in front of tt on the chain */
856                         for (x = p = saved_tt; p && p->rn_dupedkey != tt;)
857                                 p = p->rn_dupedkey;
858                         if (p) {
859                                 p->rn_dupedkey = tt->rn_dupedkey;
860                                 if (tt->rn_dupedkey)
861                                         tt->rn_dupedkey->rn_p = p;
862                         }
863 #if 0
864                         else
865                                 log(LOG_ERR, "rn_delete: couldn't find us\n");
866 #endif
867                 }
868                 t = tt + 1;
869                 if  (t->rn_flags & RNF_ACTIVE) {
870 #ifndef RN_DEBUG
871                         *++x = *t;
872                         p = t->rn_p;
873 #else
874                         b = t->rn_info;
875                         *++x = *t;
876                         t->rn_info = b;
877                         p = t->rn_p;
878 #endif
879                         if (p->rn_l == t)
880                                 p->rn_l = x;
881                         else
882                                 p->rn_r = x;
883                         x->rn_l->rn_p = x;
884                         x->rn_r->rn_p = x;
885                 }
886                 goto out;
887         }
888         if (t->rn_l == tt)
889                 x = t->rn_r;
890         else
891                 x = t->rn_l;
892         p = t->rn_p;
893         if (p->rn_r == t)
894                 p->rn_r = x;
895         else
896                 p->rn_l = x;
897         x->rn_p = p;
898         /*
899          * Demote routes attached to us.
900          */
901         if (t->rn_mklist) {
902                 if (x->rn_b >= 0) {
903                         for (mp = &x->rn_mklist; (m = *mp) != NULL;)
904                                 mp = &m->rm_mklist;
905                         *mp = t->rn_mklist;
906                 } else {
907                         /* If there are any key,mask pairs in a sibling
908                            duped-key chain, some subset will appear sorted
909                            in the same order attached to our mklist */
910                         for (m = t->rn_mklist; m && x; x = x->rn_dupedkey)
911                                 if (m == x->rn_mklist) {
912                                         struct radix_mask *mm = m->rm_mklist;
913                                         x->rn_mklist = 0;
914                                         if (--(m->rm_refs) < 0)
915                                                 MKFree(m);
916                                         m = mm;
917                                 }
918 #if 0
919                         if (m)
920                                 log(LOG_ERR, "%s %p at %p\n",
921                                     "rn_delete: Orphaned Mask", m, x);
922 #endif
923                 }
924         }
925         /*
926          * We may be holding an active internal node in the tree.
927          */
928         x = tt + 1;
929         if (t != x) {
930 #ifndef RN_DEBUG
931                 *t = *x;
932 #else
933                 b = t->rn_info;
934                 *t = *x;
935                 t->rn_info = b;
936 #endif
937                 t->rn_l->rn_p = t;
938                 t->rn_r->rn_p = t;
939                 p = x->rn_p;
940                 if (p->rn_l == x)
941                         p->rn_l = t;
942                 else
943                         p->rn_r = t;
944         }
945 out:
946         tt->rn_flags &= ~RNF_ACTIVE;
947         tt[1].rn_flags &= ~RNF_ACTIVE;
948         return (tt);
949 }
950
951 int
952 rn_walktree(h, f, w)
953         struct radix_node_head *h;
954         int (*f) __P((struct radix_node *, void *));
955         void *w;
956 {
957         int error;
958         struct radix_node *base, *next;
959         struct radix_node *rn = h->rnh_treetop;
960         /*
961          * This gets complicated because we may delete the node
962          * while applying the function f to it, so we need to calculate
963          * the successor node in advance.
964          */
965         /* First time through node, go left */
966         while (rn->rn_b >= 0)
967                 rn = rn->rn_l;
968         for (;;) {
969                 base = rn;
970                 /* If at right child go back up, otherwise, go right */
971                 while (rn->rn_p->rn_r == rn && (rn->rn_flags & RNF_ROOT) == 0)
972                         rn = rn->rn_p;
973                 /* Find the next *leaf* since next node might vanish, too */
974                 for (rn = rn->rn_p->rn_r; rn->rn_b >= 0;)
975                         rn = rn->rn_l;
976                 next = rn;
977                 /* Process leaves */
978                 while ((rn = base) != NULL) {
979                         base = rn->rn_dupedkey;
980                         if (!(rn->rn_flags & RNF_ROOT)
981                             && (error = (*f)(rn, w)))
982                                 return (error);
983                 }
984                 rn = next;
985                 if (rn->rn_flags & RNF_ROOT)
986                         return (0);
987         }
988         /* NOTREACHED */
989 }
990
991 int
992 rn_inithead(head, off)
993         void **head;
994         int off;
995 {
996         struct radix_node_head *rnh;
997
998         if (*head)
999                 return (1);
1000         R_Malloc(rnh, struct radix_node_head *, sizeof (*rnh));
1001         if (rnh == 0)
1002                 return (0);
1003         *head = rnh;
1004         return rn_inithead0(rnh, off);
1005 }
1006
1007 int
1008 rn_inithead0(rnh, off)
1009         struct radix_node_head *rnh;
1010         int off;
1011 {
1012         struct radix_node *t, *tt, *ttt;
1013
1014         Bzero(rnh, sizeof (*rnh));
1015         t = rn_newpair(rn_zeros, off, rnh->rnh_nodes);
1016         ttt = rnh->rnh_nodes + 2;
1017         t->rn_r = ttt;
1018         t->rn_p = t;
1019         tt = t->rn_l;
1020         tt->rn_flags = t->rn_flags = RNF_ROOT | RNF_ACTIVE;
1021         tt->rn_b = -1 - off;
1022         *ttt = *tt;
1023         ttt->rn_key = rn_ones;
1024         rnh->rnh_addaddr = rn_addroute;
1025         rnh->rnh_deladdr = rn_delete;
1026         rnh->rnh_matchaddr = rn_match;
1027         rnh->rnh_lookup = rn_lookup;
1028         rnh->rnh_walktree = rn_walktree;
1029         rnh->rnh_treetop = t;
1030         return (1);
1031 }
1032
1033 void
1034 rn_init()
1035 {
1036         char *cp, *cplim;
1037
1038         if (max_keylen == 0) {
1039 #if 0
1040                 log(LOG_ERR,
1041                     "rn_init: radix functions require max_keylen be set\n");
1042 #endif
1043                 return;
1044         }
1045         if (rn_zeros == NULL) {
1046                 R_Malloc(rn_zeros, char *, 3 * max_keylen);
1047         }
1048         if (rn_zeros == NULL)
1049                 panic("rn_init");
1050         Bzero(rn_zeros, 3 * max_keylen);
1051         rn_ones = cp = rn_zeros + max_keylen;
1052         addmask_key = cplim = rn_ones + max_keylen;
1053         while (cp < cplim)
1054                 *cp++ = -1;
1055         if (rn_inithead((void *)&mask_rnhead, 0) == 0)
1056                 panic("rn_init 2");
1057 }
1058
1059
1060 static int
1061 rn_freenode(struct radix_node *n, void *p)
1062 {
1063         struct radix_node_head *rnh = p;
1064         struct radix_node *d;
1065
1066         d = rnh->rnh_deladdr(n->rn_key, NULL, rnh);
1067         if (d != NULL) {
1068                 FreeS(d, max_keylen + 2 * sizeof (*d));
1069         }
1070         return 0;
1071 }
1072
1073
1074 void
1075 rn_freehead(rnh)
1076       struct radix_node_head *rnh;
1077 {
1078
1079         (void)rn_walktree(rnh, rn_freenode, rnh);
1080
1081         rnh->rnh_addaddr = NULL;
1082         rnh->rnh_deladdr = NULL;
1083         rnh->rnh_matchaddr = NULL;
1084         rnh->rnh_lookup = NULL;
1085         rnh->rnh_walktree = NULL;
1086
1087         Free(rnh);
1088 }
1089
1090
1091 void
1092 rn_fini()
1093 {
1094         struct radix_mask *m;
1095
1096         if (rn_zeros != NULL) {
1097                 FreeS(rn_zeros, 3 * max_keylen);
1098                 rn_zeros = NULL;
1099         }
1100
1101         if (mask_rnhead != NULL) {
1102                 rn_freehead(mask_rnhead);
1103                 mask_rnhead = NULL;
1104         }
1105
1106         while ((m = rn_mkfreelist) != NULL) {
1107                 rn_mkfreelist = m->rm_mklist;
1108                 KFREE(m);
1109         }
1110 }
1111
1112
1113 #ifdef  USE_MAIN
1114
1115 typedef struct myst {
1116         addrfamily_t    dst;
1117         addrfamily_t    mask;
1118         struct radix_node nodes[2];
1119 } myst_t;
1120
1121 int
1122 main(int argc, char *argv[])
1123 {
1124         struct radix_node_head *rnh;
1125         struct radix_node *rn;
1126         addrfamily_t af, mf;
1127         myst_t st1, st2, *stp;
1128
1129         memset(&st1, 0, sizeof(st1));
1130         memset(&st2, 0, sizeof(st2));
1131         memset(&af, 0, sizeof(af));
1132
1133         rn_init();
1134
1135         rnh = NULL;
1136         rn_inithead(&rnh, offsetof(addrfamily_t, adf_addr) << 3);
1137
1138         st1.dst.adf_len = sizeof(st1);
1139         st1.mask.adf_len = sizeof(st1);
1140         st1.dst.adf_addr.in4.s_addr = inet_addr("127.0.0.0");
1141         st1.mask.adf_addr.in4.s_addr = inet_addr("255.0.0.0");
1142         rn = rnh->rnh_addaddr(&st1.dst, &st1.mask, rnh, st1.nodes);
1143         printf("add.1 %p\n", rn);
1144
1145         st2.dst.adf_len = sizeof(st2);
1146         st2.mask.adf_len = sizeof(st2);
1147         st2.dst.adf_addr.in4.s_addr = inet_addr("127.0.1.0");
1148         st2.mask.adf_addr.in4.s_addr = inet_addr("255.255.255.0");
1149         rn = rnh->rnh_addaddr(&st2.dst, &st2.mask, rnh, st2.nodes);
1150         printf("add.2 %p\n", rn);
1151
1152         af.adf_len = sizeof(af);
1153         af.adf_addr.in4.s_addr = inet_addr("127.0.1.0");
1154         rn = rnh->rnh_matchaddr(&af, rnh);
1155         if (rn != NULL) {
1156                 printf("1.lookup = %p key %p mask %p\n", rn, rn->rn_key, rn->rn_mask);
1157                 stp = rn->rn_key;
1158                 printf("%s/", inet_ntoa(stp->dst.adf_addr.in4));
1159                 stp = rn->rn_mask;
1160                 printf("%s\n", inet_ntoa(stp->dst.adf_addr.in4));
1161         }
1162
1163         mf.adf_len = sizeof(mf);
1164         mf.adf_addr.in4.s_addr = inet_addr("255.255.255.0");
1165         rn = rnh->rnh_lookup(&af, &mf, rnh);
1166         if (rn != NULL) {
1167                 printf("2.lookup = %p key %p mask %p\n", rn, rn->rn_key, rn->rn_mask);
1168                 stp = rn->rn_key;
1169                 printf("%s/", inet_ntoa(stp->dst.adf_addr.in4));
1170                 stp = rn->rn_mask;
1171                 printf("%s\n", inet_ntoa(stp->dst.adf_addr.in4));
1172         }
1173
1174         af.adf_len = sizeof(af);
1175         af.adf_addr.in4.s_addr = inet_addr("126.0.0.1");
1176         rn = rnh->rnh_matchaddr(&af, rnh);
1177         if (rn != NULL) {
1178                 printf("3.lookup = %p key %p mask %p\n", rn, rn->rn_key, rn->rn_mask);
1179                 stp = rn->rn_key;
1180                 printf("%s/", inet_ntoa(stp->dst.adf_addr.in4));
1181                 stp = rn->rn_mask;
1182                 printf("%s\n", inet_ntoa(stp->dst.adf_addr.in4));
1183         }
1184
1185         return 0;
1186 }
1187
1188
1189 void
1190 log(int level, char *format, ...)
1191 {
1192         va_list ap;
1193
1194         va_start(ap, format);
1195         vfprintf(stderr, format, ap);
1196         va_end(ap);
1197 }
1198 #endif
1199
1200
1201 #ifndef _KERNEL
1202 void
1203 panic(char *str)
1204 {
1205         fputs(str, stderr);
1206         abort();
1207 }
1208 #endif