norain 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- norain/__init__.py +3 -0
- norain/__main__.py +5 -0
- norain/block.py +281 -0
- norain/boot.py +142 -0
- norain/cli.py +748 -0
- norain/control.py +703 -0
- norain/defaults.py +42 -0
- norain/generate.py +264 -0
- norain/install.py +312 -0
- norain/maintain.py +313 -0
- norain/model.py +409 -0
- norain/monitor.py +314 -0
- norain/paths.py +124 -0
- norain/probe.py +158 -0
- norain/proxy.py +136 -0
- norain/repair.py +278 -0
- norain/routing.py +332 -0
- norain/rules.py +214 -0
- norain/runner.py +59 -0
- norain-0.2.0.dev0.dist-info/METADATA +99 -0
- norain-0.2.0.dev0.dist-info/RECORD +53 -0
- norain-0.2.0.dev0.dist-info/WHEEL +5 -0
- norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
- norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
- norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
- norain_core/__init__.py +4 -0
- norain_core/apply.py +70 -0
- norain_core/atomic.py +80 -0
- norain_core/cliutil.py +68 -0
- norain_core/daemonctl.py +192 -0
- norain_core/errors.py +60 -0
- norain_core/fetch.py +158 -0
- norain_core/log.py +104 -0
- norain_core/migrate.py +86 -0
- norain_core/osutil.py +332 -0
- norain_core/redact.py +60 -0
- norain_core/secrets.py +87 -0
- norain_core/singbox.py +93 -0
- norain_core/state.py +97 -0
- norain_core/supervisor.py +352 -0
- norain_core/sysproxy.py +112 -0
- norain_core/tomlio.py +86 -0
- norain_server/__init__.py +3 -0
- norain_server/__main__.py +5 -0
- norain_server/cert.py +276 -0
- norain_server/cli.py +477 -0
- norain_server/deploy.py +604 -0
- norain_server/firewall.py +226 -0
- norain_server/generate.py +112 -0
- norain_server/model.py +272 -0
- norain_server/paths.py +101 -0
- norain_server/runner.py +123 -0
- norain_server/service.py +83 -0
norain/proxy.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""代理模块:负责转发的核心——一个被监督的 sing-box 进程。
|
|
2
|
+
|
|
3
|
+
转发本身由 sing-box 完成(不重复造轮子);本模块把共享的监督器(norain_core.supervisor)
|
|
4
|
+
包成可以由内控制模块启动、停止、重启的组件。监督器自己负责 sing-box 崩溃后的有限次重启,
|
|
5
|
+
超过上限后本模块进入 failed 状态,由自维持模块接手(修复 → 阻断)。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from norain_core import sysproxy
|
|
17
|
+
from norain_core.errors import EXIT_OK
|
|
18
|
+
from norain_core.state import read_json
|
|
19
|
+
from norain_core.supervisor import STOP_GRACE_SECONDS, Spec, Supervisor
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ProxyModule:
|
|
23
|
+
name = "proxy"
|
|
24
|
+
|
|
25
|
+
def __init__(self, spec_fn: Callable[[], Spec], sysproxy_state: Path | None = None) -> None:
|
|
26
|
+
self._spec_fn = spec_fn
|
|
27
|
+
# traffic_mode = system-proxy 时由 sing-box 写系统代理;它被硬杀时不还原,所以这里自己记账
|
|
28
|
+
self._sysproxy_state = sysproxy_state
|
|
29
|
+
self._sysproxy_snapshot: dict | None = None
|
|
30
|
+
self._sysproxy_lock = threading.Lock()
|
|
31
|
+
self.spec: Spec | None = None
|
|
32
|
+
self.sup: Supervisor | None = None
|
|
33
|
+
self.exit_code: int | None = None
|
|
34
|
+
self.started_at: float | None = None
|
|
35
|
+
self._thread: threading.Thread | None = None
|
|
36
|
+
self._lifetime_restarts = 0
|
|
37
|
+
|
|
38
|
+
def _run(self, sup: Supervisor) -> None:
|
|
39
|
+
try:
|
|
40
|
+
self.exit_code = sup.run()
|
|
41
|
+
except Exception: # noqa: BLE001 监督器自身异常按故障处理
|
|
42
|
+
self.exit_code = 1
|
|
43
|
+
finally:
|
|
44
|
+
self._lifetime_restarts += sup.total_restarts
|
|
45
|
+
self._restore_snapshot() # sing-box 已退出(含被硬杀):把系统代理写回原样
|
|
46
|
+
|
|
47
|
+
# ---- 系统代理快照:sing-box 的 set_system_proxy 不保证还原(见 norain_core.sysproxy) ----
|
|
48
|
+
|
|
49
|
+
def _restore_stale(self) -> None:
|
|
50
|
+
"""上次被强杀留下的快照:在重新启动前先还原,避免系统代理一直指着死端口。"""
|
|
51
|
+
path = self._sysproxy_state
|
|
52
|
+
if path is None:
|
|
53
|
+
return
|
|
54
|
+
values = sysproxy.load(path)
|
|
55
|
+
if values:
|
|
56
|
+
sysproxy.write(values)
|
|
57
|
+
sysproxy.discard(path)
|
|
58
|
+
|
|
59
|
+
def _save_snapshot(self) -> None:
|
|
60
|
+
if self._sysproxy_state is None:
|
|
61
|
+
return
|
|
62
|
+
values = sysproxy.read()
|
|
63
|
+
if values is None:
|
|
64
|
+
return
|
|
65
|
+
self._sysproxy_snapshot = values
|
|
66
|
+
sysproxy.save(self._sysproxy_state, values)
|
|
67
|
+
|
|
68
|
+
def _restore_snapshot(self) -> None:
|
|
69
|
+
with self._sysproxy_lock:
|
|
70
|
+
values, self._sysproxy_snapshot = self._sysproxy_snapshot, None
|
|
71
|
+
if values is None or self._sysproxy_state is None:
|
|
72
|
+
return
|
|
73
|
+
sysproxy.write(values)
|
|
74
|
+
sysproxy.discard(self._sysproxy_state)
|
|
75
|
+
|
|
76
|
+
def start(self) -> None:
|
|
77
|
+
if self.alive():
|
|
78
|
+
return
|
|
79
|
+
self._restore_stale()
|
|
80
|
+
self._save_snapshot()
|
|
81
|
+
try:
|
|
82
|
+
self.spec = self._spec_fn()
|
|
83
|
+
except Exception:
|
|
84
|
+
self._restore_snapshot()
|
|
85
|
+
raise
|
|
86
|
+
self.sup = Supervisor(self.spec)
|
|
87
|
+
self.exit_code = None
|
|
88
|
+
self.started_at = time.time()
|
|
89
|
+
self._thread = threading.Thread(target=self._run, args=(self.sup,), name="norain-proxy", daemon=True)
|
|
90
|
+
self._thread.start()
|
|
91
|
+
|
|
92
|
+
def stop(self) -> None:
|
|
93
|
+
if self.sup is not None:
|
|
94
|
+
self.sup.request_stop()
|
|
95
|
+
if self._thread is not None:
|
|
96
|
+
self._thread.join(STOP_GRACE_SECONDS + 10)
|
|
97
|
+
self._restore_snapshot()
|
|
98
|
+
|
|
99
|
+
def alive(self) -> bool:
|
|
100
|
+
return bool(self._thread and self._thread.is_alive())
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def failed(self) -> bool:
|
|
104
|
+
"""监督器已经放弃(达到连续重启上限或自身出错)。"""
|
|
105
|
+
return not self.alive() and self.exit_code not in (None, EXIT_OK)
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def child_pid(self) -> int | None:
|
|
109
|
+
return self.sup.child_pid if self.sup is not None and self.alive() else None
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def ready(self) -> bool:
|
|
113
|
+
"""sing-box 在运行,并且所有本地端口都已开始监听。"""
|
|
114
|
+
# 直接问监督器(同一进程里的对象):这个属性每秒被读很多次,不值得每次读状态文件再查进程表
|
|
115
|
+
sup = self.sup
|
|
116
|
+
return bool(sup is not None and self.alive() and sup.ready and sup.child_pid is not None)
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def restarts(self) -> int:
|
|
120
|
+
return self._lifetime_restarts + (self.sup.total_restarts if self.sup and self.alive() else 0)
|
|
121
|
+
|
|
122
|
+
def wait_ready(self, timeout: float) -> bool:
|
|
123
|
+
deadline = time.monotonic() + timeout
|
|
124
|
+
while time.monotonic() < deadline:
|
|
125
|
+
if self.ready:
|
|
126
|
+
return True
|
|
127
|
+
if self.failed:
|
|
128
|
+
return False
|
|
129
|
+
time.sleep(0.2)
|
|
130
|
+
return self.ready
|
|
131
|
+
|
|
132
|
+
def status(self) -> dict:
|
|
133
|
+
state = "running" if self.ready else "starting" if self.alive() else "failed" if self.failed else "stopped"
|
|
134
|
+
return {"state": state, "pid": self.child_pid, "restarts": self.restarts,
|
|
135
|
+
"exit_code": self.exit_code,
|
|
136
|
+
"last_result": read_json(self.spec.last_error_file) if self.spec and self.failed else None}
|
norain/repair.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""修复模块:把代理重置回最初状态。四种修复,各对应一条命令(`norain repair <级别>`):
|
|
2
|
+
|
|
3
|
+
file 文件修复:扫描程序目录,按哈希清单判断文件损坏或缺失,从安装包副本里重新解出。
|
|
4
|
+
builtin 内置配置修复:清掉代理内部状态(生成的 sing-box 配置、选中的协议、学到的名单、
|
|
5
|
+
错误记录),从 cfg.toml 重新生成。不动用户配置。
|
|
6
|
+
full 完全配置修复:在 builtin 之上,把用户配置恢复为安装时的初始配置,并恢复计算机的
|
|
7
|
+
配置(解除阻断对防火墙的修改、清除残留的系统代理、重新同步自启动项)。
|
|
8
|
+
reload 重载修复:完全卸载并清除痕迹,再用安装包副本重新安装。
|
|
9
|
+
|
|
10
|
+
自维持模块只使用 file 和 builtin 两种。卸载部分是独立的命令(`norain uninstall`)。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
import zipfile
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from norain_core import atomic, fetch, singbox
|
|
24
|
+
from norain_core.errors import EXIT_CONFLICT, NorainError
|
|
25
|
+
from norain_core.log import Logger
|
|
26
|
+
from norain_core.state import read_json, write_json
|
|
27
|
+
|
|
28
|
+
from .paths import Paths
|
|
29
|
+
|
|
30
|
+
PACKAGES = ("norain", "norain_core", "norain_server")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Report:
|
|
35
|
+
level: str
|
|
36
|
+
actions: list[str] = field(default_factory=list)
|
|
37
|
+
problems: list[str] = field(default_factory=list) # 没能修好的
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def ok(self) -> bool:
|
|
41
|
+
return not self.problems
|
|
42
|
+
|
|
43
|
+
def as_dict(self) -> dict:
|
|
44
|
+
return {"level": self.level, "ok": self.ok, "actions": self.actions, "problems": self.problems}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def package_root() -> Path:
|
|
48
|
+
"""程序文件所在的目录(site-packages 或源码的 src/)。"""
|
|
49
|
+
return Path(__file__).resolve().parent.parent
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _sha(path: Path) -> str:
|
|
53
|
+
return fetch.sha256_file(path)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _package_files(root: Path) -> list[Path]:
|
|
57
|
+
out = []
|
|
58
|
+
for pkg in PACKAGES:
|
|
59
|
+
base = root / pkg
|
|
60
|
+
if base.is_dir():
|
|
61
|
+
out += [p for p in sorted(base.rglob("*")) if p.is_file() and "__pycache__" not in p.parts
|
|
62
|
+
and p.suffix != ".pyc"]
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def save_package(paths: Paths) -> dict:
|
|
67
|
+
"""安装时调用:把当前的程序文件打成安装包副本,并写哈希清单。"""
|
|
68
|
+
root = package_root()
|
|
69
|
+
paths.package_dir.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
files = _package_files(root)
|
|
71
|
+
tmp = paths.package_zip.with_suffix(".zip.part")
|
|
72
|
+
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as z:
|
|
73
|
+
for f in files:
|
|
74
|
+
z.write(f, f.relative_to(root).as_posix())
|
|
75
|
+
os.replace(tmp, paths.package_zip)
|
|
76
|
+
manifest = {
|
|
77
|
+
"created_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
78
|
+
"package_root": str(root),
|
|
79
|
+
"files": {f.relative_to(root).as_posix(): _sha(f) for f in files},
|
|
80
|
+
"zip_sha256": _sha(paths.package_zip),
|
|
81
|
+
"singbox": ({"path": str(paths.bundled_singbox), "sha256": _sha(paths.bundled_singbox)}
|
|
82
|
+
if paths.bundled_singbox.is_file() else None),
|
|
83
|
+
}
|
|
84
|
+
write_json(paths.manifest, manifest)
|
|
85
|
+
return manifest
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ---- 文件修复 ------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
def scan(paths: Paths) -> dict:
|
|
91
|
+
"""只扫描不修改:返回缺失和损坏的文件。"""
|
|
92
|
+
manifest = read_json(paths.manifest)
|
|
93
|
+
if not manifest:
|
|
94
|
+
return {"manifest": False, "missing": [], "damaged": [], "singbox": "unknown"}
|
|
95
|
+
root = Path(manifest["package_root"])
|
|
96
|
+
missing, damaged = [], []
|
|
97
|
+
for rel, digest in manifest["files"].items():
|
|
98
|
+
f = root / rel
|
|
99
|
+
if not f.is_file():
|
|
100
|
+
missing.append(rel)
|
|
101
|
+
elif _sha(f) != digest:
|
|
102
|
+
damaged.append(rel)
|
|
103
|
+
sb = manifest.get("singbox")
|
|
104
|
+
sb_state = "ok"
|
|
105
|
+
if sb:
|
|
106
|
+
p = Path(sb["path"])
|
|
107
|
+
sb_state = "missing" if not p.is_file() else ("ok" if _sha(p) == sb["sha256"] else "damaged")
|
|
108
|
+
return {"manifest": True, "missing": missing, "damaged": damaged, "singbox": sb_state}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def repair_files(paths: Paths, log: Logger | None = None) -> Report:
|
|
112
|
+
rep = Report("file")
|
|
113
|
+
manifest = read_json(paths.manifest)
|
|
114
|
+
if not manifest:
|
|
115
|
+
rep.problems.append("没有哈希清单(不是通过 norain install 安装的),无法判断文件是否损坏")
|
|
116
|
+
return rep
|
|
117
|
+
found = scan(paths)
|
|
118
|
+
bad = found["missing"] + found["damaged"]
|
|
119
|
+
if bad:
|
|
120
|
+
if not paths.package_zip.is_file() or _sha(paths.package_zip) != manifest.get("zip_sha256"):
|
|
121
|
+
rep.problems.append(f"{len(bad)} 个程序文件损坏或缺失,但安装包副本也已损坏,需要重新安装(pip)")
|
|
122
|
+
else:
|
|
123
|
+
root = Path(manifest["package_root"])
|
|
124
|
+
with zipfile.ZipFile(paths.package_zip) as z:
|
|
125
|
+
for rel in bad:
|
|
126
|
+
dest = root / rel
|
|
127
|
+
try:
|
|
128
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
129
|
+
tmp = dest.with_name(dest.name + ".repair")
|
|
130
|
+
tmp.write_bytes(z.read(rel))
|
|
131
|
+
os.replace(tmp, dest)
|
|
132
|
+
rep.actions.append(f"已恢复 {rel}")
|
|
133
|
+
except (OSError, KeyError) as e:
|
|
134
|
+
rep.problems.append(f"恢复 {rel} 失败:{e}")
|
|
135
|
+
if found["singbox"] != "ok" and manifest.get("singbox"):
|
|
136
|
+
try:
|
|
137
|
+
# 缓存里的压缩包会重新校验 SHA-256;缓存没有时重新下载
|
|
138
|
+
info = fetch.install_singbox(paths.bundled_singbox, paths.cache_dir, need_tags={"with_quic"})
|
|
139
|
+
rep.actions.append(f"sing-box {found['singbox']},已重新安装 {info.version}")
|
|
140
|
+
manifest["singbox"] = {"path": str(paths.bundled_singbox), "sha256": _sha(paths.bundled_singbox)}
|
|
141
|
+
write_json(paths.manifest, manifest)
|
|
142
|
+
except NorainError as e:
|
|
143
|
+
rep.problems.append(f"sing-box 无法恢复:{e.message}")
|
|
144
|
+
if not bad and found["singbox"] == "ok":
|
|
145
|
+
rep.actions.append(f"扫描了 {len(manifest['files'])} 个文件,没有发现损坏或缺失")
|
|
146
|
+
if log:
|
|
147
|
+
log.info("repair.file", **rep.as_dict())
|
|
148
|
+
return rep
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ---- 内置配置修复 --------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
def repair_builtin(paths: Paths, log: Logger | None = None) -> Report:
|
|
154
|
+
"""复位代理内部状态。可以在内控制进程运行期间调用(不删除它的进程状态文件)。"""
|
|
155
|
+
rep = Report("builtin")
|
|
156
|
+
for f, label in ((paths.current_json, "生成的 sing-box 配置"), (paths.meta_json, "配置元数据"),
|
|
157
|
+
(paths.selection, "自适应选中的协议和 DNS 覆盖"), (paths.learned, "自动学到的名单"),
|
|
158
|
+
(paths.last_error, "错误记录")):
|
|
159
|
+
if f.exists():
|
|
160
|
+
f.unlink()
|
|
161
|
+
rep.actions.append(f"已清除{label}")
|
|
162
|
+
for srs in paths.rules_dir.glob("*.srs") if paths.rules_dir.is_dir() else []:
|
|
163
|
+
try:
|
|
164
|
+
with srs.open("rb") as fh:
|
|
165
|
+
good = fh.read(3) == b"SRS"
|
|
166
|
+
except OSError:
|
|
167
|
+
good = False
|
|
168
|
+
if not good:
|
|
169
|
+
srs.unlink(missing_ok=True)
|
|
170
|
+
rep.actions.append(f"已删除损坏的规则集 {srs.name}(会自动重新下载)")
|
|
171
|
+
from . import runner
|
|
172
|
+
try:
|
|
173
|
+
prep = runner.prepare(paths, apply=True)
|
|
174
|
+
rep.actions.append(f"已从 cfg.toml 重新生成 sing-box 配置(版本 {prep.applied.version})")
|
|
175
|
+
except NorainError as e:
|
|
176
|
+
detail = ";".join(f"{fe.path} {fe.message}" for fe in e.field_errors) or e.message
|
|
177
|
+
rep.problems.append(f"重新生成配置失败:{detail}")
|
|
178
|
+
if log:
|
|
179
|
+
log.info("repair.builtin", **rep.as_dict())
|
|
180
|
+
return rep
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# ---- 完全配置修复 --------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
def repair_full(paths: Paths, log: Logger | None = None) -> Report:
|
|
186
|
+
"""调用前必须已经停止代理(命令行负责)。"""
|
|
187
|
+
from . import block, boot, install
|
|
188
|
+
from .model import load_config
|
|
189
|
+
rep = Report("full")
|
|
190
|
+
try:
|
|
191
|
+
if block.release(paths, log=log)["was_active"]:
|
|
192
|
+
rep.actions.append("已解除阻断,恢复防火墙")
|
|
193
|
+
except NorainError as e:
|
|
194
|
+
rep.problems.append(f"{e.message}({e.hint})")
|
|
195
|
+
msg = install.clear_system_proxy(paths)
|
|
196
|
+
if msg:
|
|
197
|
+
rep.actions.append(msg)
|
|
198
|
+
if paths.orig_config.is_file():
|
|
199
|
+
if not paths.config.exists() or paths.config.read_bytes() != paths.orig_config.read_bytes():
|
|
200
|
+
saved = atomic.backup(paths.config, paths.backups)
|
|
201
|
+
shutil.copy2(paths.orig_config, paths.config)
|
|
202
|
+
os.chmod(paths.config, 0o600)
|
|
203
|
+
rep.actions.append("已把 cfg.toml 恢复为安装时的初始配置"
|
|
204
|
+
+ (f"(当前配置备份在 {saved})" if saved else ""))
|
|
205
|
+
else:
|
|
206
|
+
rep.problems.append("没有保存安装时的初始配置,用户配置保持不变")
|
|
207
|
+
inner = repair_builtin(paths, log)
|
|
208
|
+
rep.actions += inner.actions
|
|
209
|
+
rep.problems += inner.problems
|
|
210
|
+
try:
|
|
211
|
+
rep.actions.append(boot.sync(paths, load_config(paths.config)))
|
|
212
|
+
except NorainError as e:
|
|
213
|
+
rep.problems.append(f"自启动项没有同步:{e.message}")
|
|
214
|
+
if log:
|
|
215
|
+
log.info("repair.full", **rep.as_dict())
|
|
216
|
+
return rep
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ---- 重载修复 ------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
def repair_reload(paths: Paths, *, start: bool = True) -> Report:
|
|
222
|
+
"""完全卸载并清除痕迹,再从安装包副本重新安装。调用前必须已经停止代理。"""
|
|
223
|
+
from . import install
|
|
224
|
+
rep = Report("reload")
|
|
225
|
+
manifest = read_json(paths.manifest)
|
|
226
|
+
if not manifest or not paths.package_zip.is_file():
|
|
227
|
+
raise NorainError("没有安装包副本,无法重载修复", exit_code=EXIT_CONFLICT, module="repair",
|
|
228
|
+
hint="重新安装 Norain(pip),然后运行 norain install")
|
|
229
|
+
if _sha(paths.package_zip) != manifest.get("zip_sha256"):
|
|
230
|
+
raise NorainError("安装包副本已损坏,无法重载修复", exit_code=EXIT_CONFLICT, module="repair",
|
|
231
|
+
hint="重新安装 Norain(pip),然后运行 norain install")
|
|
232
|
+
keep = Path(tempfile.mkdtemp(prefix="norain-reload-"))
|
|
233
|
+
try:
|
|
234
|
+
# 卸载会删除整个状态目录,先把重装需要的东西挪到临时目录
|
|
235
|
+
pkg = keep / "norain-pkg.zip"
|
|
236
|
+
shutil.copy2(paths.package_zip, pkg)
|
|
237
|
+
cfg_src = None
|
|
238
|
+
for cand in (paths.orig_config, paths.config):
|
|
239
|
+
if cand.is_file():
|
|
240
|
+
cfg_src = keep / "cfg.toml"
|
|
241
|
+
shutil.copy2(cand, cfg_src)
|
|
242
|
+
break
|
|
243
|
+
secret = paths.home / "password"
|
|
244
|
+
if secret.is_file():
|
|
245
|
+
shutil.copy2(secret, keep / "password")
|
|
246
|
+
sb = None
|
|
247
|
+
if paths.bundled_singbox.is_file():
|
|
248
|
+
try:
|
|
249
|
+
singbox.require(singbox.inspect(paths.bundled_singbox), need_tags={"with_quic"})
|
|
250
|
+
sb = keep / paths.bundled_singbox.name
|
|
251
|
+
shutil.copy2(paths.bundled_singbox, sb)
|
|
252
|
+
except NorainError:
|
|
253
|
+
sb = None # 现有二进制不可信,重装时重新下载并校验
|
|
254
|
+
|
|
255
|
+
un = install.uninstall(paths)
|
|
256
|
+
rep.actions += un["done"]
|
|
257
|
+
rep.problems += un["errors"]
|
|
258
|
+
|
|
259
|
+
root = Path(manifest["package_root"])
|
|
260
|
+
with zipfile.ZipFile(pkg) as z:
|
|
261
|
+
for rel in z.namelist():
|
|
262
|
+
dest = root / rel
|
|
263
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
264
|
+
tmp = dest.with_name(dest.name + ".repair")
|
|
265
|
+
tmp.write_bytes(z.read(rel))
|
|
266
|
+
os.replace(tmp, dest)
|
|
267
|
+
rep.actions.append(f"已从安装包副本重新解出 {len(manifest['files'])} 个程序文件")
|
|
268
|
+
|
|
269
|
+
paths.home.mkdir(parents=True, exist_ok=True)
|
|
270
|
+
if (keep / "password").is_file():
|
|
271
|
+
shutil.copy2(keep / "password", secret)
|
|
272
|
+
os.chmod(secret, 0o600)
|
|
273
|
+
res = install.install(paths, singbox_path=sb, config_src=cfg_src, force=True, start=start)
|
|
274
|
+
rep.actions += res["steps"]
|
|
275
|
+
rep.actions += [f"注意:{w}" for w in res["warnings"]]
|
|
276
|
+
finally:
|
|
277
|
+
shutil.rmtree(keep, ignore_errors=True)
|
|
278
|
+
return rep
|