46901f2b62
AmneziaWG 3 tunnels idle for a while need 5+ s for the first handshake, so the 4-5 s checks marked working connections as dead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
531 lines
21 KiB
Python
531 lines
21 KiB
Python
#!/usr/bin/python3
|
|
"""BroV network core — narrow root helper (LaunchDaemon local.maksar.brov.netctl).
|
|
|
|
The core (mihomo) runs as root with its config, keys and API secret in
|
|
/Library/Application Support/BroV/netcore (root, 0700). BroV never sees those: it talks
|
|
to this helper over a Unix socket that only the installing user may open, and the helper
|
|
allows exactly these operations:
|
|
|
|
state groups, provider nodes with delays, hidden connections, TUN on/off
|
|
select {group, name} ai-out / amnezia / saga-sw / planet9-sw / home-sw, name must be a member
|
|
delay {group}|{proxy} speed test of exit / ai-out / amnezia, or of a client tunnel
|
|
tun {on} traffic capture on (fresh core start) / off; remembered
|
|
add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated
|
|
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
|
|
rebind {} the Mac moved to another network: clean core restart (WireGuard
|
|
tunnels bind to the new address, nothing leaks)
|
|
hide {name} take an Amnezia connection or a VLESS node out of the list and
|
|
out of "auto" (the key / subscription stay, nothing is deleted)
|
|
unhide {name} put it back
|
|
|
|
One JSON object per line in, one per line out. Nothing here can rewrite the core config
|
|
or point traffic elsewhere.
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
ROOT = "/Library/Application Support/BroV"
|
|
CORE = os.path.join(ROOT, "netcore")
|
|
KEYS = os.path.join(CORE, "keys")
|
|
SOCK = "/var/run/brov-netctl.sock"
|
|
API = "http://127.0.0.1:9097"
|
|
TEST_URL = "https://www.gstatic.com/generate_204"
|
|
|
|
SELECT_GROUPS = {"ai-out", "amnezia", "saga-sw", "planet9-sw", "home-sw"}
|
|
DELAY_GROUPS = {"exit", "ai-out", "auto", "amnezia"}
|
|
CLIENT_TUNNELS = {"saga", "planet9", "home"}
|
|
MAX_REQUEST = 64 * 1024
|
|
|
|
CORE_LABEL = "local.maksar.brov.netd"
|
|
HIDDEN = os.path.join(CORE, "hidden.json")
|
|
CONFIG = os.path.join(CORE, "config.yaml")
|
|
MIHOMO = os.path.join(ROOT, "mihomo")
|
|
|
|
ALLOWED_UID = int(sys.argv[1]) if len(sys.argv) > 1 else -1
|
|
gen_lock = threading.Lock()
|
|
|
|
|
|
def secret():
|
|
with open(os.path.join(CORE, "api.secret")) as f:
|
|
return f.read().strip()
|
|
|
|
|
|
def api(method, path, body=None, timeout=8):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(API + path, method=method, data=data, headers={
|
|
"Authorization": "Bearer " + secret(), "Content-Type": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
raw = r.read()
|
|
return json.loads(raw) if raw else {}
|
|
|
|
|
|
def q(name):
|
|
return urllib.parse.quote(name, safe="")
|
|
|
|
|
|
def gen(*args):
|
|
return subprocess.run(["/usr/bin/python3", os.path.join(CORE, "gen.py"), *args], cwd=CORE,
|
|
capture_output=True, text=True, timeout=60).stdout
|
|
|
|
|
|
# MARK: - Commands
|
|
|
|
def cmd_state(_):
|
|
proxies = api("GET", "/proxies").get("proxies", {})
|
|
keep = {}
|
|
for name, p in proxies.items():
|
|
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
|
|
providers = {}
|
|
for prov in ("vless-cluster", "vless-keys", "amnezia-keys", "clients"):
|
|
try:
|
|
lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
|
|
except Exception:
|
|
lst = []
|
|
providers[prov] = [{"name": x.get("name"), "history": (x.get("history") or [])[-1:]} for x in lst]
|
|
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
|
|
return {"ok": True, "proxies": keep, "providers": providers, "tun": tun, "hidden": load_hidden()}
|
|
|
|
|
|
def cmd_select(r):
|
|
group, name = r.get("group"), r.get("name")
|
|
if group not in SELECT_GROUPS or not isinstance(name, str):
|
|
return {"ok": False, "error": "группа не разрешена"}
|
|
members = api("GET", "/proxies/" + q(group)).get("all", [])
|
|
if name not in members:
|
|
return {"ok": False, "error": "такого варианта нет в группе"}
|
|
api("PUT", "/proxies/" + q(group), {"name": name})
|
|
return {"ok": True}
|
|
|
|
|
|
def cmd_delay(r):
|
|
test = "url=" + q(TEST_URL) + "&timeout=8000" # AmneziaWG 3 handshakes after idle can take 5+ s
|
|
if r.get("group") in DELAY_GROUPS:
|
|
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=15)}
|
|
if r.get("proxy") in CLIENT_TUNNELS:
|
|
try:
|
|
d = api("GET", "/providers/proxies/clients/%s/healthcheck?%s" % (q(r["proxy"]), test),
|
|
timeout=15).get("delay", 0)
|
|
except Exception:
|
|
d = 0
|
|
return {"ok": True, "delays": {r["proxy"]: d}}
|
|
return {"ok": False, "error": "замер не разрешён"}
|
|
|
|
|
|
# MARK: - System DNS
|
|
#
|
|
# With capture on, the Mac's DNS must go into the core (198.18.0.2 sits inside the TUN and
|
|
# is hijacked). A DNS server in the local network — e.g. the home router — is reached
|
|
# around the TUN, and when it doesn't answer nothing resolves. The previous servers are
|
|
# saved and put back when capture goes off.
|
|
|
|
CORE_DNS = "198.18.0.2"
|
|
DNS_BACKUP = os.path.join(CORE, "dns-backup.json")
|
|
|
|
|
|
def network_services():
|
|
out = subprocess.run(["/usr/sbin/networksetup", "-listallnetworkservices"],
|
|
capture_output=True, text=True, timeout=10).stdout.splitlines()
|
|
return [l for l in out[1:] if l and not l.startswith("*")]
|
|
|
|
|
|
def active_services():
|
|
"""Hardware services that carry traffic right now: Wi-Fi or a wired adapter (en*) with
|
|
status active. Touching the others — «iPhone USB», Thunderbolt Bridge, VPN services —
|
|
made macOS re-check them and offer the iPhone's hotspot over and over."""
|
|
order = subprocess.run(["/usr/sbin/networksetup", "-listnetworkserviceorder"],
|
|
capture_output=True, text=True, timeout=10).stdout
|
|
out = []
|
|
for name, port, dev in re.findall(r"\(\d+\) (.+)\n\(Hardware Port: ([^,]*), Device: ([^)]*)\)", order):
|
|
if not re.fullmatch(r"en\d+", dev) or "iphone" in (name + port).lower():
|
|
continue
|
|
status = subprocess.run(["/sbin/ifconfig", dev], capture_output=True, text=True, timeout=5).stdout
|
|
if "status: active" in status:
|
|
out.append(name.strip())
|
|
return out
|
|
|
|
|
|
def dns_of(service):
|
|
out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service],
|
|
capture_output=True, text=True, timeout=10).stdout.splitlines()
|
|
ip = r"\d{1,3}(\.\d{1,3}){3}|[0-9a-fA-F]*:[0-9a-fA-F:]+"
|
|
return [x.strip() for x in out if re.fullmatch(ip, x.strip())]
|
|
|
|
|
|
def set_dns(service, servers):
|
|
subprocess.run(["/usr/sbin/networksetup", "-setdnsservers", service] + (servers or ["Empty"]),
|
|
capture_output=True, timeout=10)
|
|
|
|
|
|
def dns_to_core():
|
|
try:
|
|
with open(DNS_BACKUP) as f:
|
|
backup = json.load(f)
|
|
except (OSError, ValueError):
|
|
backup = {}
|
|
active = set(active_services())
|
|
for svc in network_services():
|
|
cur = dns_of(svc)
|
|
if svc in active:
|
|
if cur != [CORE_DNS]:
|
|
backup[svc] = cur
|
|
set_dns(svc, [CORE_DNS])
|
|
elif cur == [CORE_DNS]: # set by an older version: give it back
|
|
set_dns(svc, [x for x in backup.pop(svc, []) if x != CORE_DNS])
|
|
fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump(backup, f)
|
|
|
|
|
|
def dns_restore():
|
|
try:
|
|
with open(DNS_BACKUP) as f:
|
|
backup = json.load(f)
|
|
except (OSError, ValueError):
|
|
backup = {}
|
|
for svc in network_services():
|
|
if dns_of(svc) == [CORE_DNS]:
|
|
set_dns(svc, [x for x in backup.get(svc, []) if x != CORE_DNS])
|
|
try:
|
|
os.remove(DNS_BACKUP)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def save_tun(on):
|
|
tmp = os.path.join(CORE, "tun.json.tmp")
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump({"on": on}, f)
|
|
os.rename(tmp, os.path.join(CORE, "tun.json"))
|
|
|
|
|
|
def cmd_tun(r):
|
|
"""On = a fresh core start. A core that has been running while the AmneziaVPN app held
|
|
the routes keeps treating Amnezia's utun as the way out; its own TUN often gets the same
|
|
utun name and then sends everything into itself (no routes, no DNS). A restart forgets
|
|
that. The state is saved so the core comes back the same way after a reboot."""
|
|
on = r.get("on")
|
|
if not isinstance(on, bool):
|
|
return {"ok": False, "error": "нужно on: true/false"}
|
|
if on and subprocess.run(["/usr/bin/pgrep", "-x", "AmneziaVPN"], capture_output=True).returncode == 0:
|
|
return {"ok": False, "error": "открыто приложение AmneziaVPN — закрой его (⌘Q), потом включай"}
|
|
with gen_lock:
|
|
save_tun(on)
|
|
gen()
|
|
if not on:
|
|
dns_restore()
|
|
api("PATCH", "/configs", {"tun": {"enable": False}})
|
|
return {"ok": True}
|
|
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
|
for _ in range(40):
|
|
time.sleep(0.25)
|
|
try:
|
|
if api("GET", "/configs", timeout=2).get("tun", {}).get("enable"):
|
|
dns_to_core()
|
|
return {"ok": True}
|
|
except Exception:
|
|
pass
|
|
return {"ok": False, "error": "ядро не поднялось после перезапуска"}
|
|
|
|
|
|
def provider_reload_and_test(proxy):
|
|
api("PUT", "/providers/proxies/amnezia-keys")
|
|
try:
|
|
hc = api("GET", "/providers/proxies/amnezia-keys/%s/healthcheck?url=%s&timeout=6000"
|
|
% (q(proxy), q(TEST_URL)), timeout=10)
|
|
return hc.get("delay", 0)
|
|
except Exception:
|
|
return 0
|
|
|
|
|
|
VLESS_FILE = os.path.join(KEYS, "vless.txt")
|
|
|
|
|
|
def provider_names(name):
|
|
try:
|
|
return [x.get("name") for x in api("GET", "/providers/proxies/" + name).get("proxies", [])]
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def add_vless(text):
|
|
"""A single vless:// link → keys/vless.txt (provider vless-keys). The first one creates
|
|
the provider: a full core reload (connections drop for a second); later ones only
|
|
reload the provider."""
|
|
u = urllib.parse.urlsplit(text)
|
|
q = urllib.parse.parse_qs(u.query)
|
|
try:
|
|
port = u.port
|
|
except ValueError:
|
|
port = None
|
|
if (u.scheme != "vless" or not re.fullmatch(r"[0-9a-fA-F-]{36}", u.username or "") or not u.hostname
|
|
or not port or any(c in text for c in "\n\r '\"")):
|
|
return {"ok": False, "error": "не похоже на ссылку vless://uuid@сервер:порт?…"}
|
|
if q.get("security", [""])[0] == "reality" and not q.get("pbk"):
|
|
return {"ok": False, "error": "у Reality-ссылки нет ключа pbk"}
|
|
with gen_lock:
|
|
lines = [l.strip() for l in open(VLESS_FILE)] if os.path.exists(VLESS_FILE) else []
|
|
lines = [l for l in lines if l.startswith("vless://")]
|
|
if any(urllib.parse.urlsplit(l)._replace(fragment="") == u._replace(fragment="") for l in lines):
|
|
return {"ok": False, "error": "этот ключ уже добавлен"}
|
|
taken = set(provider_names("vless-cluster")) | {urllib.parse.unquote(urllib.parse.urlsplit(l).fragment) for l in lines}
|
|
base = urllib.parse.unquote(u.fragment).strip() or u.hostname
|
|
name, n = base, 2
|
|
while name in taken:
|
|
name, n = f"{base} {n}", n + 1
|
|
line = urllib.parse.urlunsplit(u._replace(fragment=urllib.parse.quote(name)))
|
|
first = not lines
|
|
tmp = VLESS_FILE + ".tmp"
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
f.write("\n".join(lines + [line]) + "\n")
|
|
os.rename(tmp, VLESS_FILE)
|
|
gen()
|
|
if first:
|
|
reload_core()
|
|
else:
|
|
api("PUT", "/providers/proxies/vless-keys")
|
|
delay = 0
|
|
try:
|
|
delay = api("GET", "/providers/proxies/vless-keys/%s/healthcheck?url=%s&timeout=6000"
|
|
% (q_(name), q_(TEST_URL)), timeout=10).get("delay", 0)
|
|
except Exception:
|
|
pass
|
|
return {"ok": True, "name": name, "server": "%s:%s" % (u.hostname, port), "proxy": name, "delay": delay}
|
|
|
|
|
|
def q_(s):
|
|
return urllib.parse.quote(s, safe="")
|
|
|
|
|
|
def cmd_add_key(r):
|
|
text = r.get("text")
|
|
if isinstance(text, str) and text.strip().startswith("vless://") and len(text) < 4000:
|
|
return add_vless(text.strip())
|
|
if not isinstance(text, str) or not text.strip().startswith("vpn://") or len(text) > 20000:
|
|
return {"ok": False, "error": "ключ должен начинаться с vpn:// (Амнезия) или vless://"}
|
|
with gen_lock:
|
|
pending = os.path.join(KEYS, ".pending.vpnkey")
|
|
fd = os.open(pending, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
f.write(text.strip())
|
|
try:
|
|
check = json.loads(gen("--check", pending).strip().splitlines()[-1])
|
|
except Exception:
|
|
check = {"ok": False, "error": "не удалось разобрать ключ"}
|
|
if not check.get("ok"):
|
|
os.remove(pending)
|
|
return {"ok": False, "error": check.get("error", "ключ не подходит")}
|
|
slug = re.sub(r"[^a-z0-9]+", "-", str(check.get("name", "amnezia")).lower()).strip("-") or "amnezia"
|
|
dest, n = os.path.join(KEYS, slug + ".vpnkey"), 2
|
|
while os.path.exists(dest):
|
|
dest, n = os.path.join(KEYS, "%s-%d.vpnkey" % (slug, n)), n + 1
|
|
os.rename(pending, dest)
|
|
gen()
|
|
proxy = "AWG " + os.path.basename(dest)[:-len(".vpnkey")]
|
|
return {"ok": True, "name": check.get("name"), "server": "%s:%s" % (check.get("server"), check.get("port")),
|
|
"proxy": proxy, "delay": provider_reload_and_test(proxy)}
|
|
|
|
|
|
def load_hidden():
|
|
try:
|
|
with open(HIDDEN) as f:
|
|
h = json.load(f)
|
|
return {"amnezia": list(h.get("amnezia", [])), "vless": list(h.get("vless", []))}
|
|
except (OSError, ValueError, AttributeError):
|
|
return {"amnezia": [], "vless": []}
|
|
|
|
|
|
def save_hidden(h):
|
|
tmp = HIDDEN + ".tmp"
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump(h, f, ensure_ascii=False)
|
|
os.rename(tmp, HIDDEN)
|
|
|
|
|
|
def awg_key_exists(name):
|
|
m = re.fullmatch(r"AWG ([a-z0-9-]+)", name)
|
|
path = os.path.join(KEYS, m.group(1) + ".vpnkey") if m else ""
|
|
return bool(m) and os.path.isfile(path) and not os.path.islink(path)
|
|
|
|
|
|
def reload_core():
|
|
"""Full config reload (needed for the VLESS filter): drops open connections for a moment.
|
|
The new config is checked first; TUN comes from tun.json, i.e. as the user left it."""
|
|
check = subprocess.run([MIHOMO, "-t", "-d", CORE, "-f", CONFIG], capture_output=True, text=True, timeout=30)
|
|
if check.returncode != 0:
|
|
raise RuntimeError("ядро не приняло новый конфиг")
|
|
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
|
|
|
|
|
|
def change_hidden(name, hide):
|
|
if not isinstance(name, str) or not name or len(name) > 200 or "\n" in name:
|
|
return {"ok": False, "error": "неверное имя подключения"}
|
|
with gen_lock:
|
|
h = load_hidden()
|
|
if name.startswith("AWG "):
|
|
if not awg_key_exists(name):
|
|
return {"ok": False, "error": "такого подключения нет"}
|
|
kind = "amnezia"
|
|
else:
|
|
vless = provider_names("vless-cluster") + provider_names("vless-keys")
|
|
if hide and name not in vless:
|
|
return {"ok": False, "error": "такого узла нет"}
|
|
if not hide and name not in h["vless"]:
|
|
return {"ok": False, "error": "этот узел не скрыт"}
|
|
kind = "vless"
|
|
if hide:
|
|
# Leave the connection before it disappears.
|
|
if kind == "amnezia" and api("GET", "/proxies/amnezia").get("now") == name:
|
|
api("PUT", "/proxies/amnezia", {"name": "amnezia-auto"})
|
|
if kind == "vless" and api("GET", "/proxies/ai-out").get("now") == name:
|
|
api("PUT", "/proxies/ai-out", {"name": "auto"})
|
|
if name not in h[kind]:
|
|
h[kind].append(name)
|
|
else:
|
|
h[kind] = [x for x in h[kind] if x != name]
|
|
before = load_hidden()
|
|
save_hidden(h)
|
|
gen()
|
|
if kind == "amnezia":
|
|
api("PUT", "/providers/proxies/amnezia-keys")
|
|
else:
|
|
try:
|
|
reload_core()
|
|
except Exception:
|
|
save_hidden(before) # keep disk and core in step
|
|
gen()
|
|
raise
|
|
return {"ok": True, "reloaded": kind == "vless"}
|
|
|
|
|
|
def cmd_refresh(_):
|
|
before = set(provider_names("vless-cluster"))
|
|
api("PUT", "/providers/proxies/vless-cluster", timeout=30)
|
|
after = provider_names("vless-cluster")
|
|
return {"ok": True, "nodes": after, "added": [n for n in after if n not in before],
|
|
"removed": sorted(before - set(after))}
|
|
|
|
|
|
def cmd_rebind(_):
|
|
"""After the Mac moved to another network (its address changed): a clean core restart.
|
|
mihomo's WireGuard outbounds stay bound to the old address; re-creating them through a
|
|
provider reload leaked every old tunnel (16.10: 652 UDP sockets, 677 MB, the Amnezia
|
|
servers stopped answering the handshake flood). A restart leaves nothing behind, and
|
|
the move has dropped the open TCP connections anyway. TUN comes back as tun.json says;
|
|
the DNS follows the newly active adapter."""
|
|
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
|
for _ in range(40):
|
|
time.sleep(0.25)
|
|
try:
|
|
api("GET", "/configs", timeout=2)
|
|
break
|
|
except Exception:
|
|
pass
|
|
try:
|
|
with open(os.path.join(CORE, "tun.json")) as f:
|
|
if json.load(f).get("on", True):
|
|
dns_to_core()
|
|
except (OSError, ValueError):
|
|
pass
|
|
return {"ok": True, "restarted": True}
|
|
|
|
|
|
def cmd_hide(r):
|
|
return change_hidden(r.get("name"), True)
|
|
|
|
|
|
def cmd_unhide(r):
|
|
return change_hidden(r.get("name"), False)
|
|
|
|
|
|
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
|
|
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide,
|
|
"refresh": cmd_refresh, "rebind": cmd_rebind}
|
|
|
|
|
|
# MARK: - Socket server
|
|
|
|
def peer_uid(conn):
|
|
# LOCAL_PEERCRED (SOL_LOCAL=0, opt=1) → struct xucred { u_int cr_version; uid_t cr_uid; … }
|
|
cred = conn.getsockopt(0, 1, 76)
|
|
return struct.unpack_from("I", cred, 4)[0]
|
|
|
|
|
|
def handle(conn):
|
|
try:
|
|
if peer_uid(conn) not in (0, ALLOWED_UID):
|
|
return
|
|
conn.settimeout(30)
|
|
buf = b""
|
|
while b"\n" not in buf and len(buf) < MAX_REQUEST:
|
|
chunk = conn.recv(8192)
|
|
if not chunk:
|
|
break
|
|
buf += chunk
|
|
req = json.loads(buf.split(b"\n", 1)[0] or b"{}")
|
|
fn = COMMANDS.get(req.get("cmd"))
|
|
if fn is None:
|
|
resp = {"ok": False, "error": "неизвестная команда"}
|
|
else:
|
|
try:
|
|
resp = fn(req)
|
|
except urllib.error.URLError:
|
|
resp = {"ok": False, "error": "ядро не отвечает"}
|
|
except Exception as e:
|
|
resp = {"ok": False, "error": str(e) or e.__class__.__name__}
|
|
conn.sendall((json.dumps(resp, ensure_ascii=False) + "\n").encode())
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def sync_dns_at_start():
|
|
"""At boot the core starts with capture as the user left it: DNS follows."""
|
|
on = True
|
|
try:
|
|
with open(os.path.join(CORE, "tun.json")) as f:
|
|
on = bool(json.load(f).get("on", True))
|
|
except (OSError, ValueError, AttributeError):
|
|
pass
|
|
try:
|
|
dns_to_core() if on else dns_restore()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def main():
|
|
if ALLOWED_UID < 0:
|
|
sys.exit("usage: netctl.py <uid allowed to connect>")
|
|
threading.Thread(target=sync_dns_at_start, daemon=True).start()
|
|
try:
|
|
os.unlink(SOCK)
|
|
except FileNotFoundError:
|
|
pass
|
|
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
old = os.umask(0o177)
|
|
srv.bind(SOCK)
|
|
os.umask(old)
|
|
os.chown(SOCK, ALLOWED_UID, -1)
|
|
os.chmod(SOCK, 0o600)
|
|
srv.listen(8)
|
|
while True:
|
|
conn, _ = srv.accept()
|
|
threading.Thread(target=handle, args=(conn,), daemon=True).start()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|