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/cli.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
"""norain 命令行(外控制模块)。
|
|
2
|
+
|
|
3
|
+
配置类 config validate|show|edit|path|set|protocol|mode|server|dns
|
|
4
|
+
list <white|black|blue|monitor|monitor-cn> [show|add|remove] [条目…]
|
|
5
|
+
控制类 start | stop | restart | boot | status | logs
|
|
6
|
+
module <模块> <start|stop|restart|status>
|
|
7
|
+
repair <file|builtin|full|reload> 四种修复
|
|
8
|
+
block <status|off|on> 阻断模式(off = 手动解除)
|
|
9
|
+
once <monitor|select|route|rules-update|rules-rollback|scan> [参数] 一次性执行某个功能
|
|
10
|
+
install | uninstall
|
|
11
|
+
调试类 任何命令加 -t:执行后显示每个模块的运行情况和最近一次的返回结果
|
|
12
|
+
|
|
13
|
+
所有指令返回明确的退出码(norain_core.errors)。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import shutil
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import tempfile
|
|
25
|
+
import time
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from norain_core import apply as core_apply
|
|
29
|
+
from norain_core import atomic, cliutil, osutil, singbox, tomlio
|
|
30
|
+
from norain_core.errors import (BIZ_BINARY_MISSING, BIZ_OK, BIZ_PROCESS_EXITED, EXIT_CONFLICT,
|
|
31
|
+
EXIT_DEPENDENCY, EXIT_FAILURE, EXIT_OK, EXIT_PERMISSION,
|
|
32
|
+
EXIT_TIMEOUT, EXIT_USAGE, NorainError)
|
|
33
|
+
from norain_core.log import Logger, RotatingFile, new_op_id
|
|
34
|
+
from norain_core.state import RUNNING, STOPPED, get_desired, op_lock, read_json, set_desired
|
|
35
|
+
|
|
36
|
+
from . import block, boot, control, generate, install, maintain, model, monitor, repair, rules, runner
|
|
37
|
+
from .model import load_config, warnings_of
|
|
38
|
+
from .paths import Paths
|
|
39
|
+
|
|
40
|
+
_out, _fail = cliutil.out, cliutil.fail
|
|
41
|
+
|
|
42
|
+
LISTS = {
|
|
43
|
+
"white": ("routing.proxy_domains", "白名单(强制走代理)"),
|
|
44
|
+
"black": ("routing.direct_domains", "黑名单(强制直连)"),
|
|
45
|
+
"blue": ("routing.isolation_allowlist", "蓝名单(阻断模式下仍允许)"),
|
|
46
|
+
"monitor": ("monitor.foreign_targets", "监控测试名单(国外,走代理)"),
|
|
47
|
+
"monitor-cn": ("monitor.domestic_targets", "监控测试名单(国内,直连)"),
|
|
48
|
+
}
|
|
49
|
+
_PASSIVE_HINT = {
|
|
50
|
+
"block": "用 norain block status|off|on", "repair": "用 norain repair <级别>",
|
|
51
|
+
"boot": "用 norain boot 或 norain config mode", "control": "用 norain start|stop|restart",
|
|
52
|
+
"cli": "它就是你正在用的命令行",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _logger(paths: Paths, module: str = "cli") -> Logger:
|
|
57
|
+
return Logger(module, sink=RotatingFile(paths.log_file, max_bytes=20 << 20, keep=5), stderr=False)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _running(paths: Paths) -> bool:
|
|
61
|
+
return bool(runner.backend(paths).status().state == "running")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---- 配置类 --------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
def cmd_config_validate(args, paths: Paths) -> int:
|
|
67
|
+
prep = runner.prepare(paths, apply=False)
|
|
68
|
+
data = generate.render(prep.cfg, prep.secret, prep.paths)
|
|
69
|
+
core_apply.check_only(data, prep.paths.run_dir, prep.binary.path)
|
|
70
|
+
warns = warnings_of(prep.cfg)
|
|
71
|
+
_out(args, {"config": str(paths.config), "config_version": generate.version_of(data),
|
|
72
|
+
"singbox_version": prep.binary.version, "warnings": warns},
|
|
73
|
+
"配置有效(已通过 sing-box check)" + "".join(f"\n警告:{w}" for w in warns))
|
|
74
|
+
return EXIT_OK
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def cmd_config_show(args, paths: Paths) -> int:
|
|
78
|
+
cfg = load_config(paths.config)
|
|
79
|
+
doc = cfg.model_dump(by_alias=True)
|
|
80
|
+
doc["proxy"]["password"] = "***" if cfg.proxy.password else ""
|
|
81
|
+
try:
|
|
82
|
+
s = generate.resolve_secret(cfg)
|
|
83
|
+
doc["proxy"]["resolved"] = {"source": s.source, "fingerprint": s.fingerprint}
|
|
84
|
+
except NorainError as e:
|
|
85
|
+
doc["proxy"]["resolved"] = {"error": "; ".join(f.message for f in e.field_errors) or e.message}
|
|
86
|
+
if args.json:
|
|
87
|
+
_out(args, {"config": doc}, "")
|
|
88
|
+
else:
|
|
89
|
+
print(json.dumps(doc, ensure_ascii=False, indent=2))
|
|
90
|
+
return EXIT_OK
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cmd_config_path(args, paths: Paths) -> int:
|
|
94
|
+
_out(args, {"config": str(paths.config), "state": str(paths.state), "log": str(paths.log_dir)},
|
|
95
|
+
f"配置:{paths.config}\n状态:{paths.state}\n日志:{paths.log_dir}")
|
|
96
|
+
return EXIT_OK
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _apply_running(paths: Paths) -> str:
|
|
100
|
+
"""配置改过之后,通知正在运行的内控制模块重新加载。"""
|
|
101
|
+
if not control.read_status(paths):
|
|
102
|
+
return "代理没有运行,下次启动时生效。"
|
|
103
|
+
resp = control.send(paths, {"op": "reload"}, timeout=90)
|
|
104
|
+
return ("已通知正在运行的代理:" + resp.get("message", "")) if resp.get("ok") else (
|
|
105
|
+
"正在运行的代理没有接受新配置:" + resp.get("message", ""))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _save_config(paths: Paths, doc: dict) -> tuple[model.ClientConfig, Path | None, bool]:
|
|
109
|
+
"""迁移并校验通过才写盘;写之前备份。TOML 注释不会保留。
|
|
110
|
+
|
|
111
|
+
写盘写的是迁移后的数据:既然整个文件都要重写,顺手把 ``schema`` 补上,
|
|
112
|
+
否则「缺少顶层 schema」的 warning 每次加载都会再出现一遍。
|
|
113
|
+
"""
|
|
114
|
+
migration = model.migrate_doc(doc, source=str(paths.config))
|
|
115
|
+
cfg = model.parse(migration.data, source=str(paths.config))
|
|
116
|
+
saved = atomic.backup(paths.config, paths.backups) if paths.config.exists() else None
|
|
117
|
+
atomic.atomic_write(paths.config, tomlio.dumps(migration.data).encode("utf-8"))
|
|
118
|
+
return cfg, saved, bool(migration.warnings)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _mutate(args, paths: Paths, changes: dict, text: str) -> int:
|
|
122
|
+
doc = model.read_raw(paths.config)
|
|
123
|
+
for key, value in changes.items():
|
|
124
|
+
try:
|
|
125
|
+
tomlio.set_path(doc, key, value)
|
|
126
|
+
except KeyError:
|
|
127
|
+
raise NorainError(f"{key} 不是可以设置的配置项", exit_code=EXIT_USAGE, module="config") from None
|
|
128
|
+
cfg, saved, added_schema = _save_config(paths, doc)
|
|
129
|
+
notes = [_apply_running(paths)]
|
|
130
|
+
if added_schema:
|
|
131
|
+
notes.append(f"配置里原来没有顶层 schema,已按版本 {model.SCHEMA_VERSION} 写入")
|
|
132
|
+
if any(k.startswith("app.") or k == "proxy.traffic_mode" for k in changes):
|
|
133
|
+
try:
|
|
134
|
+
notes.append(boot.sync(paths, cfg)) # 正常模式 / 安全模式决定是否开机自启动
|
|
135
|
+
except NorainError as e:
|
|
136
|
+
notes.append(f"自启动项没有同步:{e.message}" + (f"({e.hint})" if e.hint else ""))
|
|
137
|
+
_out(args, {"changed": changes, "backup": str(saved) if saved else None, "notes": notes},
|
|
138
|
+
text + "\n" + "\n".join(notes))
|
|
139
|
+
return EXIT_OK
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def cmd_config_set(args, paths: Paths) -> int:
|
|
143
|
+
value = tomlio.parse_value(args.value)
|
|
144
|
+
return _mutate(args, paths, {args.key: value}, f"已设置 {args.key} = {value!r}")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cmd_config_protocol(args, paths: Paths) -> int:
|
|
148
|
+
return _mutate(args, paths, {"proxy.protocol": args.protocol},
|
|
149
|
+
f"协议已设为 {args.protocol}" + ("(按测速和连通性自适应)" if args.protocol == "auto" else ""))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cmd_config_mode(args, paths: Paths) -> int:
|
|
153
|
+
return _mutate(args, paths, {"app.mode": args.mode},
|
|
154
|
+
"已设为正常模式(开机自启动)" if args.mode == "normal" else "已设为安全模式(不开机自启动,只手动启动)")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def cmd_config_server(args, paths: Paths) -> int:
|
|
158
|
+
changes: dict = {"proxy.server": args.host}
|
|
159
|
+
if args.hy2_port:
|
|
160
|
+
changes["proxy.hysteria2.port"] = args.hy2_port
|
|
161
|
+
if args.trojan_port:
|
|
162
|
+
changes["proxy.trojan.port"] = args.trojan_port
|
|
163
|
+
if args.credential_ref:
|
|
164
|
+
changes["proxy.credential_ref"] = args.credential_ref
|
|
165
|
+
return _mutate(args, paths, changes, f"代理服务器已设为 {args.host}")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def cmd_config_dns(args, paths: Paths) -> int:
|
|
169
|
+
changes = {f"dns.{k}": v for k, v in (("mode", args.mode), ("domestic", args.domestic),
|
|
170
|
+
("proxy", args.proxy), ("strategy", args.strategy)) if v}
|
|
171
|
+
if not changes:
|
|
172
|
+
cfg = load_config(paths.config)
|
|
173
|
+
_out(args, {"dns": cfg.dns.model_dump()}, json.dumps(cfg.dns.model_dump(), ensure_ascii=False, indent=2))
|
|
174
|
+
return EXIT_OK
|
|
175
|
+
return _mutate(args, paths, changes, "DNS 配置已更新")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cmd_config_edit(args, paths: Paths) -> int:
|
|
179
|
+
"""在编辑器里修改 cfg.toml。保存后先校验,通过才替换原文件。"""
|
|
180
|
+
editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or (
|
|
181
|
+
"notepad" if osutil.IS_WINDOWS else shutil.which("nano") or shutil.which("vi"))
|
|
182
|
+
if not editor:
|
|
183
|
+
raise NorainError("找不到编辑器", exit_code=EXIT_DEPENDENCY, module="config",
|
|
184
|
+
hint=f"设置 EDITOR 环境变量,或直接编辑 {paths.config}")
|
|
185
|
+
model.read_raw(paths.config) # 文件不存在时给出统一的错误
|
|
186
|
+
fd, tmp_name = tempfile.mkstemp(prefix="cfg-", suffix=".toml", dir=str(paths.config.parent))
|
|
187
|
+
tmp = Path(tmp_name)
|
|
188
|
+
try:
|
|
189
|
+
with os.fdopen(fd, "wb") as f:
|
|
190
|
+
f.write(paths.config.read_bytes())
|
|
191
|
+
os.chmod(tmp, 0o600)
|
|
192
|
+
before = tmp.read_bytes()
|
|
193
|
+
subprocess.run([*editor.split(), str(tmp)], check=False)
|
|
194
|
+
if tmp.read_bytes() == before:
|
|
195
|
+
_out(args, {"changed": False}, "没有修改")
|
|
196
|
+
return EXIT_OK
|
|
197
|
+
try:
|
|
198
|
+
cfg = load_config(tmp)
|
|
199
|
+
except NorainError as e:
|
|
200
|
+
keep = paths.config.with_name(paths.config.name + ".rejected")
|
|
201
|
+
os.replace(tmp, keep)
|
|
202
|
+
e.hint = f"原配置没有被改动。你的修改保存在 {keep}"
|
|
203
|
+
raise
|
|
204
|
+
saved = atomic.backup(paths.config, paths.backups)
|
|
205
|
+
os.replace(tmp, paths.config)
|
|
206
|
+
finally:
|
|
207
|
+
tmp.unlink(missing_ok=True)
|
|
208
|
+
notes = [_apply_running(paths)]
|
|
209
|
+
try:
|
|
210
|
+
notes.append(boot.sync(paths, cfg))
|
|
211
|
+
except NorainError as e:
|
|
212
|
+
notes.append(f"自启动项没有同步:{e.message}")
|
|
213
|
+
_out(args, {"changed": True, "backup": str(saved) if saved else None, "notes": notes},
|
|
214
|
+
f"配置已保存(旧配置备份在 {saved})。\n" + "\n".join(notes))
|
|
215
|
+
return EXIT_OK
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def cmd_list(args, paths: Paths) -> int:
|
|
219
|
+
key, label = LISTS[args.name]
|
|
220
|
+
doc = model.read_raw(paths.config)
|
|
221
|
+
cfg = model.parse(doc) # 没写在文件里的名单取默认值
|
|
222
|
+
section, field = key.split(".")
|
|
223
|
+
current = list(getattr(getattr(cfg, section), field))
|
|
224
|
+
if args.action == "show":
|
|
225
|
+
_out(args, {"list": args.name, "field": key, "entries": current},
|
|
226
|
+
f"{label} [{key}]\n" + ("\n".join(f" {e}" for e in current) or " (空)"))
|
|
227
|
+
return EXIT_OK
|
|
228
|
+
if not args.entries:
|
|
229
|
+
raise NorainError("没有给出条目", exit_code=EXIT_USAGE, module="config",
|
|
230
|
+
hint=f"例如:norain list {args.name} {args.action} example.com")
|
|
231
|
+
if args.action == "add":
|
|
232
|
+
new = current + [e for e in args.entries if e not in current]
|
|
233
|
+
else:
|
|
234
|
+
missing = [e for e in args.entries if e not in current]
|
|
235
|
+
if missing:
|
|
236
|
+
raise NorainError("名单里没有:" + "、".join(missing), exit_code=EXIT_USAGE, module="config")
|
|
237
|
+
new = [e for e in current if e not in args.entries]
|
|
238
|
+
return _mutate(args, paths, {key: new},
|
|
239
|
+
f"{label}:{'已加入' if args.action == 'add' else '已移除'} {'、'.join(args.entries)}")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ---- 控制类:生命周期 ----------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
def _local_proxy_hint(cfg) -> str:
|
|
245
|
+
host = f"[{cfg.local.listen}]" if ":" in cfg.local.listen else cfg.local.listen
|
|
246
|
+
if cfg.proxy.traffic_mode == "tun":
|
|
247
|
+
return f"全局接管(TUN)已启用。本地代理:{host}:{cfg.local.port}(HTTP 和 SOCKS5 共用)。"
|
|
248
|
+
if cfg.proxy.traffic_mode == "system-proxy":
|
|
249
|
+
return f"已设置系统代理。本地代理:{host}:{cfg.local.port}。只有遵守系统代理的程序才走代理。"
|
|
250
|
+
return (f"本地代理:{host}:{cfg.local.port}(HTTP 和 SOCKS5 共用)。\n"
|
|
251
|
+
"只有设置了这个代理的程序才会走代理;系统其他流量不受影响。")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _preflight(prep) -> None:
|
|
255
|
+
if prep.cfg.proxy.traffic_mode == "tun" and not osutil.is_admin():
|
|
256
|
+
raise NorainError("TUN 模式需要管理员权限", exit_code=EXIT_PERMISSION, module="control",
|
|
257
|
+
hint="用管理员 / root 运行,或运行 norain config set proxy.traffic_mode mixed")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _start(paths: Paths, op_id: str):
|
|
261
|
+
prep = runner.prepare(paths, apply=False) # 先在前台报出配置问题
|
|
262
|
+
_preflight(prep)
|
|
263
|
+
set_desired(paths.desired, RUNNING, op_id=op_id)
|
|
264
|
+
try:
|
|
265
|
+
runner.backend(prep.paths).start(timeout=45)
|
|
266
|
+
except NorainError as e:
|
|
267
|
+
# 只有「启动超时」才回滚期望状态:守护进程已经被停掉,留着 running 会被保活方
|
|
268
|
+
# 反复拉起;其它失败(配置错、进程崩溃)保留 running 让 status 报出原因。
|
|
269
|
+
if e.exit_code == EXIT_TIMEOUT:
|
|
270
|
+
set_desired(paths.desired, STOPPED, op_id=op_id)
|
|
271
|
+
raise
|
|
272
|
+
return prep
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _stop(paths: Paths, op_id: str) -> None:
|
|
276
|
+
set_desired(paths.desired, STOPPED, op_id=op_id) # 先写期望状态,保证任何保活方都不会再拉起
|
|
277
|
+
runner.backend(paths).stop(timeout=40)
|
|
278
|
+
maintain.kill_watchdog(paths)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def cmd_start(args, paths: Paths) -> int:
|
|
282
|
+
op_id = new_op_id()
|
|
283
|
+
was_blocked = block.is_active(paths)
|
|
284
|
+
with op_lock(paths.lock, op="start", op_id=op_id):
|
|
285
|
+
prep = _start(paths, op_id)
|
|
286
|
+
_out(args, {"state": "running", "op_id": op_id, "block_released": was_blocked,
|
|
287
|
+
"local_proxy": {"listen": prep.cfg.local.listen, "port": prep.cfg.local.port}},
|
|
288
|
+
"已启动" + ("(已自动解除阻断模式)" if was_blocked else "") + "\n" + _local_proxy_hint(prep.cfg)
|
|
289
|
+
+ "\n启动测试(监控)在后台进行,运行 norain status 查看结果。")
|
|
290
|
+
return EXIT_OK
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def cmd_boot(args, paths: Paths) -> int:
|
|
294
|
+
"""启动模块的入口:开机自启动项运行的就是 `norain boot --autostart`。"""
|
|
295
|
+
if args.autostart and get_desired(paths.desired) != RUNNING:
|
|
296
|
+
_out(args, {"state": "skipped"}, "期望状态是 stopped(用户手动停止过),不启动")
|
|
297
|
+
return EXIT_OK
|
|
298
|
+
return cmd_start(args, paths)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def cmd_stop(args, paths: Paths) -> int:
|
|
302
|
+
op_id = new_op_id()
|
|
303
|
+
with op_lock(paths.lock, op="stop", op_id=op_id):
|
|
304
|
+
_stop(paths, op_id)
|
|
305
|
+
_out(args, {"state": "stopped", "op_id": op_id}, "已停止")
|
|
306
|
+
return EXIT_OK
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def cmd_restart(args, paths: Paths) -> int:
|
|
310
|
+
op_id = new_op_id()
|
|
311
|
+
with op_lock(paths.lock, op="restart", op_id=op_id):
|
|
312
|
+
prep = runner.prepare(paths, apply=False) # 新配置无效时不动正在运行的代理
|
|
313
|
+
_preflight(prep)
|
|
314
|
+
runner.backend(prep.paths).stop(timeout=40)
|
|
315
|
+
maintain.kill_watchdog(paths)
|
|
316
|
+
prep = _start(paths, op_id)
|
|
317
|
+
_out(args, {"state": "running", "op_id": op_id}, "已重启\n" + _local_proxy_hint(prep.cfg))
|
|
318
|
+
return EXIT_OK
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def cmd_run(args, paths: Paths) -> int:
|
|
322
|
+
return runner.run_foreground(paths, autostart=args.autostart)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def cmd_watchdog(args, paths: Paths) -> int:
|
|
326
|
+
return maintain.watchdog_main(paths)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ---- 控制类:状态 --------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
def build_status(paths: Paths) -> dict:
|
|
332
|
+
st: dict = {"updated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
|
333
|
+
"desired": get_desired(paths.desired)}
|
|
334
|
+
business = BIZ_OK
|
|
335
|
+
try:
|
|
336
|
+
cfg = load_config(paths.config)
|
|
337
|
+
paths = paths.with_log_dir(cfg.logging.directory)
|
|
338
|
+
st["config"] = {"valid": True}
|
|
339
|
+
st["proxy"] = {"protocol": cfg.proxy.protocol, "server": cfg.proxy.server,
|
|
340
|
+
"port": cfg.proxy.port, "traffic_mode": cfg.proxy.traffic_mode}
|
|
341
|
+
st["local_proxy"] = {"listen": cfg.local.listen, "port": cfg.local.port}
|
|
342
|
+
st["app"] = {"mode": cfg.app.mode, "auto_start": cfg.app.auto_start}
|
|
343
|
+
st["warnings"] = warnings_of(cfg)
|
|
344
|
+
except NorainError as e:
|
|
345
|
+
business = e.business_code
|
|
346
|
+
st["config"] = {"valid": False, "errors": [f.as_dict() for f in e.field_errors] or e.message}
|
|
347
|
+
try:
|
|
348
|
+
info = runner.locate_singbox(paths)
|
|
349
|
+
st["singbox"] = {"path": str(info.path), "version": info.version,
|
|
350
|
+
"pinned": singbox.PINNED_VERSION,
|
|
351
|
+
"version_ok": info.version == singbox.PINNED_VERSION}
|
|
352
|
+
except NorainError as e:
|
|
353
|
+
st["singbox"] = {"error": e.message}
|
|
354
|
+
business = business or BIZ_BINARY_MISSING
|
|
355
|
+
|
|
356
|
+
svc = runner.backend(paths).status()
|
|
357
|
+
st["service"] = {"state": svc.state, "pid": svc.pid}
|
|
358
|
+
st["process"] = {"running": bool(svc.child_pid), "pid": svc.child_pid}
|
|
359
|
+
st["restarts"] = svc.restarts
|
|
360
|
+
meta = read_json(paths.meta_json) or {}
|
|
361
|
+
st["config"]["version"] = meta.get("config_version")
|
|
362
|
+
st["config"]["generated_at"] = meta.get("generated_at")
|
|
363
|
+
last = read_json(paths.last_error)
|
|
364
|
+
st["last_error"] = last
|
|
365
|
+
st["block"] = block.status(paths)
|
|
366
|
+
|
|
367
|
+
live = control.read_status(paths) or {}
|
|
368
|
+
st["phase"] = live.get("phase")
|
|
369
|
+
st["modules"] = live.get("modules")
|
|
370
|
+
st["monitor"] = live.get("monitor")
|
|
371
|
+
st["rules"] = live.get("rules")
|
|
372
|
+
if live.get("protocol"):
|
|
373
|
+
st.setdefault("proxy", {})["active_protocol"] = live["protocol"]["active"]
|
|
374
|
+
|
|
375
|
+
if st["desired"] == RUNNING and svc.state != "running":
|
|
376
|
+
business = (last or {}).get("business_code") or business or BIZ_PROCESS_EXITED
|
|
377
|
+
elif svc.state == "running":
|
|
378
|
+
business = BIZ_OK if st["process"]["running"] else BIZ_PROCESS_EXITED
|
|
379
|
+
# 进程正常时,业务码取监控模块的结论(链路是否真的连通)
|
|
380
|
+
if business == BIZ_OK and st["monitor"]:
|
|
381
|
+
business = st["monitor"]["code"]
|
|
382
|
+
st["business_code"] = business
|
|
383
|
+
st["link_check"] = (st["monitor"] or {}).get("meaning") or (
|
|
384
|
+
"监控还没有结论" if svc.state == "running" else "代理没有运行")
|
|
385
|
+
return st
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def cmd_status(args, paths: Paths) -> int:
|
|
389
|
+
st = build_status(paths)
|
|
390
|
+
if args.json:
|
|
391
|
+
print(json.dumps(st, ensure_ascii=False, indent=2))
|
|
392
|
+
return EXIT_OK
|
|
393
|
+
state = {"running": "运行中", "stopped": "已停止", "failed": "失败"}[st["service"]["state"]]
|
|
394
|
+
print(f"状态:{state}(期望:{'运行' if st['desired'] == RUNNING else '停止'}"
|
|
395
|
+
+ (f",阶段:{st['phase']}" if st.get("phase") else "") + ")")
|
|
396
|
+
if st["config"]["valid"]:
|
|
397
|
+
p, local = st["proxy"], st["local_proxy"]
|
|
398
|
+
active = p.get("active_protocol")
|
|
399
|
+
proto = p["protocol"] + (f" → 当前 {active}" if active and p["protocol"] == "auto" else "")
|
|
400
|
+
print(f"服务器:{p['server']}({proto}),接管方式:{p['traffic_mode']}")
|
|
401
|
+
print(f"本地代理:{local['listen']}:{local['port']}")
|
|
402
|
+
print(f"启动模式:{'正常模式' if st['app']['mode'] == 'normal' else '安全模式'}")
|
|
403
|
+
else:
|
|
404
|
+
print("配置无效,运行 norain config validate 查看详情")
|
|
405
|
+
if st["block"]["active"]:
|
|
406
|
+
print(f"阻断模式:已启用(错误码 {st['block']['code']},{st['block']['engaged_at']})。"
|
|
407
|
+
"解除:norain block off")
|
|
408
|
+
if st.get("monitor"):
|
|
409
|
+
print(f"链路检测:错误码 {st['monitor']['code']}({st['monitor']['meaning']})")
|
|
410
|
+
else:
|
|
411
|
+
print(f"链路检测:{st['link_check']}")
|
|
412
|
+
print(f"sing-box 重启次数:{st['restarts']}")
|
|
413
|
+
if st["business_code"]:
|
|
414
|
+
print(f"业务码:{st['business_code']}")
|
|
415
|
+
if st["last_error"]:
|
|
416
|
+
print(f"最近错误:{st['last_error']['message']}({st['last_error']['time']})")
|
|
417
|
+
for w in st.get("warnings", []):
|
|
418
|
+
print(f"警告:{w}")
|
|
419
|
+
return EXIT_OK
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def cmd_logs(args, paths: Paths) -> int:
|
|
423
|
+
try:
|
|
424
|
+
paths = paths.with_log_dir(load_config(paths.config).logging.directory)
|
|
425
|
+
except NorainError:
|
|
426
|
+
pass
|
|
427
|
+
return cliutil.tail(paths.log_file, lines=args.lines, follow=args.follow)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _short(value, limit: int = 160) -> str:
|
|
431
|
+
if value in (None, [], {}):
|
|
432
|
+
return "-"
|
|
433
|
+
text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
|
|
434
|
+
return text if len(text) <= limit else text[:limit] + "…"
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def print_trace(paths: Paths) -> None:
|
|
438
|
+
"""-t:每个模块的运行情况和最近一次的返回结果。"""
|
|
439
|
+
live = control.read_status(paths)
|
|
440
|
+
print("\n── 模块运行情况 " + "─" * 40, file=sys.stderr)
|
|
441
|
+
if not live:
|
|
442
|
+
blk = block.status(paths)
|
|
443
|
+
print("内控制模块没有运行,其余模块随之停止。", file=sys.stderr)
|
|
444
|
+
print(f" block {'blocking' if blk['active'] else 'idle':<10} {_short(blk if blk['active'] else None)}",
|
|
445
|
+
file=sys.stderr)
|
|
446
|
+
print(f" watchdog {'running' if maintain.watchdog_alive(paths) else 'stopped'}", file=sys.stderr)
|
|
447
|
+
last = read_json(paths.last_error)
|
|
448
|
+
if last:
|
|
449
|
+
print(f" 最近错误:{_short(last)}", file=sys.stderr)
|
|
450
|
+
return
|
|
451
|
+
print(f"阶段:{live['phase']} 协议:{live['protocol']['active']} "
|
|
452
|
+
f"监控错误码:{live['monitor']['code']}({live['monitor']['meaning']})", file=sys.stderr)
|
|
453
|
+
for name in control.MODULES:
|
|
454
|
+
m = (live.get("modules") or {}).get(name)
|
|
455
|
+
if not m:
|
|
456
|
+
continue
|
|
457
|
+
extra = {k: v for k, v in m.items() if k not in ("state", "last_result")}
|
|
458
|
+
print(f" {name:<8} {m.get('state', '?'):<10} {_short(extra, 90)}", file=sys.stderr)
|
|
459
|
+
print(f" {'':<8} 返回结果:{_short(m.get('last_result'), 400)}", file=sys.stderr)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
# ---- 控制类:模块 --------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
def cmd_module(args, paths: Paths) -> int:
|
|
465
|
+
name = args.name
|
|
466
|
+
if args.action == "status":
|
|
467
|
+
live = control.read_status(paths)
|
|
468
|
+
mod = ((live or {}).get("modules") or {}).get(name)
|
|
469
|
+
if mod is None:
|
|
470
|
+
mod = {"state": "stopped", "note": "内控制模块没有运行"}
|
|
471
|
+
if name == "block":
|
|
472
|
+
mod = {"state": "blocking" if block.is_active(paths) else "idle", "last_result": block.status(paths)}
|
|
473
|
+
_out(args, {"module": name, **mod}, f"{name}:{mod.get('state')}\n"
|
|
474
|
+
+ json.dumps({k: v for k, v in mod.items() if k != "state"}, ensure_ascii=False, indent=2))
|
|
475
|
+
return EXIT_OK
|
|
476
|
+
if name in _PASSIVE_HINT:
|
|
477
|
+
raise NorainError(f"{name} 模块不能单独{args.action}", exit_code=EXIT_USAGE, module="control",
|
|
478
|
+
hint=_PASSIVE_HINT[name])
|
|
479
|
+
resp = control.send(paths, {"op": "module", "name": name, "action": args.action}, timeout=90)
|
|
480
|
+
if not resp.get("ok"):
|
|
481
|
+
raise NorainError(f"{name} {args.action} 没有执行:{resp.get('message')}", exit_code=EXIT_CONFLICT,
|
|
482
|
+
module="control", retryable=True)
|
|
483
|
+
_out(args, {"module": name, "action": args.action, **resp},
|
|
484
|
+
f"{name}:{resp.get('message')}(当前 {resp.get('module', {}).get('state')})")
|
|
485
|
+
return EXIT_OK
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# ---- 控制类:修复 --------------------------------------------------------------
|
|
489
|
+
|
|
490
|
+
def cmd_repair(args, paths: Paths) -> int:
|
|
491
|
+
op_id = new_op_id()
|
|
492
|
+
level = args.level
|
|
493
|
+
log = _logger(paths, "repair")
|
|
494
|
+
with op_lock(paths.lock, op=f"repair-{level}", op_id=op_id, timeout=900):
|
|
495
|
+
was_running = get_desired(paths.desired) == RUNNING
|
|
496
|
+
if level == "file":
|
|
497
|
+
rep = repair.repair_files(paths, log)
|
|
498
|
+
elif level == "builtin":
|
|
499
|
+
rep = repair.repair_builtin(paths, log)
|
|
500
|
+
if control.read_status(paths): # 让正在运行的代理加载复位后的配置
|
|
501
|
+
control.send(paths, {"op": "reload"}, timeout=90)
|
|
502
|
+
else:
|
|
503
|
+
_stop(paths, op_id) # 这两级会动用户配置和系统配置,必须先停下来
|
|
504
|
+
if level == "full":
|
|
505
|
+
rep = repair.repair_full(paths, log)
|
|
506
|
+
if was_running and rep.ok:
|
|
507
|
+
_start(paths, op_id)
|
|
508
|
+
rep.actions.append("已重新启动")
|
|
509
|
+
else:
|
|
510
|
+
rep = repair.repair_reload(paths, start=was_running)
|
|
511
|
+
text = "\n".join(f"· {a}" for a in rep.actions) + "".join(f"\n未修好:{p}" for p in rep.problems)
|
|
512
|
+
_out(args, {**rep.as_dict(), "op_id": op_id}, text)
|
|
513
|
+
return EXIT_OK if rep.ok else EXIT_FAILURE
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# ---- 控制类:阻断 --------------------------------------------------------------
|
|
517
|
+
|
|
518
|
+
def cmd_block(args, paths: Paths) -> int:
|
|
519
|
+
if args.action == "status":
|
|
520
|
+
st = block.status(paths)
|
|
521
|
+
text = "阻断模式:" + ("已启用" if st["active"] else "未启用")
|
|
522
|
+
if st["active"]:
|
|
523
|
+
text += (f"\n错误码:{st['code']} 原因:{st['reason']}\n进入时间:{st['engaged_at']}\n"
|
|
524
|
+
+ "可能原因:\n" + "".join(f" · {g}\n" for g in st["guesses"])
|
|
525
|
+
+ f"解除:{st['restore_command']}\n不依赖 Norain 的手工恢复:{st['manual_restore']}")
|
|
526
|
+
_out(args, st, text)
|
|
527
|
+
return EXIT_OK
|
|
528
|
+
if args.action == "off":
|
|
529
|
+
res = block.release(paths, log=_logger(paths, "block"))
|
|
530
|
+
_out(args, res, ("已解除阻断,防火墙恢复正常放行。" if res["was_active"] else "当前不在阻断模式。")
|
|
531
|
+
+ "\n注意:这不代表代理已修复,此时代理不一定在运行;流量会直连。启动代理:norain start")
|
|
532
|
+
return EXIT_OK
|
|
533
|
+
# on:手动进入阻断(同自动触发时一样,结束其他所有模块)
|
|
534
|
+
cfg = load_config(paths.config)
|
|
535
|
+
op_id = new_op_id()
|
|
536
|
+
with op_lock(paths.lock, op="block", op_id=op_id):
|
|
537
|
+
st = block.engage(cfg, paths, code=0, reason="用户手动进入阻断模式", log=_logger(paths, "block"),
|
|
538
|
+
notify=False)
|
|
539
|
+
_stop(paths, op_id)
|
|
540
|
+
_out(args, {"active": True, "allowed": st["allowed"], "unresolved": st["unresolved"]},
|
|
541
|
+
"已进入阻断模式,其他模块已停止。解除:norain block off"
|
|
542
|
+
+ ("\n没能解析(因此没有放行):" + "、".join(st["unresolved"]) if st["unresolved"] else ""))
|
|
543
|
+
return EXIT_OK
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ---- 控制类:一次性执行某个模块的某个功能 --------------------------------------
|
|
547
|
+
|
|
548
|
+
def cmd_once(args, paths: Paths) -> int:
|
|
549
|
+
what, live = args.what, control.read_status(paths)
|
|
550
|
+
if what == "monitor":
|
|
551
|
+
if live:
|
|
552
|
+
resp = control.send(paths, {"op": "monitor"}, timeout=120)
|
|
553
|
+
_out(args, resp, resp.get("text", ""))
|
|
554
|
+
return EXIT_OK
|
|
555
|
+
cfg = load_config(paths.config)
|
|
556
|
+
try:
|
|
557
|
+
geo = rules.Geo(runner.locate_singbox(paths).path, paths)
|
|
558
|
+
except NorainError:
|
|
559
|
+
geo = None
|
|
560
|
+
rnd = monitor.run_round(cfg, monitor.Ports(), geo)
|
|
561
|
+
_out(args, {"result": rnd.as_dict(), "standalone": True},
|
|
562
|
+
"(代理没有运行:只检测直连,走代理的项目一律为无返回)\n" + monitor.report_text(rnd))
|
|
563
|
+
return EXIT_OK
|
|
564
|
+
if what == "scan":
|
|
565
|
+
res = repair.scan(paths)
|
|
566
|
+
_out(args, res, f"缺失 {len(res['missing'])} 个,损坏 {len(res['damaged'])} 个,sing-box:{res['singbox']}"
|
|
567
|
+
+ "".join(f"\n 缺失 {f}" for f in res["missing"]) + "".join(f"\n 损坏 {f}" for f in res["damaged"])
|
|
568
|
+
+ ("" if res["manifest"] else "\n没有哈希清单(不是通过 norain install 安装的)"))
|
|
569
|
+
return EXIT_OK
|
|
570
|
+
if what == "rules-update":
|
|
571
|
+
if live:
|
|
572
|
+
resp = control.send(paths, {"op": "rules-update"}, timeout=180)
|
|
573
|
+
rep = resp.get("result") or {}
|
|
574
|
+
else:
|
|
575
|
+
rep = rules.update(load_config(paths.config), paths)
|
|
576
|
+
_out(args, rep, f"已更新:{'、'.join(rep.get('updated', [])) or '无'};未变化:"
|
|
577
|
+
f"{'、'.join(rep.get('unchanged', [])) or '无'}"
|
|
578
|
+
+ "".join(f"\n失败 {k}:{v}" for k, v in (rep.get("failed") or {}).items()))
|
|
579
|
+
return EXIT_FAILURE if rep.get("failed") else EXIT_OK
|
|
580
|
+
if what == "rules-rollback":
|
|
581
|
+
if not args.arg:
|
|
582
|
+
raise NorainError("需要规则集名称", exit_code=EXIT_USAGE, module="routing",
|
|
583
|
+
hint="例如:norain once rules-rollback geoip-cn")
|
|
584
|
+
if not rules.rollback(paths, args.arg):
|
|
585
|
+
raise NorainError(f"{args.arg} 没有可回滚的上一版本", exit_code=EXIT_CONFLICT, module="routing")
|
|
586
|
+
note = _apply_running(paths)
|
|
587
|
+
_out(args, {"rolled_back": args.arg}, f"{args.arg} 已回滚到上一版本。\n{note}")
|
|
588
|
+
return EXIT_OK
|
|
589
|
+
# 以下两个功能需要代理在运行(要用它的本地探测入口)
|
|
590
|
+
if not live:
|
|
591
|
+
raise NorainError("这个功能需要代理在运行", exit_code=EXIT_CONFLICT, module="control",
|
|
592
|
+
hint="先运行 norain start")
|
|
593
|
+
if what == "select":
|
|
594
|
+
resp = control.send(paths, {"op": "select"}, timeout=120)
|
|
595
|
+
if not resp.get("ok"):
|
|
596
|
+
raise NorainError(resp.get("message", "没有执行"), exit_code=EXIT_CONFLICT, module="control")
|
|
597
|
+
_out(args, resp, f"当前协议:{resp['active']}({'已切换' if resp['switched'] else '未切换'}:{resp['reason']})\n"
|
|
598
|
+
+ json.dumps(resp["result"], ensure_ascii=False, indent=2))
|
|
599
|
+
return EXIT_OK
|
|
600
|
+
if not args.arg:
|
|
601
|
+
raise NorainError("需要域名", exit_code=EXIT_USAGE, module="routing",
|
|
602
|
+
hint="例如:norain once route example.com")
|
|
603
|
+
resp = control.send(paths, {"op": "route", "domain": args.arg}, timeout=180)
|
|
604
|
+
v = resp.get("result") or {}
|
|
605
|
+
_out(args, resp, f"{v.get('domain')}:{v.get('decision')}"
|
|
606
|
+
+ ("(已更新名单,稍后自动重载)" if v.get("changed") else "")
|
|
607
|
+
+ "".join(f"\n {s}" for s in v.get("steps", [])))
|
|
608
|
+
return EXIT_OK
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
# ---- 控制类:安装与卸载 --------------------------------------------------------
|
|
612
|
+
|
|
613
|
+
def cmd_install(args, paths: Paths) -> int:
|
|
614
|
+
res = install.install(
|
|
615
|
+
paths, archive=Path(args.singbox_archive) if args.singbox_archive else None,
|
|
616
|
+
sha256=args.singbox_sha256, singbox_path=Path(args.singbox_path) if args.singbox_path else None,
|
|
617
|
+
config_src=Path(args.config) if args.config else None, server=args.server or "",
|
|
618
|
+
traffic_mode=args.traffic_mode, protocol=args.protocol, force=args.force, start=not args.no_start)
|
|
619
|
+
_out(args, res, "\n".join(f"· {s}" for s in res["steps"]) + "".join(f"\n注意:{w}" for w in res["warnings"])
|
|
620
|
+
+ f"\n\n配置文件:{res['config']}\n`norain` 命令和环境变量在新开的终端里生效。")
|
|
621
|
+
if not args.no_start and not res.get("started"):
|
|
622
|
+
return EXIT_FAILURE # 装完没起来不能报成功,否则脚本会把失败当成功
|
|
623
|
+
return EXIT_OK
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def cmd_uninstall(args, paths: Paths) -> int:
|
|
627
|
+
if not args.yes:
|
|
628
|
+
if not sys.stdin.isatty():
|
|
629
|
+
raise NorainError("卸载会删除全部配置和数据,需要确认", exit_code=EXIT_USAGE, module="install",
|
|
630
|
+
hint="加 --yes")
|
|
631
|
+
if input("将删除 Norain 的全部配置、数据、自启动项和环境变量。输入 yes 确认:").strip().lower() != "yes":
|
|
632
|
+
print("已取消")
|
|
633
|
+
return EXIT_OK
|
|
634
|
+
res = install.uninstall(paths)
|
|
635
|
+
_out(args, res, "\n".join(f"· {d}" for d in res["done"]) + "".join(f"\n未完成:{e}" for e in res["errors"])
|
|
636
|
+
+ "\n" + res["note"])
|
|
637
|
+
return EXIT_FAILURE if res["errors"] else EXIT_OK
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
# ---- 入口 ----------------------------------------------------------------------
|
|
641
|
+
|
|
642
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
643
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
644
|
+
common.add_argument("--json", action="store_true", help="以 JSON 输出结果")
|
|
645
|
+
common.add_argument("-t", "--trace", action="store_true",
|
|
646
|
+
help="调试:执行后显示每个模块的运行情况和返回结果")
|
|
647
|
+
p = argparse.ArgumentParser(prog="norain", description="Norain 客户端")
|
|
648
|
+
sub = p.add_subparsers(dest="command", required=True, metavar="<命令>")
|
|
649
|
+
|
|
650
|
+
def add(parent, name, func, help_):
|
|
651
|
+
sp = parent.add_parser(name, parents=[common], help=help_)
|
|
652
|
+
sp.set_defaults(func=func)
|
|
653
|
+
return sp
|
|
654
|
+
|
|
655
|
+
# 配置类
|
|
656
|
+
cfg = sub.add_parser("config", help="配置").add_subparsers(dest="sub", required=True)
|
|
657
|
+
add(cfg, "validate", cmd_config_validate, "校验 cfg.toml 并运行 sing-box check")
|
|
658
|
+
add(cfg, "show", cmd_config_show, "显示生效配置(隐藏秘密)")
|
|
659
|
+
add(cfg, "edit", cmd_config_edit, "在编辑器里修改 cfg.toml(保存后校验)")
|
|
660
|
+
add(cfg, "path", cmd_config_path, "显示配置、状态、日志的位置")
|
|
661
|
+
st = add(cfg, "set", cmd_config_set, "设置任意配置项,例如 config set dns.mode split")
|
|
662
|
+
st.add_argument("key")
|
|
663
|
+
st.add_argument("value")
|
|
664
|
+
add(cfg, "protocol", cmd_config_protocol, "协议:自适应 / Hysteria2 / Trojan").add_argument(
|
|
665
|
+
"protocol", choices=["auto", "hysteria2", "trojan"])
|
|
666
|
+
add(cfg, "mode", cmd_config_mode, "启动模式:normal(开机自启动)/ safe(只手动启动)").add_argument(
|
|
667
|
+
"mode", choices=["normal", "safe"])
|
|
668
|
+
sv = add(cfg, "server", cmd_config_server, "代理服务器")
|
|
669
|
+
sv.add_argument("host")
|
|
670
|
+
sv.add_argument("--hy2-port", type=int)
|
|
671
|
+
sv.add_argument("--trojan-port", type=int)
|
|
672
|
+
sv.add_argument("--credential-ref", help="file:<密码文件> 或 env:<变量名>")
|
|
673
|
+
dn = add(cfg, "dns", cmd_config_dns, "DNS(不带参数时显示当前设置)")
|
|
674
|
+
dn.add_argument("--mode", choices=["local", "split", "proxy"])
|
|
675
|
+
dn.add_argument("--domestic", help="国内 DNS 的 IP")
|
|
676
|
+
dn.add_argument("--proxy", help="经代理访问的 DNS,https://… 或 IP")
|
|
677
|
+
dn.add_argument("--strategy", choices=["prefer_ipv4", "prefer_ipv6", "ipv4_only", "ipv6_only"])
|
|
678
|
+
|
|
679
|
+
ls = add(sub, "list", cmd_list, "白名单 / 黑名单 / 蓝名单 / 监控测试名单")
|
|
680
|
+
ls.add_argument("name", choices=list(LISTS))
|
|
681
|
+
ls.add_argument("action", nargs="?", default="show", choices=["show", "add", "remove"])
|
|
682
|
+
ls.add_argument("entries", nargs="*")
|
|
683
|
+
|
|
684
|
+
# 控制类
|
|
685
|
+
add(sub, "start", cmd_start, "启动代理(处于阻断模式时先自动解除)")
|
|
686
|
+
add(sub, "stop", cmd_stop, "停止代理(之后不会被自动拉起)")
|
|
687
|
+
add(sub, "restart", cmd_restart, "重启代理")
|
|
688
|
+
bt = add(sub, "boot", cmd_boot, "启动模块的入口(开机自启动项调用)")
|
|
689
|
+
bt.add_argument("--autostart", action="store_true", help="用户手动停止过时不启动")
|
|
690
|
+
add(sub, "status", cmd_status, "查看状态")
|
|
691
|
+
rn = add(sub, "run", cmd_run, "前台运行内控制模块")
|
|
692
|
+
rn.add_argument("--autostart", action="store_true", help="期望状态不是 running 时直接退出")
|
|
693
|
+
lg = add(sub, "logs", cmd_logs, "查看日志")
|
|
694
|
+
lg.add_argument("-f", "--follow", action="store_true")
|
|
695
|
+
lg.add_argument("-n", "--lines", type=int, default=50)
|
|
696
|
+
|
|
697
|
+
md = add(sub, "module", cmd_module, "启动 / 结束 / 重启 / 查看单个模块")
|
|
698
|
+
md.add_argument("name", choices=list(control.MODULES))
|
|
699
|
+
md.add_argument("action", choices=["start", "stop", "restart", "status"])
|
|
700
|
+
|
|
701
|
+
rp = add(sub, "repair", cmd_repair, "修复:file(文件)/ builtin(内置配置)/ full(完全配置)/ reload(重载)")
|
|
702
|
+
rp.add_argument("level", choices=["file", "builtin", "full", "reload"])
|
|
703
|
+
|
|
704
|
+
bk = add(sub, "block", cmd_block, "阻断模式:status / off(手动解除)/ on(手动进入)")
|
|
705
|
+
bk.add_argument("action", choices=["status", "off", "on"])
|
|
706
|
+
|
|
707
|
+
on = add(sub, "once", cmd_once, "一次性执行某个模块的某个功能")
|
|
708
|
+
on.add_argument("what", choices=["monitor", "select", "route", "rules-update", "rules-rollback", "scan"],
|
|
709
|
+
help="monitor 立即检测一轮;select 立即测速选协议;route <域名> 判断分流;"
|
|
710
|
+
"rules-update 更新规则集;rules-rollback <名称> 回滚;scan 扫描程序文件")
|
|
711
|
+
on.add_argument("arg", nargs="?")
|
|
712
|
+
|
|
713
|
+
ins = add(sub, "install", cmd_install, "安装:sing-box、默认配置、norain 命令、环境变量、开机自启动")
|
|
714
|
+
ins.add_argument("--singbox-archive", help="本地的 sing-box 压缩包(不联网)")
|
|
715
|
+
ins.add_argument("--singbox-sha256", help="压缩包的 SHA-256(默认用锁定文件里的值)")
|
|
716
|
+
ins.add_argument("--singbox-path", help="直接使用已有的 sing-box 可执行文件")
|
|
717
|
+
ins.add_argument("--config", help="用这份 cfg.toml 作为初始配置")
|
|
718
|
+
ins.add_argument("--server", help="代理服务器域名或 IP(也可以用环境变量 NORAIN_SERVER)")
|
|
719
|
+
ins.add_argument("--traffic-mode", default="system-proxy", choices=["tun", "mixed", "system-proxy"])
|
|
720
|
+
ins.add_argument("--protocol", default="auto", choices=["auto", "hysteria2", "trojan"])
|
|
721
|
+
ins.add_argument("--force", action="store_true", help="覆盖已有的 cfg.toml(先备份)")
|
|
722
|
+
ins.add_argument("--no-start", action="store_true", help="安装后不启动")
|
|
723
|
+
un = add(sub, "uninstall", cmd_uninstall, "完全卸载并清除痕迹")
|
|
724
|
+
un.add_argument("--yes", action="store_true", help="不询问,直接卸载")
|
|
725
|
+
|
|
726
|
+
add(sub, "_watchdog", cmd_watchdog, argparse.SUPPRESS)
|
|
727
|
+
return p
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def main(argv: list[str] | None = None) -> int:
|
|
731
|
+
args = build_parser().parse_args(argv)
|
|
732
|
+
paths = Paths.from_env()
|
|
733
|
+
try:
|
|
734
|
+
code = args.func(args, paths)
|
|
735
|
+
except NorainError as e:
|
|
736
|
+
code = _fail(args, e)
|
|
737
|
+
except KeyboardInterrupt:
|
|
738
|
+
return 130
|
|
739
|
+
if getattr(args, "trace", False) and args.command not in ("run", "_watchdog", "uninstall"):
|
|
740
|
+
try:
|
|
741
|
+
print_trace(paths)
|
|
742
|
+
except Exception as e: # noqa: BLE001 调试输出出错不能改变命令的退出码
|
|
743
|
+
print(f"(无法读取模块状态:{e})", file=sys.stderr)
|
|
744
|
+
return code
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
if __name__ == "__main__": # python -m norain.cli 也要能用;缺了它会静默退出 0
|
|
748
|
+
raise SystemExit(main())
|