Drop ports_valid flag, it just wastes a register
[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
260 with open("rules.h", "w") as out:
261     parse = argparse.ArgumentParser()
262     parse.add_argument("--ihl", dest="ihl", required=True, choices=["drop-options","accept-options","parse-options"])
263     parse.add_argument("--v6frag", dest="v6frag", required=True, choices=["drop-frags","ignore","parse-frags","ignore-parse-if-rule"])
264     parse.add_argument("--8021q", dest="vlan", required=True, choices=["drop-vlan","accept-vlan","parse-vlan"])
265     parse.add_argument("--require-8021q", dest="vlan_tag")
266     args = parse.parse_args(sys.argv[1:])
267
268     if args.ihl == "drop-options":
269         out.write("#define PARSE_IHL XDP_DROP\n")
270     elif args.ihl == "accept-options":
271         out.write("#define PARSE_IHL XDP_PASS\n")
272     elif args.ihl == "parse-options":
273         out.write("#define PARSE_IHL PARSE\n")
274
275     if args.v6frag == "drop-frags":
276         out.write("#define PARSE_V6_FRAG XDP_DROP\n")
277     elif args.v6frag == "ignore":
278         pass
279     elif args.v6frag == "parse-frags":
280         out.write("#define PARSE_V6_FRAG PARSE\n")
281
282     if args.vlan == "drop-vlan":
283         out.write("#define PARSE_8021Q XDP_DROP\n")
284     elif args.vlan == "accept-vlan":
285         out.write("#define PARSE_8021Q XDP_PASS\n")
286     elif args.vlan == "parse-vlan":
287         out.write("#define PARSE_8021Q PARSE\n")
288
289     if args.vlan_tag is not None:
290         if args.vlan != "parse-vlan":
291             assert False
292         out.write("#define REQ_8021Q " + args.vlan_tag + "\n")
293
294     rules6 = ""
295     rules4 = ""
296     use_v6_frags = False
297     rulecnt = 0
298     ratelimitcnt = 0
299     v4persrcratelimits = []
300     v6persrcratelimits = []
301
302     lastrule = None
303     for line in sys.stdin.readlines():
304         if "{" in line:
305             if lastrule is not None:
306                 print("Skipped rule due to lack of understood community tag: " + lastrule)
307             lastrule = line
308             continue
309         if "BGP.ext_community: " in line:
310             assert lastrule is not None
311
312             t = lastrule.split("{")
313             if t[0].strip() == "flow4":
314                 proto = 4
315                 rules4 += "\tdo {\\\n"
316             elif t[0].strip() == "flow6":
317                 proto = 6
318                 rules6 += "\tdo {\\\n"
319             else:
320                 continue
321
322             def write_rule(r):
323                 global rules4, rules6
324                 if proto == 6:
325                     rules6 += "\t\t" + r.replace("\n", " \\\n\t\t") + " \\\n"
326                 else:
327                     rules4 += "\t\t" + r.replace("\n", " \\\n\t\t") + " \\\n"
328
329             rule = t[1].split("}")[0].strip()
330             for step in rule.split(";"):
331                 if step.strip().startswith("src") or step.strip().startswith("dst"):
332                     nets = step.strip()[3:].strip().split(" ")
333                     if len(nets) > 1:
334                         assert nets[1] == "offset"
335                         offset = nets[2]
336                     else:
337                         offset = None
338                     if step.strip().startswith("src"):
339                         write_rule(ip_to_rule(proto, nets[0], "saddr", offset))
340                     else:
341                         write_rule(ip_to_rule(proto, nets[0], "daddr", offset))
342                 elif step.strip().startswith("proto") and proto == 4:
343                     write_rule(proto_to_rule(4, step.strip()[6:]))
344                 elif step.strip().startswith("next header") and proto == 6:
345                     write_rule(proto_to_rule(6, step.strip()[12:]))
346                 elif step.strip().startswith("icmp type"):
347                     write_rule(icmp_type_to_rule(proto, step.strip()[10:]))
348                 elif step.strip().startswith("icmp code"):
349                     write_rule(icmp_code_to_rule(proto, step.strip()[10:]))
350                 elif step.strip().startswith("sport") or step.strip().startswith("dport") or step.strip().startswith("port"):
351                     write_rule(port_to_rule(step.strip().split(" ")[0], step.strip().split(" ", 1)[1]))
352                 elif step.strip().startswith("length"):
353                     write_rule(len_to_rule(step.strip()[7:]))
354                 elif step.strip().startswith("dscp"):
355                     write_rule(dscp_to_rule(proto, step.strip()[5:]))
356                 elif step.strip().startswith("tcp flags"):
357                     write_rule(tcp_flags_to_rule(step.strip()[10:]))
358                 elif step.strip().startswith("label"):
359                     write_rule(flow_label_to_rule(step.strip()[6:]))
360                 elif step.strip().startswith("fragment"):
361                     if proto == 6:
362                         use_v6_frags = True
363                     write_rule(fragment_to_rule(proto, step.strip()[9:]))
364                 elif step.strip() == "":
365                     pass
366                 else:
367                     assert False
368
369             # Now write the match handling!
370             first_action = None
371             stats_action = None
372             last_action = None
373             for community in line.split("("):
374                 if not community.startswith("generic, "):
375                     continue
376                 blocks = community.split(",")
377                 assert len(blocks) == 3
378                 if len(blocks[1].strip()) != 10: # Should be 0x12345678
379                     continue
380                 ty = blocks[1].strip()[:6]
381                 high_byte = int(blocks[1].strip()[6:8], 16)
382                 mid_byte = int(blocks[1].strip()[8:], 16)
383                 low_bytes = int(blocks[2].strip(") \n"), 16)
384                 if ty == "0x8006" or ty == "0x800c" or ty == "0x8306" or ty == "0x830c":
385                     if first_action is not None:
386                         # Two ratelimit actions, just drop the old one. RFC 8955 says we can.
387                         first_action = None
388                     exp = (low_bytes & (0xff << 23)) >> 23
389                     if low_bytes == 0:
390                         first_action = "{stats_replace}\nreturn XDP_DROP;"
391                     elif low_bytes & (1 <<  31) != 0:
392                         # Negative limit, just drop
393                         first_action = "{stats_replace}\nreturn XDP_DROP;"
394                     elif exp == 0xff:
395                         # NaN/INF. Just treat as INF and accept
396                         first_action = None
397                     elif exp <= 127: # < 1
398                         first_action = "{stats_replace}\nreturn XDP_DROP;"
399                     elif exp >= 127 + 63: # The count won't even fit in 64-bits, just accept
400                         first_action = None
401                     else:
402                         mantissa = low_bytes & ((1 << 23) - 1)
403                         value = 1.0 + mantissa / (2**23)
404                         value *= 2**(exp-127)
405                         if ty == "0x8006" or ty == "0x8306":
406                             accessor = "rate->rate.sent_bytes"
407                         else:
408                             accessor = "rate->rate.sent_packets"
409                         # Note that int64_t will overflow after 292 years of uptime
410                         first_action = "int64_t time = bpf_ktime_get_ns();\n"
411                         first_action +=  "uint64_t allowed_since_last = 0;\n"
412                         if ty == "0x8006" or ty == "0x800c":
413                             spin_lock = "bpf_spin_lock(&rate->lock);"
414                             spin_unlock = "bpf_spin_unlock(&rate->lock);"
415                             first_action += f"const uint32_t ratelimitidx = {ratelimitcnt};\n"
416                             first_action += "struct ratelimit *rate = bpf_map_lookup_elem(&rate_map, &ratelimitidx);\n"
417                             ratelimitcnt += 1
418                         else:
419                             spin_lock = "/* No locking as we're per-CPU */"
420                             spin_unlock = "/* No locking as we're per-CPU */"
421                             if proto == 4:
422                                 if mid_byte > 32:
423                                     continue
424                                 first_action += f"const uint32_t srcip = ip->saddr & MASK4({mid_byte});\n"
425                                 first_action += f"void *rate_map = &v4_src_rate_{len(v4persrcratelimits)};\n"
426                                 v4persrcratelimits.append((high_byte + 1) * 1024)
427                             else:
428                                 if mid_byte > 128:
429                                     continue
430                                 first_action += f"const uint128_t srcip = ip6->saddr & MASK6({mid_byte});\n"
431                                 first_action += f"void *rate_map = &v6_src_rate_{len(v6persrcratelimits)};\n"
432                                 v6persrcratelimits.append((high_byte + 1) * 1024)
433                             first_action += f"struct percpu_ratelimit *rate = bpf_map_lookup_elem(rate_map, &srcip);\n"
434                         first_action +=  "if (rate) {\n"
435                         first_action += f"\t{spin_lock}\n"
436                         first_action += f"\tif (likely({accessor} > 0))" + " {\n"
437                         first_action +=  "\t\tint64_t diff = time - rate->sent_time;\n"
438                         # Unlikely or not, if the flow is slow, take a perf hit (though with the else if branch it doesn't matter)
439                         first_action +=  "\t\tif (unlikely(diff > 1000000000))\n"
440                         first_action += f"\t\t\t{accessor} = 0;\n"
441                         first_action +=  "\t\telse if (likely(diff > 0))\n"
442                         first_action += f"\t\t\tallowed_since_last = ((uint64_t)diff) * {math.floor(value)} / 1000000000;\n"
443                         first_action +=  "\t}\n"
444                         first_action += f"\tif ({accessor} - ((int64_t)allowed_since_last) <= 0)" + " {\n"
445                         if ty == "0x8006" or ty == "0x8306":
446                             first_action += f"\t\t{accessor} = data_end - pktdata;\n"
447                         else:
448                             first_action += f"\t\t{accessor} = 1;\n"
449                         first_action +=  "\t\trate->sent_time = time;\n"
450                         first_action += f"\t\t{spin_unlock}\n"
451                         first_action +=  "\t} else {\n"
452                         first_action += f"\t\t{spin_unlock}\n"
453                         first_action +=  "\t\t{stats_replace}\n"
454                         first_action +=  "\t\treturn XDP_DROP;\n"
455                         first_action +=  "\t}\n"
456                         if ty == "0x8306" or ty == "0x830c":
457                             first_action +=  "} else {\n"
458                             first_action +=  "\tstruct percpu_ratelimit new_rate = { .sent_time = time, };\n"
459                             first_action +=  "\trate = &new_rate;\n"
460                             if ty == "0x8006" or ty == "0x8306":
461                                 first_action += f"\t\t{accessor} = data_end - pktdata;\n"
462                             else:
463                                 first_action += f"\t\t{accessor} = 1;\n"
464                             first_action +=  "\tbpf_map_update_elem(rate_map, &srcip, rate, BPF_ANY);\n"
465                         first_action +=  "}\n"
466                 elif ty == "0x8007":
467                     if low_bytes & 1 == 0:
468                         last_action = "return XDP_PASS;"
469                     if low_bytes & 2 == 2:
470                         stats_action = f"const uint32_t ruleidx = STATIC_RULE_CNT + {rulecnt};\n"
471                         stats_action += "INCREMENT_MATCH(ruleidx);"
472                 elif ty == "0x8008":
473                     assert False # We do not implement the redirect action
474                 elif ty == "0x8009":
475                     if low_bytes & ~0b111111 != 0:
476                         assert False # Invalid DSCP value
477                     if proto == 4:
478                         write_rule("int32_t chk = ~BE16(ip->check) & 0xffff;")
479                         write_rule("uint8_t orig_tos = ip->tos;")
480                         write_rule("ip->tos = (ip->tos & 3) | " + str(low_bytes << 2) + ";")
481                         write_rule("chk = (chk - orig_tos + ip->tos);")
482                         write_rule("if (unlikely(chk > 0xffff)) { chk -= 65535; }")
483                         write_rule("else if (unlikely(chk < 0)) { chk += 65535; }")
484                         write_rule("ip->check = ~BE16(chk);")
485                     else:
486                         write_rule("ip6->priority = " + str(low_bytes >> 2) + ";")
487                         write_rule("ip6->flow_lbl[0] = (ip6->flow_lbl[0] & 0x3f) | " + str((low_bytes & 3) << 6) + ";")
488             if first_action is not None:
489                 write_rule(first_action.replace("{stats_replace}", stats_action))
490             if stats_action is not None and (first_action is None or "{stats_replace}" not in first_action):
491                 write_rule(stats_action)
492             if last_action is not None:
493                 write_rule(last_action)
494             if proto == 6:
495                 rules6 += "\t} while(0);\\\n"
496             else:
497                 rules4 += "\t} while(0);\\\n"
498             rulecnt += 1
499             lastrule = None
500
501     out.write("\n")
502     out.write(f"#define RULECNT {rulecnt}\n")
503     if ratelimitcnt != 0:
504         out.write(f"#define RATE_CNT {ratelimitcnt}\n")
505     if rules4 != "":
506         out.write("#define NEED_V4_PARSE\n")
507         out.write("#define RULES4 {\\\n" + rules4 + "}\n")
508     if rules6:
509         out.write("#define NEED_V6_PARSE\n")
510         out.write("#define RULES6 {\\\n" + rules6 + "}\n")
511     if args.v6frag == "ignore-parse-if-rule":
512         if use_v6_frags:
513             out.write("#define PARSE_V6_FRAG PARSE\n")
514     with open("maps.h", "w") as out:
515         for idx, limit in enumerate(v4persrcratelimits):
516             out.write(f"V4_SRC_RATE_DEFINE({idx}, {limit})\n")
517         for idx, limit in enumerate(v6persrcratelimits):
518             out.write(f"V6_SRC_RATE_DEFINE({idx}, {limit})\n")