constraint.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <assert.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. #include "../lib/constraint.h"
  11. #include "../lib/logger.h"
  12. #include "../lib/xalloc.h"
  13. //
  14. // Efficient address-space constraints (AH 7/2013)
  15. //
  16. // This module uses a tree-based representation to efficiently
  17. // manipulate and query constraints on the address space to be
  18. // scanned. It provides a value for every IP address, and these
  19. // values are applied by setting them for network prefixes. Order
  20. // matters: setting a value replaces any existing value for that
  21. // prefix or subsets of it. We use this to implement network
  22. // whitelisting and blacklisting.
  23. //
  24. // Think of setting values in this structure like painting
  25. // subnets with different colors. We can paint subnets black to
  26. // exclude them and white to allow them. Only the top color shows.
  27. // This makes for potentially very powerful constraint specifications.
  28. //
  29. // Internally, this is implemented using a binary tree, where each
  30. // node corresponds to a network prefix. (E.g., the root is
  31. // 0.0.0.0/0, and its children, if present, are 0.0.0.0/1 and
  32. // 128.0.0.0/1.) Each leaf of the tree stores the value that applies
  33. // to every address within the leaf's portion of the prefix space.
  34. //
  35. // As an optimization, after all values are set, we look up the
  36. // value or subtree for every /16 prefix and cache them as an array.
  37. // This lets subsequent lookups bypass the bottom half of the tree.
  38. //
  39. /*
  40. * Constraint Copyright 2013 Regents of the University of Michigan
  41. *
  42. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  43. * use this file except in compliance with the License. You may obtain a copy
  44. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  45. */
  46. typedef struct node {
  47. struct node *l;
  48. struct node *r;
  49. value_t value;
  50. uint64_t count;
  51. } node_t;
  52. // As an optimization, we precompute lookups for every prefix of this
  53. // length:
  54. #define RADIX_LENGTH 20
  55. struct _constraint {
  56. node_t *root; // root node of the tree
  57. uint32_t *radix; // array of prefixes (/RADIX_LENGTH) that are painted paint_value
  58. size_t radix_len; // number of prefixes in radix array
  59. int painted; // have we precomputed counts for each node?
  60. value_t paint_value; // value for which we precomputed counts
  61. };
  62. // Tree operations respect the invariant that every node that isn't a
  63. // leaf has exactly two children.
  64. #define IS_LEAF(node) ((node)->l == NULL)
  65. // Allocate a new leaf with the given value
  66. static node_t* _create_leaf(value_t value)
  67. {
  68. node_t *node = xmalloc(sizeof(node_t));
  69. node->l = NULL;
  70. node->r = NULL;
  71. node->value = value;
  72. return node;
  73. }
  74. // Free the subtree rooted at node.
  75. static void _destroy_subtree(node_t *node)
  76. {
  77. if (node == NULL)
  78. return;
  79. _destroy_subtree(node->l);
  80. _destroy_subtree(node->r);
  81. free(node);
  82. }
  83. // Convert from an internal node to a leaf.
  84. static void _convert_to_leaf(node_t *node)
  85. {
  86. assert(node);
  87. assert(!IS_LEAF(node));
  88. _destroy_subtree(node->l);
  89. _destroy_subtree(node->r);
  90. node->l = NULL;
  91. node->r = NULL;
  92. }
  93. // Recursive function to set value for a given network prefix within
  94. // the tree. (Note: prefix must be in host byte order.)
  95. static void _set_recurse(node_t *node, uint32_t prefix, int len, value_t value)
  96. {
  97. assert(node);
  98. assert(0 <= len && len <= 32);
  99. if (len == 0) {
  100. // We're at the end of the prefix; make this a leaf and set the value.
  101. if (!IS_LEAF(node)) {
  102. _convert_to_leaf(node);
  103. }
  104. node->value = value;
  105. return;
  106. }
  107. if (IS_LEAF(node)) {
  108. // We're not at the end of the prefix, but we hit a leaf.
  109. if (node->value == value) {
  110. // A larger prefix has the same value, so we're done.
  111. return;
  112. }
  113. // The larger prefix has a different value, so we need to convert it
  114. // into an internal node and continue processing on one of the leaves.
  115. node->l = _create_leaf(node->value);
  116. node->r = _create_leaf(node->value);
  117. }
  118. // We're not at the end of the prefix, and we're at an internal
  119. // node. Recurse on the left or right subtree.
  120. if (prefix & 0x80000000) {
  121. _set_recurse(node->r, prefix << 1, len - 1, value);
  122. } else {
  123. _set_recurse(node->l, prefix << 1, len - 1, value);
  124. }
  125. // At this point, we're an internal node, and the value is set
  126. // by one of our children or its descendent. If both children are
  127. // leaves with the same value, we can discard them and become a left.
  128. if (IS_LEAF(node->r) && IS_LEAF(node->l) && node->r->value == node->l->value) {
  129. node->value = node->l->value;
  130. _convert_to_leaf(node);
  131. }
  132. }
  133. // Set the value for a given network prefix, overwriting any existing
  134. // values on that prefix or subsets of it.
  135. // (Note: prefix must be in host byte order.)
  136. void constraint_set(constraint_t *con, uint32_t prefix, int len, value_t value)
  137. {
  138. assert(con);
  139. _set_recurse(con->root, prefix, len, value);
  140. con->painted = 0;
  141. }
  142. // Return the value pertaining to an address, according to the tree
  143. // starting at given root. (Note: address must be in host byte order.)
  144. static int _lookup_ip(node_t *root, uint32_t address)
  145. {
  146. assert(root);
  147. node_t *node = root;
  148. uint32_t mask = 0x80000000;
  149. for (;;) {
  150. if (IS_LEAF(node)) {
  151. return node->value;
  152. }
  153. if (address & mask) {
  154. node = node->r;
  155. } else {
  156. node = node->l;
  157. }
  158. mask >>= 1;
  159. }
  160. }
  161. // Return the value pertaining to an address.
  162. // (Note: address must be in host byte order.)
  163. value_t constraint_lookup_ip(constraint_t *con, uint32_t address)
  164. {
  165. assert(con);
  166. return _lookup_ip(con->root, address);
  167. }
  168. // Return the nth painted IP address.
  169. static int _lookup_index(node_t *root, uint64_t n)
  170. {
  171. assert(root);
  172. node_t *node = root;
  173. uint32_t ip = 0;
  174. uint32_t mask = 0x80000000;
  175. for (;;) {
  176. if (IS_LEAF(node)) {
  177. return ip | n;
  178. }
  179. if (n < node->l->count) {
  180. node = node->l;
  181. } else {
  182. n -= node->l->count;
  183. node = node->r;
  184. ip |= mask;
  185. }
  186. mask >>= 1;
  187. }
  188. }
  189. // For a given value, return the IP address with zero-based index n.
  190. // (i.e., if there are three addresses with value 0xFF, looking up index 1
  191. // will return the second one).
  192. // Note that the tree must have been previously painted with this value.
  193. uint32_t constraint_lookup_index(constraint_t *con, uint64_t index, value_t value)
  194. {
  195. assert(con);
  196. if (!con->painted || con->paint_value != value) {
  197. constraint_paint_value(con, value);
  198. }
  199. uint64_t radix_idx = index / (1 << (32 - RADIX_LENGTH));
  200. if (radix_idx < con->radix_len) {
  201. // Radix lookup
  202. uint32_t radix_offset = index % (1 << (32 - RADIX_LENGTH)); // TODO: bitwise maths
  203. return con->radix[radix_idx] | radix_offset;
  204. }
  205. // Otherwise, do the "slow" lookup in tree.
  206. // Note that tree counts do NOT include things in the radix,
  207. // so we subtract these off here.
  208. index -= con->radix_len * (1 << (32 - RADIX_LENGTH));
  209. assert(index < con->root->count);
  210. return _lookup_index(con->root, index);
  211. }
  212. // Implement count_ips by recursing on halves of the tree. Size represents
  213. // the number of addresses in a prefix at the current level of the tree.
  214. // If paint is specified, each node will have its count set to the number of
  215. // leaves under it set to value.
  216. // If exclude_radix is specified, the number of addresses will exlcude prefixes
  217. // that are a /RADIX_LENGTH or larger
  218. static uint64_t _count_ips_recurse(node_t *node, value_t value,
  219. uint64_t size, int paint, int exclude_radix)
  220. {
  221. assert(node);
  222. uint64_t n;
  223. if (IS_LEAF(node)) {
  224. if (node->value == value) {
  225. n = size;
  226. // Exclude prefixes already included in the radix
  227. if (exclude_radix && size >= (1 << (32 -RADIX_LENGTH))) {
  228. n = 0;
  229. }
  230. } else {
  231. n = 0;
  232. }
  233. } else {
  234. n = _count_ips_recurse(node->l, value, size >> 1, paint, exclude_radix) +
  235. _count_ips_recurse(node->r, value, size >> 1, paint, exclude_radix);
  236. }
  237. if (paint) {
  238. node->count = n;
  239. }
  240. return n;
  241. }
  242. // Return a node that determines the values for the addresses with
  243. // the given prefix. This is either the internal node that
  244. // corresponds to the end of the prefix or a leaf node that
  245. // encompasses the prefix. (Note: prefix must be in host byte order.)
  246. static node_t* _lookup_node(node_t *root, uint32_t prefix, int len)
  247. {
  248. assert(root);
  249. assert(0 <= len && len <= 32);
  250. node_t *node = root;
  251. uint32_t mask = 0x80000000;
  252. int i;
  253. for (i=0; i < len; i++) {
  254. if (IS_LEAF(node)) {
  255. return node;
  256. }
  257. if (prefix & mask) {
  258. node = node->r;
  259. } else {
  260. node = node->l;
  261. }
  262. mask >>= 1;
  263. }
  264. return node;
  265. }
  266. // For each node, precompute the count of leaves beneath it set to value.
  267. // Note that the tree can be painted for only one value at a time.
  268. void constraint_paint_value(constraint_t *con, value_t value)
  269. {
  270. assert(con);
  271. log_trace("constraint", "Painting value %lu", value);
  272. // Paint everything except what we will put in radix
  273. _count_ips_recurse(con->root, value, (uint64_t)1 << 32, 1, 1);
  274. // Fill in the radix array with a list of addresses
  275. uint32_t i;
  276. con->radix_len = 0;
  277. for (i=0; i < (1 << RADIX_LENGTH); i++) {
  278. uint32_t prefix = i << (32 - RADIX_LENGTH);
  279. node_t *node = _lookup_node(con->root, prefix, RADIX_LENGTH);
  280. if (IS_LEAF(node) && node->value == value) {
  281. // Add this prefix to the radix
  282. con->radix[con->radix_len++] = prefix;
  283. }
  284. }
  285. log_debug("constraint", "%lu IPs in radix array, %lu IPs in tree",
  286. con->radix_len * (1 << (32 - RADIX_LENGTH)), con->root->count);
  287. con->painted = 1;
  288. con->paint_value = value;
  289. }
  290. // Return the number of addresses that have a given value.
  291. uint64_t constraint_count_ips(constraint_t *con, value_t value)
  292. {
  293. assert(con);
  294. if (con->painted && con->paint_value == value) {
  295. return con->root->count + con->radix_len * (1 << (32 - RADIX_LENGTH));
  296. } else {
  297. return _count_ips_recurse(con->root, value, (uint64_t)1 << 32, 0, 0);
  298. }
  299. }
  300. // Initialize the tree.
  301. // All addresses will initally have the given value.
  302. constraint_t* constraint_init(value_t value)
  303. {
  304. constraint_t* con = xmalloc(sizeof(constraint_t));
  305. con->root = _create_leaf(value);
  306. con->radix = xcalloc(sizeof(uint32_t), 1 << RADIX_LENGTH);
  307. con->painted = 0;
  308. return con;
  309. }
  310. // Deinitialize and free the tree.
  311. void constraint_free(constraint_t *con)
  312. {
  313. assert(con);
  314. log_trace("constraint", "Cleaning up");
  315. _destroy_subtree(con->root);
  316. free(con->radix);
  317. free(con);
  318. }
  319. /*
  320. int main(void)
  321. {
  322. log_init(stderr, LOG_DEBUG);
  323. constraint_t *con = constraint_init(0);
  324. constraint_set(con, ntohl(inet_addr("128.128.0.0")), 1, 22);
  325. constraint_set(con, ntohl(inet_addr("128.128.0.0")), 1, 1);
  326. constraint_set(con, ntohl(inet_addr("128.0.0.0")), 1, 1);
  327. constraint_set(con, ntohl(inet_addr("10.0.0.0")), 24, 1);
  328. constraint_set(con, ntohl(inet_addr("10.0.0.0")), 24, 0);
  329. constraint_set(con, ntohl(inet_addr("10.11.12.0")), 24, 1);
  330. constraint_set(con, ntohl(inet_addr("141.212.0.0")), 16, 0);
  331. for (int x=1; x < 2; x++) {
  332. if (x == 1) {
  333. constraint_optimize(con);
  334. }
  335. printf("count(0)=%ld\n", constraint_count_ips(con, 0));
  336. printf("count(1)=%ld\n", constraint_count_ips(con, 1));
  337. printf("%d\n", constraint_lookup_ip(con,ntohl(inet_addr("10.11.12.0"))));
  338. assert(constraint_count_ips(con, 0) + constraint_count_ips(con, 1) == (uint64_t)1 << 32);
  339. uint32_t i=0, count=0;
  340. do {
  341. if (constraint_lookup_ip(con, i))
  342. count++;
  343. } while (++i != 0);
  344. printf("derived count(1)=%u\n", count);
  345. }
  346. constraint_free(con);
  347. }
  348. */