Combine redundant rule conditions to work around LLVM bug 52455 fully
[flowspec-xdp] / genrules.py
1 #!/usr/bin/env python3
2
3 import sys
4 import ipaddress
5 from enum import Enum
6 import argparse
7 import math
8
9
10 IP_PROTO_ICMP = 1
11 IP_PROTO_ICMPV6 = 58
12 IP_PROTO_TCP = 6
13 IP_PROTO_UDP = 17
14
15 class ASTAction(Enum):
16     OR = 1
17     AND = 2
18     NOT = 3
19     FALSE = 4
20     TRUE = 5
21     EXPR = 6
22 class ASTNode:
23     def __init__(self, action, left, right=None):
24         self.action = action
25         if action == ASTAction.FALSE or action == ASTAction.TRUE:
26             assert left is None and right is None
27             return
28         self.left = left
29         if right is None:
30             assert action == ASTAction.EXPR or action == ASTAction.NOT
31         else:
32             self.right = right
33
34     def write(self, expr_param, expr_param2=None):
35         if self.action == ASTAction.OR:
36             return "(" + self.left.write(expr_param, expr_param2) + ") || (" + self.right.write(expr_param, expr_param2) + ")"
37         if self.action == ASTAction.AND:
38             return "(" + self.left.write(expr_param, expr_param2) + ") && (" + self.right.write(expr_param, expr_param2) + ")"
39         if self.action == ASTAction.NOT:
40             return "!(" + self.left.write(expr_param, expr_param2) + ")"
41         if self.action == ASTAction.FALSE:
42             return "0"
43         if self.action == ASTAction.TRUE:
44             return "1"
45         if self.action == ASTAction.EXPR:
46             return self.left.write(expr_param, expr_param2)
47
48 def parse_ast(expr, parse_expr, comma_is_or):
49     expr = expr.strip()
50
51     comma_split = expr.split(",", 1)
52     or_split = expr.split("||", 1)
53     if len(comma_split) > 1 and not "||" in comma_split[0]:
54         # Confusingly, BIRD uses `,` as either || or &&, depending on the type
55         # of expression being parsed. Specifically, a `numbers-match` uses `,`
56         # as OR, whereas a `bitmask-match` uses `,` as AND.
57         if comma_is_or:
58             return ASTNode(ASTAction.OR, parse_ast(comma_split[0], parse_expr, comma_is_or), parse_ast(comma_split[1], parse_expr, comma_is_or))
59         else:
60             return ASTNode(ASTAction.AND, parse_ast(comma_split[0], parse_expr, comma_is_or), parse_ast(comma_split[1], parse_expr, comma_is_or))
61     if len(or_split) > 1:
62         assert not "," in or_split[0]
63         return ASTNode(ASTAction.OR, parse_ast(or_split[0], parse_expr, comma_is_or), parse_ast(or_split[1], parse_expr, comma_is_or))
64
65     and_split = expr.split("&&", 1)
66     if len(and_split) > 1:
67         return ASTNode(ASTAction.AND, parse_ast(and_split[0], parse_expr, comma_is_or), parse_ast(and_split[1], parse_expr, comma_is_or))
68
69     if expr.strip() == "true":
70         return ASTNode(ASTAction.TRUE, None)
71     if expr.strip() == "false":
72         return ASTNode(ASTAction.FALSE, None)
73
74     if expr.startswith("!"):
75         return ASTNode(ASTAction.NOT, parse_ast(expr[1:], parse_expr, comma_is_or))
76
77     return parse_expr(expr)
78
79
80 class NumbersAction(Enum):
81     EQ = "=="
82     GT = ">"
83     GTOE = ">="
84     LT = "<"
85     LTOE = "<="
86 class NumbersExpr:
87     def __init__(self, action, val):
88         self.action = action
89         self.val = val
90
91     def write(self, param, param2):
92         if param2 is not None:
93             return "(" + param + self.action.value + self.val + ") || (" + param2 + self.action.value + self.val + ")"
94         return param + self.action.value + self.val
95
96 def parse_numbers_expr(expr):
97     space_split = expr.split(" ")
98     if expr.startswith(">="):
99         assert len(space_split) == 2
100         return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GTOE, space_split[1]))
101     if expr.startswith(">"):
102         assert len(space_split) == 2
103         return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GT, space_split[1]))
104     if expr.startswith("<="):
105         assert len(space_split) == 2
106         return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LTOE, space_split[1]))
107     if expr.startswith("<"):
108         assert len(space_split) == 2
109         return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LT, space_split[1]))
110     if ".." in expr:
111         rangesplit = expr.split("..")
112         assert len(rangesplit) == 2
113         #XXX: Are ranges really inclusive,inclusive?
114         left = ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GTOE, rangesplit[0]))
115         right = ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LTOE, rangesplit[1]))
116         return ASTNode(ASTAction.AND, left, right)
117     
118     if expr.startswith("= "):
119         expr = expr[2:]
120     return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.EQ, expr))
121
122 class FragExpr(Enum):
123     IF = 1
124     FF = 2
125     DF = 3
126     LF = 4
127
128     def write(self, ipproto, _param2):
129         if ipproto == 4:
130             if self == FragExpr.IF:
131                 return "(ip->frag_off & BE16(IP_MF|IP_OFFSET)) != 0"
132             elif self == FragExpr.FF:
133                 return "((ip->frag_off & BE16(IP_MF)) != 0 && (ip->frag_off & BE16(IP_OFFSET)) == 0)"
134             elif self == FragExpr.DF:
135                 return "(ip->frag_off & BE16(IP_DF)) != 0"
136             elif self == FragExpr.LF:
137                 return "((ip->frag_off & BE16(IP_MF)) == 0 && (ip->frag_off & BE16(IP_OFFSET)) != 0)"
138             else:
139                 assert False
140         else:
141             if self == FragExpr.IF:
142                 return "frag6 != NULL"
143             elif self == FragExpr.FF:
144                 return "(frag6 != NULL && (frag6->frag_off & BE16(IP6_MF)) != 0 && (frag6->frag_off & BE16(IP6_FRAGOFF)) == 0)"
145             elif self == FragExpr.DF:
146                 assert False # No such thing in v6
147             elif self == FragExpr.LF:
148                 return "(frag6 != NULL && (frag6->frag_off & BE16(IP6_MF)) == 0 && (frag6->frag_off & BE16(IP6_FRAGOFF)) != 0)"
149             else:
150                 assert False
151
152 def parse_frag_expr(expr):
153     if expr == "is_fragment":
154         return ASTNode(ASTAction.EXPR, FragExpr.IF)
155     elif expr == "first_fragment":
156         return ASTNode(ASTAction.EXPR, FragExpr.FF)
157     elif expr == "dont_fragment":
158         return ASTNode(ASTAction.EXPR, FragExpr.DF)
159     elif expr == "last_fragment":
160         return ASTNode(ASTAction.EXPR, FragExpr.LF)
161     else:
162         assert False
163
164 class BitExpr:
165     def __init__(self, val):
166         s = val.split("/")
167         assert len(s) == 2
168         self.match = s[0]
169         self.mask = s[1]
170
171     def write(self, param, _param2):
172         return f"({param} & {self.mask}) == {self.match}"
173
174 def parse_bit_expr(expr):
175     return ASTNode(ASTAction.EXPR, BitExpr(expr))
176
177
178 def ip_to_rule(proto, inip, ty, offset):
179     if proto == 4:
180         assert offset is None
181         net = ipaddress.IPv4Network(inip.strip())
182         if net.prefixlen == 0:
183             return ""
184         return f"""if ((ip->{ty} & MASK4({net.prefixlen})) != BIGEND32({int(net.network_address)}ULL))
185         break;"""
186     else:
187         net = ipaddress.IPv6Network(inip.strip())
188         if net.prefixlen == 0:
189             return ""
190         u32s = [(int(net.network_address) >> (3*32)) & 0xffffffff,
191                 (int(net.network_address) >> (2*32)) & 0xffffffff,
192                 (int(net.network_address) >> (1*32)) & 0xffffffff,
193                 (int(net.network_address) >> (0*32)) & 0xffffffff]
194         if offset is None:
195             mask = f"MASK6({net.prefixlen})"
196         else:
197             mask = f"MASK6_OFFS({offset}, {net.prefixlen})"
198         return f"""if ((ip6->{ty} & {mask}) != (BIGEND128({u32s[0]}ULL, {u32s[1]}ULL, {u32s[2]}ULL, {u32s[3]}ULL) & {mask}))
199         break;"""
200
201 def fragment_to_rule(ipproto, rules):
202     ast = parse_ast(rules, parse_frag_expr, False)
203     return "if (!( " + ast.write(ipproto) + " )) break;"
204
205 def len_to_rule(rules):
206     ast = parse_ast(rules, parse_numbers_expr, True)
207     return "if (!( " + ast.write("(data_end - pktdata)") + " )) break;"
208  
209 def proto_to_rule(ipproto, proto):
210     ast = parse_ast(proto, parse_numbers_expr, True)
211
212     if ipproto == 4:
213         return "if (!( " + ast.write("ip->protocol") + " )) break;"
214     else:
215         return "if (!( " + ast.write("ip6->nexthdr") + " )) break;"
216
217 def icmp_type_to_rule(proto, ty):
218     ast = parse_ast(ty, parse_numbers_expr, True)
219     if proto == 4:
220         return "if (icmp == NULL) break;\nif (!( " + ast.write("icmp->type") + " )) break;"
221     else:
222         return "if (icmpv6 == NULL) break;\nif (!( " + ast.write("icmpv6->icmp6_type") + " )) break;"
223
224 def icmp_code_to_rule(proto, code):
225     ast = parse_ast(code, parse_numbers_expr, True)
226     if proto == 4:
227         return "if (icmp == NULL) break;\nif (!( " + ast.write("icmp->code") + " )) break;"
228     else:
229         return "if (icmpv6 == NULL) break;\nif (!( " + ast.write("icmpv6->icmp6_code") + " )) break;"
230
231 def dscp_to_rule(proto, rules):
232     ast = parse_ast(rules, parse_numbers_expr, True)
233
234     if proto == 4:
235         return "if (!( " + ast.write("((ip->tos & 0xfc) >> 2)") + " )) break;"
236     else:
237         return "if (!( " + ast.write("((ip6->priority << 2) | ((ip6->flow_lbl[0] & 0xc0) >> 6))") + " )) break;"
238
239 def port_to_rule(ty, rules):
240     if ty == "port" :
241         ast = parse_ast(rules, parse_numbers_expr, True)
242         return "if (sport == -1 || dport == -1) break;\nif (!( " + ast.write("sport", "dport") + " )) break;"
243
244     ast = parse_ast(rules, parse_numbers_expr, True)
245     return "if (" + ty + " == -1) break;\nif (!( " + ast.write(ty) + " )) break;"
246
247 def tcp_flags_to_rule(rules):
248     ast = parse_ast(rules, parse_bit_expr, False)
249
250     return f"""if (tcp == NULL) break;
251 if (!( {ast.write("(ntohs(tcp->flags) & 0xfff)")} )) break;"""
252
253 def flow_label_to_rule(rules):
254     ast = parse_ast(rules, parse_bit_expr, False)
255
256     return f"""if (ip6 == NULL) break;
257 if (!( {ast.write("((((uint32_t)(ip6->flow_lbl[0] & 0xf)) << 2*8) | (((uint32_t)ip6->flow_lbl[1]) << 1*8) | (uint32_t)ip6->flow_lbl[0])")} )) break;"""
258
259 class RuleAction(Enum):
260     CONDITIONS = 1
261     ACTION = 2
262     LIST = 3
263 class RuleNode:
264     def __init__(self, ty, action, inner):
265         self.ty = ty
266         self.action = action
267         self.inner = inner
268         if ty == RuleAction.ACTION:
269             assert inner is None
270             assert type(action) == str
271         elif ty == RuleAction.LIST:
272             assert type(inner) == list
273             assert action is None
274             for item in inner:
275                 assert type(item) == RuleNode
276         else:
277             assert ty == RuleAction.CONDITIONS
278             assert type(action) == list
279             assert type(inner) == RuleNode
280
281     def maybe_join(self, neighbor):
282         if self.ty == RuleAction.CONDITIONS and neighbor.ty == RuleAction.CONDITIONS:
283             overlapping_conditions = [x for x in self.action if x in neighbor.action]
284             if len(overlapping_conditions) != 0:
285                 us = RuleNode(RuleAction.CONDITIONS, [x for x in self.action if x not in overlapping_conditions], self.inner)
286                 them = RuleNode(RuleAction.CONDITIONS, [x for x in neighbor.action if x not in overlapping_conditions], neighbor.inner)
287                 self.action = overlapping_conditions
288                 if self.inner.ty == RuleAction.LIST and us.action == []:
289                     self.inner.inner.append(them)
290                 else:
291                     self.inner = RuleNode(RuleAction.LIST, None, [us, them])
292                 self.inner.flatten()
293                 return True
294         return False
295
296     def flatten(self):
297         # LLVM can be pretty bad at optimizing out common subexpressions. Thus, we have to do a
298         # pass here to toptimize out common subexpressions in back-to-back rules.
299         # See https://bugs.llvm.org/show_bug.cgi?id=52455
300         assert self.ty == RuleAction.LIST
301         did_update = True
302         while did_update:
303             did_update = False
304             for i in range(0, len(self.inner) - 1):
305                 if self.inner[i].maybe_join(self.inner[i + 1]):
306                     del self.inner[i + 1]
307                     did_update = True
308                     break
309
310     def write(self, out, pfx="\t"):
311         if self.ty == RuleAction.CONDITIONS:
312             out.write(pfx + "do {\\\n")
313             for cond in self.action:
314                 out.write("\t" + pfx + cond.strip().replace("\n", " \\\n\t" + pfx) + " \\\n")
315             self.inner.write(out, pfx)
316             out.write(pfx + "} while(0);\\\n")
317         elif self.ty == RuleAction.LIST:
318             for item in self.inner:
319                 item.write(out, pfx + "\t")
320         else:
321             out.write("\t" + pfx + self.action.strip().replace("\n", " \\\n\t" + pfx) + " \\\n")
322
323 with open("rules.h", "w") as out:
324     parse = argparse.ArgumentParser()
325     parse.add_argument("--ihl", dest="ihl", required=True, choices=["drop-options","accept-options","parse-options"])
326     parse.add_argument("--v6frag", dest="v6frag", required=True, choices=["drop-frags","ignore","parse-frags","ignore-parse-if-rule"])
327     parse.add_argument("--8021q", dest="vlan", required=True, choices=["drop-vlan","accept-vlan","parse-vlan"])
328     parse.add_argument("--require-8021q", dest="vlan_tag")
329     args = parse.parse_args(sys.argv[1:])
330
331     if args.ihl == "drop-options":
332         out.write("#define PARSE_IHL XDP_DROP\n")
333     elif args.ihl == "accept-options":
334         out.write("#define PARSE_IHL XDP_PASS\n")
335     elif args.ihl == "parse-options":
336         out.write("#define PARSE_IHL PARSE\n")
337
338     if args.v6frag == "drop-frags":
339         out.write("#define PARSE_V6_FRAG XDP_DROP\n")
340     elif args.v6frag == "ignore":
341         pass
342     elif args.v6frag == "parse-frags":
343         out.write("#define PARSE_V6_FRAG PARSE\n")
344
345     if args.vlan == "drop-vlan":
346         out.write("#define PARSE_8021Q XDP_DROP\n")
347     elif args.vlan == "accept-vlan":
348         out.write("#define PARSE_8021Q XDP_PASS\n")
349     elif args.vlan == "parse-vlan":
350         out.write("#define PARSE_8021Q PARSE\n")
351
352     if args.vlan_tag is not None:
353         if args.vlan != "parse-vlan":
354             assert False
355         out.write("#define REQ_8021Q " + args.vlan_tag + "\n")
356
357     rules6 = []
358     rules4 = []
359     use_v6_frags = False
360     stats_rulecnt = 0
361     ratelimitcnt = 0
362     v4persrcratelimits = []
363     v5persrcratelimits = []
364     v6persrcratelimits = []
365
366     lastrule = None
367     for line in sys.stdin.readlines():
368         if "{" in line:
369             if lastrule is not None:
370                 print("Skipped rule due to lack of understood community tag: " + lastrule)
371             lastrule = line
372             continue
373         if "BGP.ext_community: " in line:
374             assert lastrule is not None
375
376             t = lastrule.split("{")
377             if t[0].strip() == "flow4":
378                 proto = 4
379             elif t[0].strip() == "flow6":
380                 proto = 6
381             else:
382                 continue
383
384             conditions = []
385             def write_rule(r):
386                 global conditions
387                 conditions.append(r + "\n")
388
389             rule = t[1].split("}")[0].strip()
390             for step in rule.split(";"):
391                 if step.strip().startswith("src") or step.strip().startswith("dst"):
392                     nets = step.strip()[3:].strip().split(" ")
393                     if len(nets) > 1:
394                         assert nets[1] == "offset"
395                         offset = nets[2]
396                     else:
397                         offset = None
398                     if step.strip().startswith("src"):
399                         write_rule(ip_to_rule(proto, nets[0], "saddr", offset))
400                     else:
401                         write_rule(ip_to_rule(proto, nets[0], "daddr", offset))
402                 elif step.strip().startswith("proto") and proto == 4:
403                     write_rule(proto_to_rule(4, step.strip()[6:]))
404                 elif step.strip().startswith("next header") and proto == 6:
405                     write_rule(proto_to_rule(6, step.strip()[12:]))
406                 elif step.strip().startswith("icmp type"):
407                     write_rule(icmp_type_to_rule(proto, step.strip()[10:]))
408                 elif step.strip().startswith("icmp code"):
409                     write_rule(icmp_code_to_rule(proto, step.strip()[10:]))
410                 elif step.strip().startswith("sport") or step.strip().startswith("dport") or step.strip().startswith("port"):
411                     write_rule(port_to_rule(step.strip().split(" ")[0], step.strip().split(" ", 1)[1]))
412                 elif step.strip().startswith("length"):
413                     write_rule(len_to_rule(step.strip()[7:]))
414                 elif step.strip().startswith("dscp"):
415                     write_rule(dscp_to_rule(proto, step.strip()[5:]))
416                 elif step.strip().startswith("tcp flags"):
417                     write_rule(tcp_flags_to_rule(step.strip()[10:]))
418                 elif step.strip().startswith("label"):
419                     write_rule(flow_label_to_rule(step.strip()[6:]))
420                 elif step.strip().startswith("fragment"):
421                     if proto == 6:
422                         use_v6_frags = True
423                     write_rule(fragment_to_rule(proto, step.strip()[9:]))
424                 elif step.strip() == "":
425                     pass
426                 else:
427                     assert False
428
429             actions = ""
430             def write_rule(r):
431                 global actions
432                 actions += r + "\n"
433
434             # Now write the match handling!
435             first_action = None
436             stats_action = ""
437             last_action = None
438             for community in line.split("("):
439                 if not community.startswith("generic, "):
440                     continue
441                 blocks = community.split(",")
442                 assert len(blocks) == 3
443                 if len(blocks[1].strip()) != 10: # Should be 0x12345678
444                     continue
445                 ty = blocks[1].strip()[:6]
446                 high_byte = int(blocks[1].strip()[6:8], 16)
447                 mid_byte = int(blocks[1].strip()[8:], 16)
448                 low_bytes = int(blocks[2].strip(") \n"), 16)
449                 if ty == "0x8006" or ty == "0x800c" or ty == "0x8306" or ty == "0x830c":
450                     if first_action is not None:
451                         # Two ratelimit actions, just drop the old one. RFC 8955 says we can.
452                         first_action = None
453                     exp = (low_bytes & (0xff << 23)) >> 23
454                     if low_bytes == 0:
455                         first_action = "{stats_replace}\nreturn XDP_DROP;"
456                     elif low_bytes & (1 <<  31) != 0:
457                         # Negative limit, just drop
458                         first_action = "{stats_replace}\nreturn XDP_DROP;"
459                     elif exp == 0xff:
460                         # NaN/INF. Just treat as INF and accept
461                         first_action = None
462                     elif exp < 127: # < 1
463                         first_action = "{stats_replace}\nreturn XDP_DROP;"
464                     elif exp >= 127 + 29: # We can't handle the precision required with ns this high
465                         first_action = None
466                     else:
467                         mantissa = low_bytes & ((1 << 23) - 1)
468                         value = 1.0 + mantissa / (2**23)
469                         value *= 2**(exp-127)
470
471                         first_action =   "int64_t time_masked = bpf_ktime_get_ns() & RATE_TIME_MASK;\n"
472                         first_action += f"int64_t per_pkt_ns = (1000000000LL << RATE_BUCKET_INTEGER_BITS) / {math.floor(value)};\n"
473                         if ty == "0x8006" or ty == "0x8306":
474                             first_action += "uint64_t amt = data_end - pktdata;\n"
475                         else:
476                             first_action += "uint64_t amt = 1;\n"
477                         if ty == "0x8006" or ty == "0x800c":
478                             first_action += f"const uint32_t ratelimitidx = {ratelimitcnt};\n"
479                             first_action += "struct ratelimit *rate = bpf_map_lookup_elem(&rate_map, &ratelimitidx);\n"
480                             ratelimitcnt += 1
481                             first_action +=  "int matched = 0;\n"
482                             first_action += "DO_RATE_LIMIT(bpf_spin_lock(&rate->lock), rate, time_masked, amt, per_pkt_ns, matched);\n"
483                             first_action += "if (rate) { bpf_spin_unlock(&rate->lock); }\n"
484                         else:
485                             if proto == 4:
486                                 if mid_byte > 32:
487                                     continue
488                                 first_action += f"const uint32_t srcip = ip->saddr & MASK4({mid_byte});\n"
489                                 first_action += f"void *rate_map = &v4_src_rate_{len(v4persrcratelimits)};\n"
490                                 first_action += f"int matched = check_v4_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
491                                 v4persrcratelimits.append((high_byte + 1) * 4096)
492                             elif mid_byte <= 64:
493                                 first_action += f"const uint64_t srcip = BE128BEHIGH64(ip6->saddr & MASK6({mid_byte}));\n"
494                                 first_action += f"void *rate_map = &v5_src_rate_{len(v5persrcratelimits)};\n"
495                                 first_action += f"int matched = check_v5_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
496                                 v5persrcratelimits.append((high_byte + 1) * 4096)
497                             else:
498                                 if mid_byte > 128:
499                                     continue
500                                 first_action += f"const uint128_t srcip = ip6->saddr & MASK6({mid_byte});\n"
501                                 first_action += f"void *rate_map = &v6_src_rate_{len(v6persrcratelimits)};\n"
502                                 first_action += f"int matched = check_v6_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
503                                 v6persrcratelimits.append((high_byte + 1) * 4096)
504                         first_action +=  "if (matched) {\n"
505                         first_action +=  "\t{stats_replace}\n"
506                         first_action +=  "\treturn XDP_DROP;\n"
507                         first_action +=  "}\n"
508                 elif ty == "0x8007":
509                     if low_bytes & 1 == 0:
510                         last_action = "return XDP_PASS;"
511                     if low_bytes & 2 == 2:
512                         stats_action = f"const uint32_t ruleidx = STATIC_RULE_CNT + {stats_rulecnt};\n"
513                         stats_action += "INCREMENT_MATCH(ruleidx);"
514                 elif ty == "0x8008":
515                     assert False # We do not implement the redirect action
516                 elif ty == "0x8009":
517                     if low_bytes & ~0b111111 != 0:
518                         assert False # Invalid DSCP value
519                     if proto == 4:
520                         write_rule("int32_t chk = ~BE16(ip->check) & 0xffff;")
521                         write_rule("uint8_t orig_tos = ip->tos;")
522                         write_rule("ip->tos = (ip->tos & 3) | " + str(low_bytes << 2) + ";")
523                         write_rule("chk = (chk - orig_tos + ip->tos);")
524                         write_rule("if (unlikely(chk > 0xffff)) { chk -= 65535; }")
525                         write_rule("else if (unlikely(chk < 0)) { chk += 65535; }")
526                         write_rule("ip->check = ~BE16(chk);")
527                     else:
528                         write_rule("ip6->priority = " + str(low_bytes >> 2) + ";")
529                         write_rule("ip6->flow_lbl[0] = (ip6->flow_lbl[0] & 0x3f) | " + str((low_bytes & 3) << 6) + ";")
530             if first_action is not None:
531                 write_rule(first_action.replace("{stats_replace}", stats_action))
532             if stats_action != "" and (first_action is None or "{stats_replace}" not in first_action):
533                 write_rule(stats_action)
534             if last_action is not None:
535                 write_rule(last_action)
536             if proto == 6:
537                 rules6.append(RuleNode(RuleAction.CONDITIONS, conditions, RuleNode(RuleAction.ACTION, actions, None)))
538             else:
539                 rules4.append(RuleNode(RuleAction.CONDITIONS, conditions, RuleNode(RuleAction.ACTION, actions, None)))
540             if stats_action != "":
541                 print(rule)
542                 stats_rulecnt += 1
543             lastrule = None
544
545     out.write("\n")
546     out.write(f"#define STATS_RULECNT {stats_rulecnt}\n")
547     if ratelimitcnt != 0:
548         out.write(f"#define RATE_CNT {ratelimitcnt}\n")
549
550     # Here we should probably sort the rules according to flowspec's sorting rules. We don't bother
551     # however, because its annoying.
552
553     if len(rules4) != 0:
554         out.write("#define NEED_V4_PARSE\n")
555         out.write("#define RULES4 {\\\n")
556         rules4 = RuleNode(RuleAction.LIST, None, rules4)
557         rules4.flatten()
558         rules4.write(out)
559         out.write("}\n")
560
561     if len(rules6) != 0:
562         out.write("#define NEED_V6_PARSE\n")
563         out.write("#define RULES6 {\\\n")
564         rules6 = RuleNode(RuleAction.LIST, None, rules6)
565         rules6.flatten()
566         rules6.write(out)
567         out.write("}\n")
568
569     if args.v6frag == "ignore-parse-if-rule":
570         if use_v6_frags:
571             out.write("#define PARSE_V6_FRAG PARSE\n")
572     with open("maps.h", "w") as out:
573         for idx, limit in enumerate(v4persrcratelimits):
574             out.write(f"SRC_RATE_DEFINE(4, {idx}, {limit})\n")
575         for idx, limit in enumerate(v5persrcratelimits):
576             out.write(f"SRC_RATE_DEFINE(5, {idx}, {limit})\n")
577         for idx, limit in enumerate(v6persrcratelimits):
578             out.write(f"SRC_RATE_DEFINE(6, {idx}, {limit})\n")