+class IpRule:
+ def __init__(self, ty, offset, net, proto):
+ self.ty = ty
+ self.offset = offset
+ if offset is None:
+ self.offset = 0
+ self.net = net
+ self.proto = proto
+
+ def ord(self, other):
+ assert self.ty == other.ty
+ assert self.proto == other.proto
+ if self.offset < other.offset:
+ return ORD_LESS
+ if self.offset > other.offset:
+ return ORD_GREATER
+
+ if self.net.overlaps(other.net):
+ if self.net.prefixlen > other.net.prefixlen:
+ return ORD_LESS
+ elif self.net.prefixlen < other.net.prefixlen:
+ return ORD_GREATER
+ else:
+ if self.net < other.net:
+ return ORD_LESS
+ else:
+ assert self.net > other.net
+ return ORD_GREATER
+
+ return ORD_EQUAL
+
+ def __lt__(self, other):
+ return self.ord(other) == ORD_LESS
+
+ def __eq__(self, other):
+ return type(other) == IpRule and self.ty == other.ty and self.offset == other.offset and self.net == other.net and self.proto == other.proto
+
+ def __str__(self):
+ if self.proto == 4:
+ assert self.offset == 0
+ return f"""if ((ip->{self.ty} & MASK4({self.net.prefixlen})) != BIGEND32({int(self.net.network_address)}ULL))
+ break;"""
+ else:
+ u32s = [(int(self.net.network_address) >> (3*32)) & 0xffffffff,
+ (int(self.net.network_address) >> (2*32)) & 0xffffffff,
+ (int(self.net.network_address) >> (1*32)) & 0xffffffff,
+ (int(self.net.network_address) >> (0*32)) & 0xffffffff]
+ if self.offset == 0:
+ mask = f"MASK6({self.net.prefixlen})"
+ else:
+ mask = f"MASK6_OFFS({self.offset}, {self.net.prefixlen})"
+ return f"""if ((ip6->{self.ty} & {mask}) != (BIGEND128({u32s[0]}ULL, {u32s[1]}ULL, {u32s[2]}ULL, {u32s[3]}ULL) & {mask}))
+ break;"""