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