radix.c 31 KB

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