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