+#include "connection.h"
+#include "subnet.h"
+#include "system.h"
+
+#include <utils.h>
+#include <xalloc.h>
+#include <rbl.h>
+
+/* lists type of subnet */
+
+rbltree_t *subnet_tree;
+
+void init_subnets(void)
+{
+cp
+ subnet_tree = new_rbltree((rbl_compare_t)subnet_compare, (rbl_action_t)free_subnet);
+cp
+}
+
+/* Subnet comparison */
+
+int subnet_compare_mac(subnet_t *a, subnet_t *b)
+{
+cp
+ return memcmp(&a->net.mac.address, &b->net.mac.address, sizeof(mac_t));
+}
+
+int subnet_compare_ipv4(subnet_t *a, subnet_t *b)
+{
+cp
+ /* If the subnet of a falls within the range of subnet b,
+ then we consider a smaller then b.
+ Otherwise, the addresses alone (and not the subnet masks) will be compared.
+ */
+
+ if(a->net.ipv4.mask > b->net.ipv4.mask)
+ if((a->net.ipv4.address & b->net.ipv4.mask) == b->net.ipv4.address)
+ return -1;
+
+ return a->net.ipv4.address - b->net.ipv4.address;
+}
+
+int subnet_compare_ipv6(subnet_t *a, subnet_t *b)
+{
+cp
+ /* Same as ipv4 case, but with nasty 128 bit addresses */
+
+ if(memcmp(&a->net.ipv6.mask, &b->net.ipv6.mask, sizeof(ipv6_t)) > 0)
+ if((a->net.ipv6.address.x[0] & b->net.ipv6.mask.x[0]) == b->net.ipv6.address.x[0] &&
+ (a->net.ipv6.address.x[1] & b->net.ipv6.mask.x[1]) == b->net.ipv6.address.x[1] &&
+ (a->net.ipv6.address.x[2] & b->net.ipv6.mask.x[2]) == b->net.ipv6.address.x[2] &&
+ (a->net.ipv6.address.x[3] & b->net.ipv6.mask.x[3]) == b->net.ipv6.address.x[3] &&
+ (a->net.ipv6.address.x[4] & b->net.ipv6.mask.x[4]) == b->net.ipv6.address.x[4] &&
+ (a->net.ipv6.address.x[5] & b->net.ipv6.mask.x[5]) == b->net.ipv6.address.x[5] &&
+ (a->net.ipv6.address.x[6] & b->net.ipv6.mask.x[6]) == b->net.ipv6.address.x[6] &&
+ (a->net.ipv6.address.x[7] & b->net.ipv6.mask.x[7]) == b->net.ipv6.address.x[7])
+ return -1;
+
+ return memcmp(&a->net.ipv6.address, &b->net.ipv6.address, sizeof(ipv6_t));
+}
+
+int subnet_compare(subnet_t *a, subnet_t *b)
+{
+ int x;
+cp
+ x = a->type - b->type;
+ if(x)
+ return x;
+
+ switch(a->type)
+ {
+ case SUBNET_MAC:
+ return subnet_compare_mac(a, b);
+ case SUBNET_IPV4:
+ return subnet_compare_ipv4(a, b);
+ case SUBNET_IPV6:
+ return subnet_compare_ipv6(a, b);
+ default:
+ syslog(LOG_ERR, _("subnet_compare() was called with unknown subnet type %d, restarting!"), a->type);
+ sighup = 1;
+ return 0;
+ }
+}