1#!/usr/bin/env python3
2import json
3from pathlib import Path
4import signal
5import subprocess
6import sys
7import time
8
9
10if 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
24stage = sys.argv[1]
25metadata = Path("/var/lib/snowglobe/stages") / (stage + ".json")
26network = json.loads(Path(__file__).with_name("network.json").read_text())
27rules = [
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]
34rules = [rule + ["-m", "comment", "--comment", stage, "-j", "nixos-fw-accept"] for rule in rules]
35
36
37def stop(signum, frame):
38 raise SystemExit()
39
40
41signal.signal(signal.SIGTERM, stop)
42signal.signal(signal.SIGINT, stop)
43try:
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)
50finally:
51 for command in ("iptables", "ip6tables"):
52 for rule in rules:
53 subprocess.run([command, "-w", "-D", "nixos-fw", *rule], capture_output=True)