+#include "node.h"
+#include "subnet.h"
+#include "system.h"
+
+#include <utils.h>
+#include <xalloc.h>
+#include <avl_tree.h>
+
+/* lists type of subnet */
+
+avl_tree_t *subnet_tree;
+
+void init_subnets(void)
+{
+cp
+ subnet_tree = avl_alloc_tree((avl_compare_t)subnet_compare, (avl_action_t)free_subnet);
+cp
+}
+
+/* Subnet comparison */
+
+int subnet_compare_mac(subnet_t *a, subnet_t *b)
+{
+ int result;
+cp
+ result = memcmp(&a->net.mac.address, &b->net.mac.address, sizeof(mac_t));
+
+ if(result)
+ return result;
+
+ return strcmp(a->owner->name, b->owner->name);
+}
+
+int subnet_compare_ipv4(subnet_t *a, subnet_t *b)
+{
+cp
+ /* We compare as if a subnet is a number that equals (address << 32 + netmask). */
+
+ if(a->net.ipv4.address < b->net.ipv4.address)
+ return -1;
+ else if(a->net.ipv4.address > b->net.ipv4.address)
+ return 1;
+
+ if(a->net.ipv4.mask < b->net.ipv4.mask)
+ return -1;
+ else if(a->net.ipv4.mask > b->net.ipv4.mask)
+ return 1;
+
+ return strcmp(a->owner->name, b->owner->name);
+}
+
+int subnet_compare_ipv6(subnet_t *a, subnet_t *b)
+{
+ int result;
+cp
+ /* Same as ipv4 case, but with nasty 128 bit addresses */
+
+ result = memcmp(a->net.ipv6.address.x, b->net.ipv6.address.x, sizeof(ipv6_t));
+
+ if(result)
+ return result;
+
+ result = memcmp(a->net.ipv6.mask.x, b->net.ipv6.mask.x, sizeof(ipv6_t));
+
+ if(result)
+ return result;
+
+ return strcmp(a->owner->name, b->owner->name);
+}
+
+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;
+ }
+}