douyinWEB/backend/app/singbox_manager.py
2026-09-22 10:52:53 -05:00

399 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""DouyinWEB-only sing-box: local mixed → residential SOCKS5.
HARD ISOLATION from v2ray-agent:
- Never systemctl start/stop/restart the host unit ``sing-box.service``
- Never read/write ``/etc/v2ray-agent/``
- Only manage ``douyinweb-singbox`` (systemd) or a subprocess with
``${APP}/config/sing-box.json`` listening on 127.0.0.1:17891
"""
from __future__ import annotations
import json
import os
import shutil
import signal
import subprocess
import time
from pathlib import Path
from typing import Any
from .config import BACKEND
from .global_socks import (
CONFIG_DIR,
LOCAL_MIXED_HOST,
LOCAL_MIXED_PORT,
SINGBOX_CONFIG_PATH,
active_profile,
is_global_socks_enabled,
)
# App-owned unit only — NEVER bare "sing-box" (v2ray-agent).
UNIT_NAME = "douyinweb-singbox"
FORBIDDEN_UNITS = frozenset({"sing-box", "sing-box.service", "xray", "xray.service", "v2ray", "v2ray.service"})
V2RAY_AGENT_DIR = Path("/etc/v2ray-agent")
# Dedicated binary — NEVER use /etc/v2ray-agent/sing-box/sing-box
APP_BIN_DIR = BACKEND.parent / "bin"
APP_SINGBOX = APP_BIN_DIR / "sing-box"
# Pin a known-good release; install only into APP_BIN_DIR.
SINGBOX_VERSION = "1.11.15"
SINGBOX_ASSET = f"sing-box-{SINGBOX_VERSION}-linux-amd64.tar.gz"
SINGBOX_URL = f"https://github.com/SagerNet/sing-box/releases/download/v{SINGBOX_VERSION}/{SINGBOX_ASSET}"
_PID_FILE = CONFIG_DIR / "sing-box.pid"
_LOG_PATH = CONFIG_DIR / "sing-box.log"
def _assert_safe_unit(name: str) -> str:
raw = str(name or "").strip()
base = raw.removesuffix(".service")
if raw in FORBIDDEN_UNITS or base in FORBIDDEN_UNITS or base == "sing-box":
raise RuntimeError(f"refusing to touch host unit {raw!r} (v2ray-agent / edge)")
if base != UNIT_NAME and raw != UNIT_NAME:
raise RuntimeError(f"only {UNIT_NAME} is allowed, got {raw!r}")
return UNIT_NAME
def _assert_safe_binary(path: str) -> str:
"""Refuse any binary under v2ray-agent tree."""
p = Path(path).resolve()
try:
p.relative_to(V2RAY_AGENT_DIR.resolve())
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
except ValueError:
pass
if "v2ray-agent" in str(p):
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
return str(p)
def _find_binary() -> str:
"""Only DouyinWEB-owned paths — never PATH /usr/bin or v2ray-agent."""
candidates = [
APP_SINGBOX,
Path("/opt/douyinWEB/bin/sing-box"),
]
for cand in candidates:
if cand.is_file() and os.access(cand, os.X_OK):
try:
return _assert_safe_binary(str(cand))
except RuntimeError:
continue
return ""
def ensure_binary() -> str:
"""Install dedicated sing-box into /opt/douyinWEB/bin if missing."""
found = _find_binary()
if found:
return found
APP_BIN_DIR.mkdir(parents=True, exist_ok=True)
import tempfile
import urllib.request
tmp_dir = Path(tempfile.mkdtemp(prefix="dy-singbox-"))
try:
tgz = tmp_dir / SINGBOX_ASSET
urllib.request.urlretrieve(SINGBOX_URL, tgz) # noqa: S310
subprocess.run(
["tar", "-xzf", str(tgz), "-C", str(tmp_dir)],
check=True,
capture_output=True,
timeout=120,
)
# tarball contains sing-box-<ver>-linux-amd64/sing-box
extracted = next(tmp_dir.rglob("sing-box"), None)
if extracted is None or not extracted.is_file() or extracted.name != "sing-box":
# rglob may hit the dir; prefer the file
files = [p for p in tmp_dir.rglob("sing-box") if p.is_file()]
extracted = files[0] if files else None
if not extracted or not extracted.is_file():
raise RuntimeError("sing-box binary missing from release tarball")
dest = APP_SINGBOX
shutil.copy2(extracted, dest)
os.chmod(dest, 0o755)
return _assert_safe_binary(str(dest))
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
if not profile:
raise ValueError("SOCKS 配置无效")
server = str(profile.get("server") or "").strip()
port = int(profile.get("port") or 0)
if not server or port <= 0:
raise ValueError("SOCKS 服务器或端口无效")
outbound: dict[str, Any] = {
"type": "socks",
"tag": "upstream",
"server": server,
"server_port": port,
"version": "5",
}
user = str(profile.get("username") or "").strip()
pwd = str(profile.get("password") or "")
if user:
outbound["username"] = user
if pwd:
outbound["password"] = pwd
return {
"log": {"level": "warn", "timestamp": True},
"inbounds": [
{
"type": "mixed",
"tag": "mixed-in",
"listen": LOCAL_MIXED_HOST,
"listen_port": LOCAL_MIXED_PORT,
"sniff": True,
}
],
"outbounds": [
outbound,
{"type": "direct", "tag": "direct"},
],
"route": {
"rules": [],
"final": "upstream",
},
}
def write_config(cfg_dict: dict[str, Any]) -> Path:
if V2RAY_AGENT_DIR in SINGBOX_CONFIG_PATH.parents or str(SINGBOX_CONFIG_PATH).startswith(
str(V2RAY_AGENT_DIR)
):
raise RuntimeError("refusing to write config under /etc/v2ray-agent")
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
SINGBOX_CONFIG_PATH.write_text(json.dumps(cfg_dict, ensure_ascii=False, indent=2), encoding="utf-8")
try:
os.chmod(SINGBOX_CONFIG_PATH, 0o600)
except Exception:
pass
return SINGBOX_CONFIG_PATH
def _read_pid() -> int:
try:
return int(_PID_FILE.read_text(encoding="utf-8").strip())
except Exception:
return 0
def _pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
def is_running() -> bool:
pid = _read_pid()
if _pid_alive(pid):
return True
try:
r = subprocess.run(
["systemctl", "is-active", UNIT_NAME],
capture_output=True,
text=True,
timeout=5,
)
return r.returncode == 0 and "active" in (r.stdout or "")
except Exception:
return False
def stop() -> dict[str, Any]:
"""Stop DouyinWEB residential forwarder only — never host sing-box.service."""
pid = _read_pid()
if _pid_alive(pid):
try:
os.kill(pid, signal.SIGTERM)
time.sleep(0.8)
if _pid_alive(pid):
os.kill(pid, signal.SIGKILL)
except Exception:
pass
try:
_assert_safe_unit(UNIT_NAME)
subprocess.run(["systemctl", "stop", UNIT_NAME], capture_output=True, timeout=15)
except Exception:
pass
_PID_FILE.unlink(missing_ok=True)
return {"ok": True, "running": False, "unit": UNIT_NAME}
def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
try:
binary = ensure_binary()
except Exception as exc:
return {
"ok": False,
"running": False,
"error": f"无法安装 DouyinWEB 专用 sing-box: {exc}",
}
if not binary:
return {
"ok": False,
"running": False,
"error": "未找到 DouyinWEB 专用 sing-box(应位于 /opt/douyinWEB/bin/sing-box,不使用 v2ray-agent)",
}
write_config(cfg_dict)
stop()
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
log_f = open(_LOG_PATH, "a", encoding="utf-8") # noqa: SIM115
try:
proc = subprocess.Popen(
[binary, "run", "-c", str(SINGBOX_CONFIG_PATH)],
stdin=subprocess.DEVNULL,
stdout=log_f,
stderr=subprocess.STDOUT,
cwd=str(BACKEND),
start_new_session=True,
)
except Exception as exc:
log_f.close()
return {"ok": False, "running": False, "error": str(exc)}
_PID_FILE.write_text(str(proc.pid), encoding="utf-8")
time.sleep(0.6)
if proc.poll() is not None:
tail = ""
try:
tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:]
except Exception:
pass
return {"ok": False, "running": False, "error": f"douyinweb-singbox 启动失败: {tail}"}
return {
"ok": True,
"running": True,
"pid": proc.pid,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
}
def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from .global_socks import _settings_dict
settings = _settings_dict(cfg)
if not is_global_socks_enabled(settings):
stop()
return {"ok": True, "running": False, "enabled": False, "unit": UNIT_NAME}
prof = active_profile(settings)
if not prof:
stop()
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置", "unit": UNIT_NAME}
try:
cfg_dict = build_config(prof)
except ValueError as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
write_config(cfg_dict)
try:
ensure_binary()
except Exception as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
# Rewrite unit ExecStart to app-owned binary (never /usr/bin or v2ray-agent).
try:
_install_unit_file()
except Exception:
pass
try:
_assert_safe_unit(UNIT_NAME)
r = subprocess.run(
["systemctl", "restart", UNIT_NAME],
capture_output=True,
text=True,
timeout=20,
)
if r.returncode == 0:
time.sleep(0.5)
if is_running():
return {
"ok": True,
"running": True,
"enabled": True,
"via": "systemd",
"unit": UNIT_NAME,
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
}
except Exception:
pass
return {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
def host_v2ray_agent_status() -> dict[str, Any]:
"""Read-only peek at v2ray-agent edge (never mutate)."""
active = ""
try:
r = subprocess.run(
["systemctl", "is-active", "sing-box"],
capture_output=True,
text=True,
timeout=5,
)
active = (r.stdout or "").strip()
except Exception as exc:
active = f"error:{exc}"
return {
"unit": "sing-box.service",
"active": active,
"config_dir_exists": V2RAY_AGENT_DIR.is_dir(),
"note": "read-only; DouyinWEB never restarts this unit",
}
def _install_unit_file() -> None:
binary = ensure_binary()
unit = f"""[Unit]
Description=DouyinWEB residential SOCKS forwarder (isolated from v2ray-agent)
Documentation=file:/opt/douyinWEB/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/douyinWEB/backend
ExecStart={binary} run -c /opt/douyinWEB/config/sing-box.json
Restart=on-failure
RestartSec=3
Nice=5
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
ReadOnlyPaths=/etc/v2ray-agent
[Install]
WantedBy=multi-user.target
"""
path = Path(f"/etc/systemd/system/{UNIT_NAME}.service")
path.write_text(unit, encoding="utf-8")
subprocess.run(["systemctl", "daemon-reload"], capture_output=True, timeout=15)
def status() -> dict[str, Any]:
binary = _find_binary()
pid = _read_pid()
return {
"running": is_running(),
"pid": pid if _pid_alive(pid) else 0,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
"v2ray_agent": host_v2ray_agent_status(),
"isolation": {
"app_bin": str(APP_SINGBOX),
"never_uses": str(V2RAY_AGENT_DIR),
"never_restarts": "sing-box.service",
},
"error": "",
}