| 1 | #!/usr/bin/env python3 |
| 2 | import json |
| 3 | from pathlib import Path |
| 4 | import signal |
| 5 | import subprocess |
| 6 | import sys |
| 7 | import time |
| 8 | |
| 9 | |
| 10 | if len(sys.argv) == 1: |
| 11 | data = json.load(sys.stdin) |
| 12 | if data["preview"]: |
| 13 | unit = data["serviceId"] + "-network" |
| 14 | subprocess.run(["systemctl", "stop", unit], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 15 | subprocess.run([ |
| 16 | "systemd-run", "--collect", "--unit=" + unit, |
| 17 | "--setenv=PATH=/run/current-system/sw/bin:/usr/bin:/bin", |
| 18 | sys.executable, str(Path(__file__).resolve()), data["serviceId"], |
| 19 | ], check=True) |
| 20 | time.sleep(1) |
| 21 | subprocess.run(["systemctl", "is-active", "--quiet", unit], check=True) |
| 22 | sys.exit() |
| 23 | |
| 24 | stage = sys.argv[1] |
| 25 | metadata = Path("/var/lib/snowglobe/stages") / (stage + ".json") |
| 26 | network = json.loads(Path(__file__).with_name("network.json").read_text()) |
| 27 | rules = [ |
| 28 | ["-p", "tcp", "-m", "multiport", "--dports", ",".join(str(network[key]) for key in ( |
| 29 | "c2s", "c2s_tls", "s2s", "turn", "turn_tls", |
| 30 | ))], |
| 31 | ["-p", "udp", "-m", "multiport", "--dports", f'{network["turn"]},{network["turn_tls"]}'], |
| 32 | ["-p", "udp", "--dport", f'{network["relay_first"]}:{network["relay_last"]}'], |
| 33 | ] |
| 34 | rules = [rule + ["-m", "comment", "--comment", stage, "-j", "nixos-fw-accept"] for rule in rules] |
| 35 | |
| 36 | |
| 37 | def stop(signum, frame): |
| 38 | raise SystemExit() |
| 39 | |
| 40 | |
| 41 | signal.signal(signal.SIGTERM, stop) |
| 42 | signal.signal(signal.SIGINT, stop) |
| 43 | try: |
| 44 | while metadata.exists(): |
| 45 | for command in ("iptables", "ip6tables"): |
| 46 | for rule in rules: |
| 47 | if subprocess.run([command, "-w", "-C", "nixos-fw", *rule], capture_output=True).returncode: |
| 48 | subprocess.run([command, "-w", "-I", "nixos-fw", "1", *rule], check=True) |
| 49 | time.sleep(10) |
| 50 | finally: |
| 51 | for command in ("iptables", "ip6tables"): |
| 52 | for rule in rules: |
| 53 | subprocess.run([command, "-w", "-D", "nixos-fw", *rule], capture_output=True) |