Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP. Co-authored-by: Cursor <cursoragent@cursor.com>
211 lines
6.0 KiB
Python
211 lines
6.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""sing-box local mixed inbound → remote SOCKS5 upstream."""
|
||
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,
|
||
)
|
||
|
||
_PID_FILE = CONFIG_DIR / "sing-box.pid"
|
||
_LOG_PATH = CONFIG_DIR / "sing-box.log"
|
||
|
||
|
||
def _find_binary() -> str:
|
||
for name in ("sing-box", "/usr/bin/sing-box", "/usr/local/bin/sing-box"):
|
||
p = shutil.which(name) if not name.startswith("/") else (name if Path(name).is_file() else None)
|
||
if p and Path(p).is_file():
|
||
return str(p)
|
||
return ""
|
||
|
||
|
||
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:
|
||
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")
|
||
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
|
||
# systemd fallback
|
||
try:
|
||
r = subprocess.run(
|
||
["systemctl", "is-active", "douyinweb-singbox"],
|
||
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]:
|
||
pid = _read_pid()
|
||
if _pid_alive(pid):
|
||
try:
|
||
os.kill(pid, signal.SIGTERM)
|
||
time.sleep(0.8)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
subprocess.run(["systemctl", "stop", "douyinweb-singbox"], capture_output=True, timeout=15)
|
||
except Exception:
|
||
pass
|
||
_PID_FILE.unlink(missing_ok=True)
|
||
return {"ok": True, "running": False}
|
||
|
||
|
||
def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
|
||
binary = _find_binary()
|
||
if not binary:
|
||
return {"ok": False, "running": False, "error": "未安装 sing-box(apt install sing-box 或官方脚本)"}
|
||
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"sing-box 启动失败: {tail}"}
|
||
return {"ok": True, "running": True, "pid": proc.pid, "binary": binary}
|
||
|
||
|
||
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}
|
||
prof = active_profile(settings)
|
||
if not prof:
|
||
stop()
|
||
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置"}
|
||
try:
|
||
cfg_dict = build_config(prof)
|
||
except ValueError as exc:
|
||
stop()
|
||
return {"ok": False, "running": False, "enabled": True, "error": str(exc)}
|
||
# Prefer systemd unit when present.
|
||
write_config(cfg_dict)
|
||
try:
|
||
r = subprocess.run(
|
||
["systemctl", "restart", "douyinweb-singbox"],
|
||
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"}
|
||
except Exception:
|
||
pass
|
||
return {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
|
||
|
||
|
||
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}",
|
||
"error": "",
|
||
}
|