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>
619 lines
24 KiB
Python
619 lines
24 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""ShellCrash hub — SH2-compatible controls + managed files + apply_profile."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
CONTROLLER = "http://127.0.0.1:9999"
|
||
DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_hysteria5")
|
||
DEFAULT_PROFILE = os.environ.get("DY_SHELLCRASH_DEFAULT_PROFILE", "config.yaml")
|
||
CANDIDATE_NODES = (
|
||
"1d2da142-singbox_hysteria5",
|
||
"1d2da142-singbox_tuic5",
|
||
"1d2da142-VLESS_Reality_Vision5",
|
||
"e3ea3b30-singbox_hysteria_vultr",
|
||
"e3ea3b30-singbox_tuic_vultr",
|
||
"242af835-singbox_hysteria",
|
||
"hackrobot-singbox_tuic",
|
||
"VLESS_Reality_Vision",
|
||
"socks5",
|
||
"proxycheap",
|
||
)
|
||
SELECT_GROUPS = ("GLOBAL", "🚀 节点选择")
|
||
|
||
MANAGED_ROOTS: dict[str, tuple[str, str]] = {
|
||
"shellcrash-yamls": ("yamls", "YAML 配置"),
|
||
"shellcrash-configs": ("configs", "配置文件"),
|
||
"shellcrash-jsons": ("jsons", "JSON"),
|
||
}
|
||
|
||
|
||
def _run(cmd: list[str], *, timeout: float = 15.0) -> dict[str, Any]:
|
||
try:
|
||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||
return {"ok": False, "code": 124, "stdout": "", "stderr": str(exc)}
|
||
return {
|
||
"ok": proc.returncode == 0,
|
||
"code": proc.returncode or 0,
|
||
"stdout": (proc.stdout or "").strip(),
|
||
"stderr": (proc.stderr or "").strip(),
|
||
}
|
||
|
||
|
||
def _priv(cmd: list[str], *, timeout: float = 20.0) -> dict[str, Any]:
|
||
if hasattr(os, "geteuid") and os.geteuid() == 0:
|
||
return _run(cmd, timeout=timeout)
|
||
if shutil.which("sudo"):
|
||
return _run(["sudo", "-n", *cmd], timeout=timeout)
|
||
return _run(cmd, timeout=timeout)
|
||
|
||
|
||
def shellcrash_dir() -> Path:
|
||
return Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash"))
|
||
|
||
|
||
def default_node() -> str:
|
||
return DEFAULT_NODE
|
||
|
||
|
||
def default_profile() -> str:
|
||
return DEFAULT_PROFILE
|
||
|
||
|
||
def _read_cfg() -> dict[str, str]:
|
||
cfg = shellcrash_dir() / "configs" / "ShellCrash.cfg"
|
||
out: dict[str, str] = {}
|
||
if not cfg.is_file():
|
||
return out
|
||
try:
|
||
lines = cfg.read_text(encoding="utf-8", errors="ignore").splitlines()
|
||
except OSError:
|
||
return out
|
||
for raw in lines:
|
||
if "=" not in raw or raw.lstrip().startswith("#"):
|
||
continue
|
||
key, _, value = raw.partition("=")
|
||
out[key.strip()] = value.strip()
|
||
return out
|
||
|
||
|
||
def _config_yaml() -> dict[str, Any]:
|
||
base = shellcrash_dir()
|
||
for path in (base / "yamls" / "config.yaml", Path("/tmp/ShellCrash/config.yaml"), base / "config.yaml"):
|
||
try:
|
||
if path.is_file() and path.stat().st_size > 0:
|
||
return {"available": True, "path": str(path), "bytes": path.stat().st_size}
|
||
except OSError:
|
||
continue
|
||
return {"available": False, "path": "", "bytes": 0}
|
||
|
||
|
||
def _unit_exists(unit: str) -> bool:
|
||
r = _run(["systemctl", "list-unit-files", unit, "--no-legend"], timeout=3.0)
|
||
return r["ok"] and unit in (r["stdout"] + r["stderr"])
|
||
|
||
|
||
def _stage_runtime_config(config_path: str) -> None:
|
||
src = Path(config_path)
|
||
if not src.is_file():
|
||
return
|
||
dst = Path("/tmp/ShellCrash/config.yaml")
|
||
try:
|
||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||
shutil.copyfile(src, dst)
|
||
dst.chmod(0o644)
|
||
except OSError:
|
||
return
|
||
|
||
|
||
def _http_json(url: str, *, method: str = "GET", body: dict[str, Any] | None = None, timeout: float = 6.0) -> dict[str, Any]:
|
||
data = None if body is None else json.dumps(body).encode("utf-8")
|
||
req = urllib.request.Request(
|
||
url,
|
||
data=data,
|
||
method=method,
|
||
headers={"Content-Type": "application/json"} if body is not None else {},
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
raw = resp.read().decode("utf-8", "replace")
|
||
return {"ok": True, "status": getattr(resp, "status", 200), "data": json.loads(raw) if raw.strip() else {}}
|
||
except urllib.error.HTTPError as exc:
|
||
return {"ok": False, "status": int(exc.code), "error": str(exc)}
|
||
except Exception as exc: # noqa: BLE001
|
||
return {"ok": False, "status": 0, "error": str(exc)}
|
||
|
||
|
||
def _safe_rel(root: Path, rel: str) -> Path:
|
||
rel = (rel or "").replace("\\", "/").lstrip("/")
|
||
if not rel or ".." in rel.split("/"):
|
||
raise ValueError("非法路径")
|
||
target = (root / rel).resolve()
|
||
root_res = root.resolve()
|
||
if root_res not in target.parents and target != root_res:
|
||
raise ValueError("路径越界")
|
||
return target
|
||
|
||
|
||
def managed_roots() -> list[dict[str, Any]]:
|
||
base = shellcrash_dir()
|
||
out: list[dict[str, Any]] = []
|
||
for root_id, (subdir, label) in MANAGED_ROOTS.items():
|
||
path = base / subdir
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
files = []
|
||
try:
|
||
for p in sorted(path.rglob("*")):
|
||
if p.is_file():
|
||
rel = p.relative_to(path).as_posix()
|
||
files.append({"path": rel, "size": p.stat().st_size})
|
||
except OSError:
|
||
files = []
|
||
out.append({"root_id": root_id, "label": label, "file_count": len(files), "files": files})
|
||
return out
|
||
|
||
|
||
def list_files(root_id: str) -> dict[str, Any]:
|
||
if root_id not in MANAGED_ROOTS:
|
||
raise ValueError(f"unknown root: {root_id}")
|
||
subdir, label = MANAGED_ROOTS[root_id]
|
||
path = shellcrash_dir() / subdir
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
files: list[dict[str, Any]] = []
|
||
for p in sorted(path.rglob("*")):
|
||
if p.is_file():
|
||
files.append({"path": p.relative_to(path).as_posix(), "size": p.stat().st_size})
|
||
return {"ok": True, "root_id": root_id, "label": label, "files": files}
|
||
|
||
|
||
def read_file(root_id: str, rel_path: str) -> dict[str, Any]:
|
||
if root_id not in MANAGED_ROOTS:
|
||
raise ValueError(f"unknown root: {root_id}")
|
||
subdir, _ = MANAGED_ROOTS[root_id]
|
||
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
|
||
if not target.is_file():
|
||
raise FileNotFoundError(rel_path)
|
||
text = target.read_text(encoding="utf-8", errors="replace")
|
||
return {"ok": True, "root_id": root_id, "path": rel_path, "content": text, "bytes": len(text.encode("utf-8"))}
|
||
|
||
|
||
def write_file(root_id: str, rel_path: str, content: str) -> dict[str, Any]:
|
||
if root_id not in MANAGED_ROOTS:
|
||
raise ValueError(f"unknown root: {root_id}")
|
||
subdir, _ = MANAGED_ROOTS[root_id]
|
||
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
# Write via temp then install with sudo if needed
|
||
tmp = Path("/tmp") / f"_sc_write_{os.getpid()}_{target.name}"
|
||
tmp.write_text(content if content.endswith("\n") else content + "\n", encoding="utf-8")
|
||
r = _priv(["install", "-m", "644", str(tmp), str(target)], timeout=10.0)
|
||
try:
|
||
tmp.unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
if not r.get("ok") and not target.is_file():
|
||
raise RuntimeError(r.get("stderr") or "写入失败(需要 sudo 权限)")
|
||
if not r.get("ok"):
|
||
# fallback direct write
|
||
try:
|
||
target.write_text(content if content.endswith("\n") else content + "\n", encoding="utf-8")
|
||
except OSError as exc:
|
||
raise RuntimeError(str(exc)) from exc
|
||
return {"ok": True, "root_id": root_id, "path": rel_path, "bytes": target.stat().st_size}
|
||
|
||
|
||
def delete_file(root_id: str, rel_path: str) -> dict[str, Any]:
|
||
if root_id not in MANAGED_ROOTS:
|
||
raise ValueError(f"unknown root: {root_id}")
|
||
subdir, _ = MANAGED_ROOTS[root_id]
|
||
target = _safe_rel(shellcrash_dir() / subdir, rel_path)
|
||
if not target.is_file():
|
||
raise FileNotFoundError(rel_path)
|
||
r = _priv(["rm", "-f", str(target)], timeout=10.0)
|
||
if target.exists():
|
||
try:
|
||
target.unlink()
|
||
except OSError as exc:
|
||
if not r.get("ok"):
|
||
raise RuntimeError(str(exc)) from exc
|
||
return {"ok": True, "root_id": root_id, "path": rel_path}
|
||
|
||
|
||
def _patch_yaml_listeners(text: str) -> str:
|
||
lines: list[str] = []
|
||
found_ec = found_mp = False
|
||
for line in text.splitlines():
|
||
if line.startswith("global-client-fingerprint:"):
|
||
continue
|
||
if line.startswith("external-controller:"):
|
||
lines.append("external-controller: 0.0.0.0:9999")
|
||
found_ec = True
|
||
continue
|
||
if line.startswith("mixed-port:"):
|
||
lines.append("mixed-port: 7890")
|
||
found_mp = True
|
||
continue
|
||
lines.append(line)
|
||
if not found_ec:
|
||
lines.append("external-controller: 0.0.0.0:9999")
|
||
if not found_mp:
|
||
lines.append("mixed-port: 7890")
|
||
return _ensure_douyin_direct_rules("\n".join(lines).rstrip() + "\n")
|
||
|
||
|
||
# Hard requirement: Douyin must never go through overseas proxy nodes.
|
||
_DOUYIN_DIRECT_RULES = (
|
||
" - DOMAIN-SUFFIX,douyin.com,DIRECT",
|
||
" - DOMAIN-SUFFIX,douyincdn.com,DIRECT",
|
||
" - DOMAIN-SUFFIX,douyinpic.com,DIRECT",
|
||
" - DOMAIN-SUFFIX,douyinvod.com,DIRECT",
|
||
" - DOMAIN-SUFFIX,douyinstatic.com,DIRECT",
|
||
" - DOMAIN-SUFFIX,iesdouyin.com,DIRECT",
|
||
" - DOMAIN-KEYWORD,douyin,DIRECT",
|
||
)
|
||
|
||
|
||
def _ensure_douyin_direct_rules(text: str) -> str:
|
||
"""Prepend explicit Douyin DIRECT rules under `rules:` (idempotent)."""
|
||
if "DOMAIN-SUFFIX,douyin.com,DIRECT" in text:
|
||
return text
|
||
block = "\n".join(_DOUYIN_DIRECT_RULES) + "\n"
|
||
if re.search(r"(?m)^rules:\s*$", text):
|
||
return re.sub(r"(?m)^(rules:\s*\n)", r"\1" + block, text, count=1)
|
||
# No rules section — append one.
|
||
return text.rstrip() + "\n\nrules:\n" + block + " - MATCH,DIRECT\n"
|
||
|
||
|
||
def _select_node_in_groups(node: str) -> list[dict[str, Any]]:
|
||
listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0)
|
||
proxies = (listed.get("data") or {}).get("proxies") or {} if listed.get("ok") else {}
|
||
applied: list[dict[str, Any]] = []
|
||
for group in SELECT_GROUPS:
|
||
if group != "GLOBAL" and group not in proxies:
|
||
continue
|
||
enc = urllib.parse.quote(group, safe="")
|
||
put = _http_json(f"{CONTROLLER}/proxies/{enc}", method="PUT", body={"name": node}, timeout=5.0)
|
||
applied.append({"group": group, "ok": bool(put.get("ok")), "status": put.get("status")})
|
||
return applied
|
||
|
||
|
||
def apply_profile(rel_path: str | None = None, target_node: str | None = None) -> dict[str, Any]:
|
||
"""SH2-compatible: stage YAML → config.yaml → restart → select node."""
|
||
rel = (rel_path or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
|
||
node = (target_node or DEFAULT_NODE).strip() or DEFAULT_NODE
|
||
yamls = shellcrash_dir() / "yamls"
|
||
yamls.mkdir(parents=True, exist_ok=True)
|
||
source = _safe_rel(yamls, rel)
|
||
if not source.is_file():
|
||
# allow reading from staged clash assets copy
|
||
assets = Path(__file__).resolve().parent / "clash_assets" / "clash.yaml"
|
||
if assets.is_file() and rel in {"config.yaml", "clash.yaml", DEFAULT_PROFILE}:
|
||
text = assets.read_text(encoding="utf-8", errors="replace")
|
||
else:
|
||
raise FileNotFoundError(rel)
|
||
else:
|
||
text = source.read_text(encoding="utf-8", errors="replace")
|
||
|
||
text = _patch_yaml_listeners(text)
|
||
# Prefer target node first in select groups when present as a name token
|
||
if node and re.search(rf"(?m)^\s*-\s*{re.escape(node)}\s*$", text):
|
||
# light-touch: no full YAML reorder required; runtime select via API after restart
|
||
pass
|
||
|
||
write_file("shellcrash-yamls", rel if rel.endswith((".yaml", ".yml")) else "config.yaml", text)
|
||
write_file("shellcrash-yamls", "config.yaml", text)
|
||
_stage_runtime_config(str(yamls / "config.yaml"))
|
||
|
||
unit = "shellcrash.service"
|
||
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
|
||
run = _priv(["systemctl", "restart", unit], timeout=40.0)
|
||
time.sleep(3.0)
|
||
applied = _select_node_in_groups(node)
|
||
st = status()
|
||
return {
|
||
"ok": bool(st.get("running")),
|
||
"message": "ShellCrash 配置已应用",
|
||
"path": rel,
|
||
"target_node": node,
|
||
"selected": st.get("selected_node") or node,
|
||
"applied_groups": applied,
|
||
"command_ok": bool(run.get("ok")),
|
||
"shellcrash": st,
|
||
}
|
||
|
||
|
||
def apply_residential_chain(profile: dict[str, Any], *, dialer: str = "dialer") -> dict[str, Any]:
|
||
"""Upsert socks5 landing with dialer-proxy, restart ShellCrash, select it.
|
||
|
||
Path: local → ShellCrash → [dialer group/node] → residential SOCKS → target
|
||
See: https://wiki.metacubex.one/config/proxies/dialer-proxy/
|
||
"""
|
||
name = "dy-residential"
|
||
dialer = (dialer or "dialer").strip() or "dialer"
|
||
server = str(profile.get("server") or "").strip()
|
||
try:
|
||
port = int(profile.get("port") or 0)
|
||
except Exception:
|
||
port = 0
|
||
user = str(profile.get("username") or "")
|
||
pwd = str(profile.get("password") or "")
|
||
if not server or port <= 0:
|
||
raise ValueError("住宅 SOCKS 服务器/端口无效")
|
||
|
||
block_lines = [
|
||
f" - name: {name}",
|
||
f" dialer-proxy: {dialer}",
|
||
" type: socks5",
|
||
f" server: {server}",
|
||
f" port: {port}",
|
||
]
|
||
if user:
|
||
block_lines.append(f" username: {user}")
|
||
if pwd:
|
||
block_lines.append(f" password: {pwd}")
|
||
block = "\n".join(block_lines) + "\n"
|
||
|
||
yamls = shellcrash_dir() / "yamls"
|
||
yamls.mkdir(parents=True, exist_ok=True)
|
||
cfg_path = yamls / "config.yaml"
|
||
if cfg_path.is_file():
|
||
text = cfg_path.read_text(encoding="utf-8", errors="replace")
|
||
else:
|
||
assets = Path(__file__).resolve().parent / "clash_assets" / "clash.yaml"
|
||
text = assets.read_text(encoding="utf-8", errors="replace") if assets.is_file() else "proxies:\n"
|
||
|
||
text = _upsert_proxy_block(text, name, block)
|
||
text = _ensure_proxy_in_select_groups(text, name)
|
||
text = _patch_yaml_listeners(text)
|
||
|
||
write_file("shellcrash-yamls", "config.yaml", text)
|
||
_stage_runtime_config(str(yamls / "config.yaml"))
|
||
|
||
unit = "shellcrash.service"
|
||
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
|
||
run = _priv(["systemctl", "restart", unit], timeout=40.0)
|
||
time.sleep(3.0)
|
||
applied = _select_node_in_groups(name)
|
||
st = status()
|
||
return {
|
||
"ok": bool(st.get("running")),
|
||
"message": "已启用住宅链式落地(dialer-proxy)",
|
||
"proxy_name": name,
|
||
"dialer": dialer,
|
||
"selected": st.get("selected_node") or name,
|
||
"applied_groups": applied,
|
||
"command_ok": bool(run.get("ok")),
|
||
"shellcrash": st,
|
||
"docs": "https://wiki.metacubex.one/config/proxies/dialer-proxy/",
|
||
}
|
||
|
||
|
||
def _upsert_proxy_block(text: str, name: str, block: str) -> str:
|
||
"""Replace existing `- name: {name}` proxy entry or insert under proxies:."""
|
||
# Remove existing block for this name (from its "- name:" until next top-level proxy or section).
|
||
pattern = re.compile(
|
||
rf"(?ms)^ - name:\s*{re.escape(name)}\s*\n(?: .*\n)*",
|
||
)
|
||
text2, n = pattern.subn("", text)
|
||
if "proxies:" not in text2:
|
||
return "proxies:\n" + block + text2
|
||
# Insert right after `proxies:` line
|
||
return re.sub(r"(?m)^(proxies:\s*\n)", r"\1" + block, text2, count=1)
|
||
|
||
|
||
def _ensure_proxy_in_select_groups(text: str, name: str) -> str:
|
||
"""Append proxy name into main select groups if missing (best-effort)."""
|
||
if re.search(rf"(?m)^\s*-\s*{re.escape(name)}\s*$", text):
|
||
return text
|
||
# Insert into first proxy-groups select list after `proxies:` under that group — skip if hard.
|
||
# Prefer injecting near proxycheap if present.
|
||
if re.search(r"(?m)^\s*-\s*proxycheap\s*$", text):
|
||
return re.sub(r"(?m)^(\s*-\s*proxycheap\s*)$", rf"\1\n - {name}", text, count=1)
|
||
return text
|
||
|
||
|
||
def _wg_overlay_ip() -> str:
|
||
"""Best-effort WireGuard overlay address (e.g. 10.8.0.2) for direct :9999 access."""
|
||
r = _run(["bash", "-lc", "ip -4 -o addr show wg-dy 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1"])
|
||
ip = (r.get("stdout") or "").strip().splitlines()
|
||
if ip and ip[0]:
|
||
return ip[0].strip()
|
||
env_ip = (os.environ.get("DY_NEKO_EDGE_UPSTREAM") or os.environ.get("DY_WG_OVERLAY_IP") or "").strip()
|
||
return env_ip
|
||
|
||
|
||
def _controller_secret() -> str:
|
||
yml = shellcrash_dir() / "yamls" / "config.yaml"
|
||
try:
|
||
text = yml.read_text(encoding="utf-8", errors="replace")
|
||
except OSError:
|
||
return ""
|
||
m = re.search(r"(?m)^\s*secret:\s*[\"']?([^\"'\n#]+)", text)
|
||
return (m.group(1).strip() if m else "")
|
||
|
||
|
||
def web_panel() -> dict[str, Any]:
|
||
"""Ensure service up; return dashboard URL on our public domain.
|
||
|
||
Physical edge Caddy proxies ``/ui`` + Clash API → WG ``:9999``.
|
||
Open ``/ui/#/setup?...`` with HTTPS backend prefilled so Zashboard does not
|
||
default to ``http://127.0.0.1:9090`` (mixed-content / unreachable).
|
||
"""
|
||
st = status()
|
||
if not st.get("running"):
|
||
action("start")
|
||
time.sleep(2.0)
|
||
st = status()
|
||
public = (os.environ.get("DY_PUBLIC_BASE_URL") or "").rstrip("/")
|
||
secret = _controller_secret()
|
||
secret_q = f"&secret={urllib.parse.quote(secret)}" if secret else ""
|
||
wg_ip = _wg_overlay_ip()
|
||
direct_url = f"http://{wg_ip}:9999/ui/#/proxies" if wg_ip else "http://127.0.0.1:9999/ui/#/proxies"
|
||
if public:
|
||
host = urllib.parse.urlparse(public).hostname or ""
|
||
# Must stay under /ui/; prefill HTTPS controller (same origin, port 443).
|
||
url = (
|
||
f"{public}/ui/#/setup?hostname={urllib.parse.quote(host)}"
|
||
f"&port=443&protocol=https{secret_q}"
|
||
)
|
||
proxies_url = f"{public}/ui/#/proxies"
|
||
else:
|
||
url = direct_url
|
||
proxies_url = direct_url
|
||
ui_dir = shellcrash_dir() / "ui"
|
||
ui_ok = ui_dir.is_dir() and (ui_dir / "index.html").is_file()
|
||
return {
|
||
"ok": True,
|
||
"message": "ShellCrash web 面板已就绪" if st.get("running") else "服务未就绪,仍返回面板地址",
|
||
"url": url,
|
||
"proxies_url": proxies_url,
|
||
"direct_url": direct_url,
|
||
"port": "9999",
|
||
"ui_installed": ui_ok,
|
||
"shellcrash": status(),
|
||
}
|
||
|
||
|
||
def probe_mixed(*, timeout: float = 10.0) -> dict[str, Any]:
|
||
cfg = _read_cfg()
|
||
port = cfg.get("mix_port") or "7890"
|
||
cmd = [
|
||
"curl", "-sS", "-m", str(int(timeout)), "-o", "/dev/null", "-w", "%{http_code}",
|
||
"-x", f"http://127.0.0.1:{port}", "https://www.google.com/generate_204",
|
||
]
|
||
r = _run(cmd, timeout=timeout + 2)
|
||
code = (r.get("stdout") or "").strip()
|
||
return {"ok": code in {"204", "200", "301", "302"}, "http_code": code, "mixed_port": port, "detail": r.get("stderr") or ""}
|
||
|
||
|
||
def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]:
|
||
listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0)
|
||
if not listed.get("ok"):
|
||
return {"ok": False, "error": listed.get("error") or "controller unreachable", "picked": None}
|
||
proxies = (listed.get("data") or {}).get("proxies") or {}
|
||
delays: list[dict[str, Any]] = []
|
||
best_name: str | None = None
|
||
best_delay = 10**9
|
||
for name in CANDIDATE_NODES:
|
||
if name not in proxies:
|
||
continue
|
||
enc = urllib.parse.quote(name, safe="")
|
||
url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204"
|
||
res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0)
|
||
delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0
|
||
delays.append({"name": name, "delay": delay, "ok": delay > 0})
|
||
if delay > 0 and delay < best_delay:
|
||
best_name, best_delay = name, delay
|
||
applied: list[dict[str, Any]] = []
|
||
if best_name:
|
||
applied = _select_node_in_groups(best_name)
|
||
egress = probe_mixed() if best_name else {"ok": False, "http_code": ""}
|
||
return {
|
||
"ok": bool(best_name) and bool(egress.get("ok")),
|
||
"picked": best_name,
|
||
"delay_ms": best_delay if best_name else None,
|
||
"delays": delays,
|
||
"applied": applied,
|
||
"egress": egress,
|
||
}
|
||
|
||
|
||
def status() -> dict[str, Any]:
|
||
cfg_vals = _read_cfg()
|
||
yaml = _config_yaml()
|
||
unit_name = "shellcrash.service"
|
||
active = _run(["systemctl", "is-active", unit_name], timeout=3.0) if shutil.which("systemctl") else {"ok": False, "stdout": "unknown"}
|
||
enabled = _run(["systemctl", "is-enabled", unit_name], timeout=3.0) if shutil.which("systemctl") else {"ok": False, "stdout": "unknown"}
|
||
pgrep = _run(["pgrep", "-fa", "CrashCore|mihomo"], timeout=2.0) if shutil.which("pgrep") else {"ok": False, "stdout": ""}
|
||
unit_active = (active.get("stdout") or "").splitlines()[0] if active.get("stdout") else ("active" if active.get("ok") else "inactive")
|
||
running = unit_active == "active" or bool((pgrep.get("stdout") or "").strip())
|
||
start_sh = shellcrash_dir() / "start.sh"
|
||
mixed = cfg_vals.get("mix_port") or "7890"
|
||
selected = None
|
||
if running:
|
||
prox = _http_json(f"{CONTROLLER}/proxies", timeout=3.0)
|
||
if prox.get("ok"):
|
||
pdata = (prox.get("data") or {}).get("proxies") or {}
|
||
selected = (pdata.get("🚀 节点选择") or {}).get("now") or (pdata.get("GLOBAL") or {}).get("now")
|
||
return {
|
||
"ok": True,
|
||
"available": yaml.get("available") or start_sh.is_file() or unit_active == "active",
|
||
"installed": start_sh.is_file() or _unit_exists(unit_name),
|
||
"running": running,
|
||
"unit": unit_active,
|
||
"enabled": (enabled.get("stdout") or "").splitlines()[0] if enabled.get("stdout") else "unknown",
|
||
"label": "ShellCrash",
|
||
"description": "代理上网 / 规则分流",
|
||
"detail": f"mixed :{mixed}" + (f" · 节点 {selected}" if selected else ""),
|
||
"status": "online" if running else ("configured" if start_sh.is_file() or _unit_exists(unit_name) else "missing"),
|
||
"mixed_port": mixed,
|
||
"selected_node": selected,
|
||
"default_node": DEFAULT_NODE,
|
||
"default_profile": DEFAULT_PROFILE,
|
||
"config": yaml,
|
||
"roots": managed_roots(),
|
||
"hint": "应用配置会写入 config.yaml 并重启;web 面板打开 mihomo UI。",
|
||
}
|
||
|
||
|
||
def action(act: str) -> dict[str, Any]:
|
||
act = str(act or "").strip().lower()
|
||
if act not in {"start", "stop", "restart", "status", "pick"}:
|
||
raise ValueError(f"unsupported shellcrash action: {act}")
|
||
if act == "status":
|
||
return {"ok": True, "action": "status", **status()}
|
||
if act == "pick":
|
||
picked = pick_best_node()
|
||
return {"ok": bool(picked.get("ok")), "action": "pick", "pick": picked, "shellcrash": status()}
|
||
|
||
unit = "shellcrash.service"
|
||
cfg = _config_yaml()
|
||
if cfg.get("available") and act in {"start", "restart"}:
|
||
_stage_runtime_config(str(cfg.get("path") or ""))
|
||
|
||
if _unit_exists(unit) or shutil.which("systemctl"):
|
||
if act == "start":
|
||
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
|
||
run = _priv(["systemctl", "enable", "--now", unit], timeout=25.0)
|
||
elif act == "stop":
|
||
run = _priv(["systemctl", "stop", unit], timeout=20.0)
|
||
else:
|
||
_priv(["systemctl", "reset-failed", unit], timeout=5.0)
|
||
run = _priv(["systemctl", "restart", unit], timeout=25.0)
|
||
else:
|
||
start = shellcrash_dir() / "start.sh"
|
||
if not start.is_file():
|
||
raise RuntimeError("未安装 ShellCrash(无 systemd 单元且无 start.sh)")
|
||
run = _priv(["bash", str(start), act if act != "restart" else "restart"], timeout=25.0)
|
||
|
||
time.sleep(2.0)
|
||
picked = None
|
||
if act in {"start", "restart"}:
|
||
time.sleep(1.0)
|
||
# Prefer configured default node first, then pick if needed
|
||
_select_node_in_groups(DEFAULT_NODE)
|
||
egress = probe_mixed(timeout=6.0)
|
||
if not egress.get("ok"):
|
||
picked = pick_best_node()
|
||
st = status()
|
||
ok = bool(st.get("running")) if act in {"start", "restart"} else (not st.get("running") if act == "stop" else True)
|
||
return {
|
||
"ok": bool(run.get("ok")) or ok,
|
||
"action": act,
|
||
"command_ok": bool(run.get("ok")),
|
||
"detail": run.get("stderr") or run.get("stdout") or "",
|
||
"pick": picked,
|
||
"shellcrash": st,
|
||
}
|