Skip to content

eBPF-based security platform

3.6 KB
Raw Blame
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2026 Authors of shirudo
"""Generate the destination watch tries (IPv4 and IPv6) as a C header."""

from __future__ import annotations

import argparse
import ipaddress
from pathlib import Path

# One node is 520 bytes of .rodata; keep the signed object reasonable.
MAX_NODES = 16384


def read_networks(path: Path):
	result = set()
	if not path.exists():
		return []
	for line_number, raw in enumerate(path.read_text().splitlines(), 1):
		text = raw.split("#", 1)[0].strip()
		if not text:
			continue
		try:
			network = ipaddress.ip_network(text, strict=False)
		except ValueError as error:
			raise ValueError(f"{path}:{line_number}: {error}") from error
		result.add(network)
	return sorted(result, key=lambda n: (n.version, int(n.network_address), n.prefixlen))


def build_trie(networks, version: int) -> list[dict[str, object]]:
	nodes: list[dict[str, object]] = [{"children": {}, "terminal": False}]
	octets = 4 if version == 4 else 16

	def new_node() -> int:
		if len(nodes) >= MAX_NODES:
			raise ValueError(f"watch trie exceeds {MAX_NODES} nodes")
		nodes.append({"children": {}, "terminal": False})
		return len(nodes) - 1

	for network in networks:
		if network.version != version:
			continue
		address = int(network.network_address)
		full_octets, partial_bits = divmod(network.prefixlen, 8)
		node_index = 0
		covered = False
		for depth in range(full_octets):
			if nodes[node_index]["terminal"]:
				covered = True
				break
			octet = (address >> (8 * (octets - 1 - depth))) & 0xff
			children = nodes[node_index]["children"]
			if octet not in children:
				children[octet] = new_node()
			node_index = children[octet]
		if covered:
			continue
		if partial_bits == 0:
			nodes[node_index]["terminal"] = True
			nodes[node_index]["children"] = {}
			continue
		if nodes[node_index]["terminal"]:
			continue
		depth = full_octets
		base = (address >> (8 * (octets - 1 - depth))) & 0xff
		span = 1 << (8 - partial_bits)
		children = nodes[node_index]["children"]
		first = base & ~(span - 1)
		for octet in range(first, first + span):
			if octet not in children:
				children[octet] = new_node()
			nodes[children[octet]]["terminal"] = True
			nodes[children[octet]]["children"] = {}
	return nodes


def emit_nodes(name: str, nodes: list[dict[str, object]]) -> str:
	lines = [f"#define OBS_WATCH_{name}_NODES {len(nodes)}u",
		 f"#define OBS_WATCH_{name}_INIT {{ \\"]
	for node in nodes:
		children = node["children"]
		assert isinstance(children, dict)
		parts = [f"[{octet}] = {index + 1}"
			 for octet, index in sorted(children.items())]
		child_init = "{" + ", ".join(parts) + "}" if parts else "{0}"
		terminal = 1 if node["terminal"] else 0
		lines.append(f"\t{{ .child = {child_init}, .terminal = {terminal} }}, \\")
	lines.append("}")
	return "\n".join(lines)


def main() -> int:
	parser = argparse.ArgumentParser(description=__doc__)
	parser.add_argument("list", type=Path)
	parser.add_argument("output", type=Path)
	args = parser.parse_args()

	networks = read_networks(args.list)
	body = "\n".join([
		"/* SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause */",
		"/* Generated by gen_watch.py; do not edit manually. */",
		f"/* Source: {args.list.name}; rules: {len(networks)}. */",
		"#ifndef OBS_WATCH_GENERATED_H",
		"#define OBS_WATCH_GENERATED_H",
		f"#define OBS_WATCH_RULES {len(networks)}u",
		emit_nodes("V4", build_trie(networks, 4)),
		emit_nodes("V6", build_trie(networks, 6)),
		"#endif /* OBS_WATCH_GENERATED_H */",
		"",
	])
	args.output.write_text(body)
	return 0


if __name__ == "__main__":
	raise SystemExit(main())