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