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.
Files changed (53) hide show
  1. norain/__init__.py +3 -0
  2. norain/__main__.py +5 -0
  3. norain/block.py +281 -0
  4. norain/boot.py +142 -0
  5. norain/cli.py +748 -0
  6. norain/control.py +703 -0
  7. norain/defaults.py +42 -0
  8. norain/generate.py +264 -0
  9. norain/install.py +312 -0
  10. norain/maintain.py +313 -0
  11. norain/model.py +409 -0
  12. norain/monitor.py +314 -0
  13. norain/paths.py +124 -0
  14. norain/probe.py +158 -0
  15. norain/proxy.py +136 -0
  16. norain/repair.py +278 -0
  17. norain/routing.py +332 -0
  18. norain/rules.py +214 -0
  19. norain/runner.py +59 -0
  20. norain-0.2.0.dev0.dist-info/METADATA +99 -0
  21. norain-0.2.0.dev0.dist-info/RECORD +53 -0
  22. norain-0.2.0.dev0.dist-info/WHEEL +5 -0
  23. norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
  24. norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
  25. norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
  26. norain_core/__init__.py +4 -0
  27. norain_core/apply.py +70 -0
  28. norain_core/atomic.py +80 -0
  29. norain_core/cliutil.py +68 -0
  30. norain_core/daemonctl.py +192 -0
  31. norain_core/errors.py +60 -0
  32. norain_core/fetch.py +158 -0
  33. norain_core/log.py +104 -0
  34. norain_core/migrate.py +86 -0
  35. norain_core/osutil.py +332 -0
  36. norain_core/redact.py +60 -0
  37. norain_core/secrets.py +87 -0
  38. norain_core/singbox.py +93 -0
  39. norain_core/state.py +97 -0
  40. norain_core/supervisor.py +352 -0
  41. norain_core/sysproxy.py +112 -0
  42. norain_core/tomlio.py +86 -0
  43. norain_server/__init__.py +3 -0
  44. norain_server/__main__.py +5 -0
  45. norain_server/cert.py +276 -0
  46. norain_server/cli.py +477 -0
  47. norain_server/deploy.py +604 -0
  48. norain_server/firewall.py +226 -0
  49. norain_server/generate.py +112 -0
  50. norain_server/model.py +272 -0
  51. norain_server/paths.py +101 -0
  52. norain_server/runner.py +123 -0
  53. norain_server/service.py +83 -0
norain/monitor.py ADDED
@@ -0,0 +1,314 @@
1
+ """监控模块:低消耗、高频率地检测代理是否正常,给出错误码和报告。
2
+
3
+ 检测三个方向(最初目标):连通性(国内 / 国外)、出口 IP 位置(走代理与直连、IPv4 与 IPv6)、
4
+ DNS 解析位置。判定规则以最初目标为准(docs/decisions/0010 修订):
5
+
6
+ 100 全网络连通性失败:本地没有联网
7
+ 301 部分网站正常、大部分失败,且查不到出口 IP → 触发阻断
8
+ 600 国内正常、国外失败,走代理查出口无返回、直连返回国内位置 → 服务器链路失效
9
+ 604 国内外都正常,走代理时 IPv4 出口在国内、IPv6 在国外 → IPv4 链路配置问题
10
+ 606 国内外都正常,走代理时 IPv6 出口在国内、IPv4 在国外 → IPv6 链路配置问题
11
+ 400 国内外都正常,走代理的出口在国内 → 检测链路 / 分流配置问题
12
+ 401 国外域名被解析到国内位置 → DNS 配置问题
13
+
14
+ 去抖动:同一个错误码连续出现 failure_threshold 次才上报,连续正常 recovery_threshold 次才解除,
15
+ 避免网络抖动误触发修复和阻断。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import threading
21
+ import time
22
+ from concurrent.futures import ThreadPoolExecutor
23
+ from dataclasses import dataclass
24
+ from typing import Callable
25
+
26
+ from norain_core.log import Logger
27
+
28
+ from . import probe
29
+ from .model import ClientConfig
30
+ from .rules import Geo
31
+
32
+ OK = 0
33
+ MEANING = {
34
+ 0: "正常",
35
+ 100: "本地网络未连接",
36
+ 301: "大部分网站无法访问,且无法检测出口 IP",
37
+ 400: "走代理的出口位置在国内:检测链路或分流配置有问题",
38
+ 401: "国外域名被解析到国内位置:DNS 配置有问题",
39
+ 600: "服务器链路失效:服务器未启动或连接失败",
40
+ 604: "IPv4 链路配置问题:走代理时 IPv4 出口在国内",
41
+ 606: "IPv6 链路配置问题:走代理时 IPv6 出口在国内",
42
+ }
43
+ GUESS = {
44
+ 100: ["网线或 Wi-Fi 断开", "路由器或宽带故障", "系统网络被禁用"],
45
+ 301: ["代理链路严重不稳定或被干扰", "本地防火墙或安全软件拦截了大部分连接", "DNS 被污染"],
46
+ 400: ["分流规则把国外流量判成了直连", "黑名单或学到的名单里有不该直连的条目", "规则集文件损坏或过期"],
47
+ 401: ["DNS 没有经过代理服务器解析", "系统 DNS 被其他软件改写", "TUN 的 DNS 劫持没有生效"],
48
+ 600: ["代理服务器没有启动或已宕机", "服务器端口被封或防火墙没有放行", "密码或证书配置不匹配",
49
+ "服务器地址或端口写错"],
50
+ 604: ["服务器的 IPv4 出口有问题", "客户端的 IPv4 流量没有进入代理"],
51
+ 606: ["服务器没有可用的 IPv6 出口", "客户端的 IPv6 流量绕过了代理(可在 [dns] 里设 strategy = \"ipv4_only\")"],
52
+ }
53
+
54
+
55
+ @dataclass
56
+ class Round:
57
+ at: float
58
+ domestic: list[dict]
59
+ foreign: list[dict]
60
+ direct_v4: dict | None # 直连查到的出口
61
+ proxy_v4: dict | None # 走代理(经过分流规则)查到的出口
62
+ proxy_v6: dict | None
63
+ dns_home: bool | None # 国外测试域名是否被解析到国内;None 表示无法判断
64
+ code: int = OK
65
+ reason: str = ""
66
+ elapsed_ms: float = 0.0
67
+
68
+ def as_dict(self) -> dict:
69
+ return {"at": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(self.at)), "code": self.code,
70
+ "meaning": MEANING.get(self.code, ""), "reason": self.reason,
71
+ "elapsed_ms": round(self.elapsed_ms), "domestic": self.domestic, "foreign": self.foreign,
72
+ "exit": {"direct_v4": self.direct_v4, "proxy_v4": self.proxy_v4, "proxy_v6": self.proxy_v6},
73
+ "dns_resolves_foreign_to_home": self.dns_home}
74
+
75
+
76
+ @dataclass
77
+ class Ports:
78
+ """本地探测入口。都为 None 表示代理没有运行:直连用裸连接,走代理的探测一律「无返回」。"""
79
+ routed: probe.Proxy = None # mixed-in:经过完整分流规则
80
+ direct: probe.Proxy = None # probe-direct:强制直连
81
+
82
+
83
+ def decide(rnd: Round, home: str) -> tuple[int, str]:
84
+ """按最初目标的判定表得出本轮的原始错误码(未去抖动)。"""
85
+ dom = [r["ok"] for r in rnd.domestic]
86
+ frn = [r["ok"] for r in rnd.foreign]
87
+ dom_ok = bool(dom) and sum(dom) * 2 >= len(dom)
88
+ frn_ok = bool(frn) and sum(frn) * 2 >= len(frn)
89
+ total, good = len(dom) + len(frn), sum(dom) + sum(frn)
90
+ p4 = rnd.proxy_v4["loc"] if rnd.proxy_v4 else None
91
+ p6 = rnd.proxy_v6["loc"] if rnd.proxy_v6 else None
92
+ d4 = rnd.direct_v4["loc"] if rnd.direct_v4 else None
93
+ home = home.upper()
94
+
95
+ if good == 0 and rnd.direct_v4 is None:
96
+ return 100, "国内外目标全部不通,直连也查不到出口"
97
+ if dom_ok and not frn_ok and p4 is None and p6 is None:
98
+ return 600, f"国内正常、国外失败;走代理查出口无返回,直连出口在 {d4 or '未知位置'}"
99
+ if good * 2 < total and p4 is None and p6 is None and d4 is None:
100
+ return 301, f"{total} 个目标只有 {good} 个可达,且无法检测出口 IP"
101
+ if dom_ok and frn_ok:
102
+ if p4 == home and p6 not in (None, home):
103
+ return 604, f"走代理:IPv4 出口在 {p4}(国内),IPv6 出口在 {p6}"
104
+ if p6 == home and p4 not in (None, home):
105
+ return 606, f"走代理:IPv6 出口在 {p6}(国内),IPv4 出口在 {p4}"
106
+ if p4 == home or (p4 is None and p6 == home):
107
+ return 400, f"走代理的出口在 {home}(国内),直连出口在 {d4 or '未知位置'}"
108
+ if rnd.dns_home is True:
109
+ return 401, "国外测试域名被解析到了国内位置"
110
+ return OK, ""
111
+
112
+
113
+ def run_round(cfg: ClientConfig, ports: Ports, geo: Geo | None = None) -> Round:
114
+ """执行一轮检测。各探测并行,整轮耗时约等于一次超时。"""
115
+ m = cfg.monitor
116
+ t = m.timeout_seconds
117
+ started = time.monotonic()
118
+ proxy_up = ports.routed is not None
119
+
120
+ def head(url: str, px: probe.Proxy, via: str) -> dict:
121
+ return probe.http(url, proxy=px, timeout=t, via=via, method="HEAD").as_dict()
122
+
123
+ def dns_home() -> bool | None:
124
+ if geo is None:
125
+ return None
126
+ verdicts = []
127
+ for name in m.dns_test_domains:
128
+ ips = probe.system_resolve(name)
129
+ if ips:
130
+ verdicts.append(geo.any_home(ips))
131
+ if any(v is True for v in verdicts):
132
+ return True
133
+ return False if verdicts and all(v is False for v in verdicts) else None
134
+
135
+ with ThreadPoolExecutor(max_workers=12, thread_name_prefix="norain-probe") as pool:
136
+ f_dom = [pool.submit(head, u, ports.direct, "direct") for u in m.domestic_targets]
137
+ # 代理没有运行时,国外目标一律记为失败(不能用裸连接去试:那会暴露真实 IP)
138
+ f_frn = [pool.submit(head, u, ports.routed, "proxy") for u in m.foreign_targets] if proxy_up else []
139
+ f_d4 = pool.submit(probe.trace, m.trace_v4, proxy=ports.direct, timeout=t, via="direct")
140
+ f_p4 = pool.submit(probe.trace, m.trace_v4, proxy=ports.routed, timeout=t, via="proxy") if proxy_up else None
141
+ f_p6 = pool.submit(probe.trace, m.trace_v6, proxy=ports.routed, timeout=t, via="proxy") if proxy_up else None
142
+ f_dns = pool.submit(dns_home) if proxy_up else None
143
+ rnd = Round(
144
+ at=time.time(),
145
+ domestic=[f.result() for f in f_dom],
146
+ foreign=([f.result() for f in f_frn] if proxy_up else
147
+ [{"ok": False, "target": u, "via": "proxy", "status": None, "elapsed_ms": None,
148
+ "error": "代理没有运行"} for u in m.foreign_targets]),
149
+ direct_v4=f_d4.result(),
150
+ proxy_v4=f_p4.result() if f_p4 else None,
151
+ proxy_v6=f_p6.result() if f_p6 else None,
152
+ dns_home=f_dns.result() if f_dns else None,
153
+ )
154
+ rnd.code, rnd.reason = decide(rnd, m.home_country)
155
+ rnd.elapsed_ms = (time.monotonic() - started) * 1000
156
+ return rnd
157
+
158
+
159
+ @dataclass
160
+ class Debounce:
161
+ fail_n: int
162
+ ok_n: int
163
+ current: int = OK # 已上报的错误码
164
+ _pending: int = OK
165
+ _count: int = 0
166
+ _ok_count: int = 0
167
+
168
+ def feed(self, raw: int) -> bool:
169
+ """喂入一轮的原始码,返回上报的错误码是否发生变化。"""
170
+ if raw == OK:
171
+ self._pending, self._count = OK, 0
172
+ if self.current == OK:
173
+ return False
174
+ self._ok_count += 1
175
+ if self._ok_count >= self.ok_n:
176
+ self.current, self._ok_count = OK, 0
177
+ return True
178
+ return False
179
+ self._ok_count = 0
180
+ if raw == self._pending:
181
+ self._count += 1
182
+ else:
183
+ self._pending, self._count = raw, 1
184
+ if self._count >= self.fail_n and self.current != raw:
185
+ self.current = raw
186
+ return True
187
+ return False
188
+
189
+ def reset(self) -> None:
190
+ self.current = self._pending = OK
191
+ self._count = self._ok_count = 0
192
+
193
+
194
+ class Monitor:
195
+ """监控模块。自己的线程按间隔检测;错误码变化时回调 on_change(code, round)。"""
196
+
197
+ name = "monitor"
198
+
199
+ def __init__(self, cfg: ClientConfig, ports_fn: Callable[[], Ports], geo: Geo | None, log: Logger,
200
+ on_change: Callable[[int, Round], None] | None = None) -> None:
201
+ self.cfg, self.ports_fn, self.geo, self.log, self.on_change = cfg, ports_fn, geo, log, on_change
202
+ self.debounce = Debounce(cfg.monitor.failure_threshold, cfg.monitor.recovery_threshold)
203
+ self.last: Round | None = None
204
+ self.rounds = 0
205
+ self._paused = threading.Event()
206
+ self._stop = threading.Event()
207
+ self._lock = threading.Lock()
208
+ self._thread: threading.Thread | None = None
209
+
210
+ @property
211
+ def code(self) -> int:
212
+ return self.debounce.current
213
+
214
+ def internet_ok(self) -> bool:
215
+ return self.code != 100 and not (self.last and self.last.code == 100)
216
+
217
+ def check_once(self, *, feed: bool = True) -> Round:
218
+ """立即检测一轮。feed=False 时不影响去抖动计数(命令行的一次性检测)。"""
219
+ with self._lock:
220
+ rnd = run_round(self.cfg, self.ports_fn(), self.geo)
221
+ self.last = rnd
222
+ self.rounds += 1
223
+ changed = self.debounce.feed(rnd.code) if feed else False
224
+ if rnd.code:
225
+ self.log.warn("monitor.round", code=rnd.code, reason=rnd.reason, reported=self.code)
226
+ else:
227
+ self.log.debug("monitor.round", code=0)
228
+ if changed:
229
+ self.log.warn("monitor.code_changed", code=self.code, meaning=MEANING.get(self.code, ""),
230
+ reason=rnd.reason)
231
+ if self.on_change:
232
+ self.on_change(self.code, rnd)
233
+ return rnd
234
+
235
+ def verify(self, rounds: int, *, gap: float = 1.0) -> int:
236
+ """修复之后的验证:连续快速检测几轮,全部正常才算通过。返回最后看到的原始错误码。
237
+ 不经过去抖动,也不触发回调(调用方就是处理故障的那一方)。"""
238
+ code = OK
239
+ for i in range(max(rounds, 1)):
240
+ with self._lock:
241
+ rnd = run_round(self.cfg, self.ports_fn(), self.geo)
242
+ self.last = rnd
243
+ self.rounds += 1
244
+ code = rnd.code
245
+ if code != OK:
246
+ return code
247
+ if i + 1 < rounds and self._stop.wait(gap):
248
+ break
249
+ return code
250
+
251
+ # 自维持模块发起修复期间暂停监控,避免修复过程中的抖动被当成新的故障
252
+ def pause(self) -> None:
253
+ self._paused.set()
254
+
255
+ def resume(self, *, reset: bool = True) -> None:
256
+ if reset:
257
+ self.debounce.reset()
258
+ self._paused.clear()
259
+
260
+ @property
261
+ def paused(self) -> bool:
262
+ return self._paused.is_set()
263
+
264
+ def _run(self) -> None:
265
+ while not self._stop.is_set():
266
+ if not self._paused.is_set():
267
+ try:
268
+ self.check_once()
269
+ except Exception as e: # noqa: BLE001 探测器自身出错不能让模块退出
270
+ self.log.error("monitor.failed", error=str(e))
271
+ if self._stop.wait(self.cfg.monitor.interval_seconds):
272
+ break
273
+
274
+ def start(self) -> None:
275
+ if self.alive():
276
+ return
277
+ self._stop.clear()
278
+ self._thread = threading.Thread(target=self._run, name="norain-monitor", daemon=True)
279
+ self._thread.start()
280
+
281
+ def stop(self) -> None:
282
+ self._stop.set()
283
+ if self._thread:
284
+ self._thread.join(self.cfg.monitor.timeout_seconds * 3 + 5)
285
+
286
+ def alive(self) -> bool:
287
+ return bool(self._thread and self._thread.is_alive())
288
+
289
+ def status(self) -> dict:
290
+ return {"state": ("paused" if self.paused else "running") if self.alive() else "stopped",
291
+ "code": self.code, "meaning": MEANING.get(self.code, ""), "rounds": self.rounds,
292
+ "last_result": self.last.as_dict() if self.last else None}
293
+
294
+
295
+ def report_text(rnd: Round) -> str:
296
+ """给人看的检测报告。"""
297
+ d = rnd.as_dict()
298
+ lines = [f"错误码:{rnd.code}({MEANING.get(rnd.code, '未知')})"]
299
+ if rnd.reason:
300
+ lines.append(f"依据:{rnd.reason}")
301
+ for title, rows in (("国内连通性(直连)", d["domestic"]), ("国外连通性(走代理)", d["foreign"])):
302
+ ok = sum(1 for r in rows if r["ok"])
303
+ lines.append(f"{title}:{ok}/{len(rows)}")
304
+ lines += [f" {'✓' if r['ok'] else '✗'} {r['target']}"
305
+ + (f" {r['elapsed_ms']} ms" if r["ok"] else f" {r['error']}") for r in rows]
306
+ for label, key in (("直连出口 IPv4", "direct_v4"), ("代理出口 IPv4", "proxy_v4"), ("代理出口 IPv6", "proxy_v6")):
307
+ e = d["exit"][key]
308
+ lines.append(f"{label}:{e['ip'] + '(' + (e['loc'] or '?') + ')' if e else '无返回'}")
309
+ lines.append("DNS:" + {True: "国外域名被解析到国内(异常)", False: "国外域名解析在国外(正常)",
310
+ None: "无法判断(没有 GeoIP 规则集或代理没有运行)"}[rnd.dns_home])
311
+ if rnd.code in GUESS:
312
+ lines.append("可能原因:")
313
+ lines += [f" · {g}" for g in GUESS[rnd.code]]
314
+ return "\n".join(lines)
norain/paths.py ADDED
@@ -0,0 +1,124 @@
1
+ """客户端路径。客户端是用户级程序,不需要管理员权限。
2
+
3
+ | | Windows | Linux |
4
+ |---|---|---|
5
+ | 配置 | %APPDATA%\\norain\\cfg.toml | ~/.config/norain/cfg.toml |
6
+ | 状态 | %LOCALAPPDATA%\\norain | ~/.local/state/norain |
7
+ | 日志 | %LOCALAPPDATA%\\norain\\log | ~/.local/state/norain/log |
8
+
9
+ 环境变量 NORAIN_HOME、NORAIN_CONFIG、NORAIN_STATE、NORAIN_LOG、NORAIN_SINGBOX 优先。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+
19
+ def _defaults(env, platform: str) -> tuple[Path, Path]:
20
+ home = Path(env.get("USERPROFILE") or env.get("HOME") or Path.home())
21
+ if platform == "nt":
22
+ roaming = Path(env.get("APPDATA") or home / "AppData" / "Roaming")
23
+ local = Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local")
24
+ return roaming / "norain", local / "norain"
25
+ config = Path(env.get("XDG_CONFIG_HOME") or home / ".config")
26
+ state = Path(env.get("XDG_STATE_HOME") or home / ".local" / "state")
27
+ return config / "norain", state / "norain"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Paths:
32
+ home: Path
33
+ config: Path
34
+ state: Path
35
+ log_dir: Path
36
+ log_dir_from_env: bool
37
+ singbox: str | None
38
+ platform: str
39
+
40
+ @classmethod
41
+ def from_env(cls, env=None, platform: str | None = None) -> "Paths":
42
+ env = os.environ if env is None else env
43
+ platform = platform or os.name
44
+ d_home, d_state = _defaults(env, platform)
45
+ home = Path(env.get("NORAIN_HOME") or d_home)
46
+ state = Path(env.get("NORAIN_STATE") or d_state)
47
+ return cls(
48
+ home=home,
49
+ config=Path(env.get("NORAIN_CONFIG") or home / "cfg.toml"),
50
+ state=state,
51
+ log_dir=Path(env.get("NORAIN_LOG") or state / "log"),
52
+ log_dir_from_env=bool(env.get("NORAIN_LOG")),
53
+ singbox=env.get("NORAIN_SINGBOX") or None,
54
+ platform=platform,
55
+ )
56
+
57
+ def with_log_dir(self, directory: str) -> "Paths":
58
+ if directory and not self.log_dir_from_env:
59
+ return Paths(self.home, self.config, self.state, Path(directory).expanduser(), False,
60
+ self.singbox, self.platform)
61
+ return self
62
+
63
+ @property
64
+ def bundled_singbox(self) -> Path:
65
+ return self.state / "bin" / ("sing-box.exe" if self.platform == "nt" else "sing-box")
66
+
67
+ @property
68
+ def run_dir(self) -> Path: return self.state / "run"
69
+ @property
70
+ def current_json(self) -> Path: return self.run_dir / "sing-box.json"
71
+ @property
72
+ def meta_json(self) -> Path: return self.run_dir / "sing-box.json.meta.json"
73
+ @property
74
+ def backups(self) -> Path: return self.state / "backups"
75
+ @property
76
+ def desired(self) -> Path: return self.state / "desired-state.json"
77
+ @property
78
+ def lock(self) -> Path: return self.state / "op.lock"
79
+ @property
80
+ def runner(self) -> Path: return self.run_dir / "runner.json"
81
+ @property
82
+ def stop_file(self) -> Path: return self.run_dir / "stop-request"
83
+ @property
84
+ def last_error(self) -> Path: return self.state / "last-error.json"
85
+ @property
86
+ def log_file(self) -> Path: return self.log_dir / "norain.log"
87
+
88
+ # ---- 各模块的状态文件 ----
89
+ @property
90
+ def bin_dir(self) -> Path: return self.state / "bin"
91
+ @property
92
+ def cache_dir(self) -> Path: return self.state / "cache"
93
+ @property
94
+ def status_file(self) -> Path: return self.run_dir / "status.json" # 内控制写,CLI 读
95
+ @property
96
+ def ctl_dir(self) -> Path: return self.run_dir / "ctl" # CLI → 内控制的请求
97
+ @property
98
+ def proxy_state(self) -> Path: return self.run_dir / "proxy.json" # 代理模块(sing-box)
99
+ @property
100
+ def proxy_stop(self) -> Path: return self.run_dir / "proxy-stop"
101
+ @property
102
+ def sysproxy_state(self) -> Path: return self.run_dir / "sysproxy.json" # 启动前的系统代理快照
103
+ @property
104
+ def watchdog_file(self) -> Path: return self.run_dir / "watchdog.json" # 看门狗进程
105
+ @property
106
+ def block_state(self) -> Path: return self.state / "isolation.json" # 阻断模式
107
+ @property
108
+ def rules_dir(self) -> Path: return self.state / "rules"
109
+ @property
110
+ def routing_dir(self) -> Path: return self.state / "routing"
111
+ @property
112
+ def learned(self) -> Path: return self.routing_dir / "learned.json" # 自动学到的名单
113
+ @property
114
+ def selection(self) -> Path: return self.state / "selection.json" # 自适应选中的协议
115
+ @property
116
+ def package_dir(self) -> Path: return self.state / "package" # 安装包副本(修复用)
117
+ @property
118
+ def manifest(self) -> Path: return self.package_dir / "manifest.json"
119
+ @property
120
+ def package_zip(self) -> Path: return self.package_dir / "norain-pkg.zip"
121
+ @property
122
+ def orig_config(self) -> Path: return self.package_dir / "cfg.toml.orig" # 安装时的初始配置
123
+ @property
124
+ def install_record(self) -> Path: return self.state / "install.json"
norain/probe.py ADDED
@@ -0,0 +1,158 @@
1
+ """探测工具:监控模块、分流模块和自适应选协议共用。
2
+
3
+ 「走代理」和「直连」都通过 sing-box 的本地入口(HTTP 代理)发出:
4
+ - 走 mixed-in:经过完整的分流规则,等同于用户的真实流量;
5
+ - 走 probe-direct / probe-<协议>:绕过分流,强制直连或强制走某个协议。
6
+ 这样 TUN 模式下探测流量不会被自己接管。没有可用入口时(代理没在运行)才用裸连接。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import json
13
+ import socket
14
+ import ssl
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from dataclasses import dataclass, field
20
+
21
+ Proxy = tuple[str, int] | None
22
+
23
+ _UA = "Mozilla/5.0 (norain-probe)"
24
+
25
+
26
+ @dataclass
27
+ class Result:
28
+ ok: bool
29
+ target: str = ""
30
+ via: str = ""
31
+ status: int | None = None
32
+ elapsed_ms: float | None = None
33
+ error: str = ""
34
+ body: str = field(default="", repr=False)
35
+
36
+ def as_dict(self) -> dict:
37
+ return {"ok": self.ok, "target": self.target, "via": self.via, "status": self.status,
38
+ "elapsed_ms": round(self.elapsed_ms, 1) if self.elapsed_ms is not None else None,
39
+ "error": self.error}
40
+
41
+
42
+ @functools.lru_cache(maxsize=2)
43
+ def _ssl_context(verify: bool) -> ssl.SSLContext:
44
+ """TLS 上下文只建两个(校验 / 不校验)并复用。
45
+
46
+ create_default_context() 每次都要加载系统的整个 CA 证书库(Windows 上要枚举证书存储),
47
+ 而监控每一轮有十来个探测、每个探测都新建一次——这是探测路径上最大的一笔固定开销。
48
+ SSLContext 可以在线程间共享。
49
+ """
50
+ ctx = ssl.create_default_context()
51
+ if not verify:
52
+ ctx.check_hostname = False
53
+ ctx.verify_mode = ssl.CERT_NONE
54
+ return ctx
55
+
56
+
57
+ @functools.lru_cache(maxsize=32)
58
+ def _opener(proxy: Proxy, verify: bool) -> urllib.request.OpenerDirector:
59
+ """按(本地入口, 是否校验证书)缓存 opener:入口只有固定的几个,opener 不带连接状态。"""
60
+ handlers: list = [urllib.request.HTTPSHandler(context=_ssl_context(verify))]
61
+ if proxy:
62
+ addr = f"http://{proxy[0]}:{proxy[1]}"
63
+ handlers.append(urllib.request.ProxyHandler({"http": addr, "https": addr}))
64
+ else:
65
+ handlers.append(urllib.request.ProxyHandler({})) # 明确忽略系统代理和环境变量
66
+ return urllib.request.build_opener(*handlers)
67
+
68
+
69
+ def http(url: str, *, proxy: Proxy = None, timeout: float = 5.0, via: str = "", method: str = "GET",
70
+ headers: dict | None = None, max_bytes: int = 8192, verify: bool = True) -> Result:
71
+ """发一个 HTTP 请求。任何 HTTP 状态码(包括 4xx/5xx)都算「连通」,只有网络层失败才算不通。"""
72
+ req = urllib.request.Request(url, method=method, headers={"User-Agent": _UA, **(headers or {})})
73
+ started = time.monotonic()
74
+ try:
75
+ with _opener(tuple(proxy) if proxy else None, verify).open(req, timeout=timeout) as r:
76
+ body = r.read(max_bytes).decode("utf-8", "replace")
77
+ return Result(True, url, via, r.status, (time.monotonic() - started) * 1000, body=body)
78
+ except urllib.error.HTTPError as e:
79
+ return Result(True, url, via, e.code, (time.monotonic() - started) * 1000)
80
+ except (urllib.error.URLError, OSError, ValueError, ssl.SSLError) as e:
81
+ reason = getattr(e, "reason", e)
82
+ return Result(False, url, via, None, None, error=str(reason)[:200])
83
+
84
+
85
+ def trace(url: str, *, proxy: Proxy = None, timeout: float = 5.0, via: str = "") -> dict | None:
86
+ """查询出口 IP 和位置(Cloudflare /cdn-cgi/trace 格式:每行 key=value)。无返回时为 None。"""
87
+ # 校验证书:伪造的出口位置会掩盖泄漏。默认的 1.1.1.1 / 2606:4700:4700::1111 证书带 IP SAN
88
+ r = http(url, proxy=proxy, timeout=timeout, via=via)
89
+ if not r.ok or r.status != 200:
90
+ return None
91
+ kv = dict(line.split("=", 1) for line in r.body.splitlines() if "=" in line)
92
+ if "ip" not in kv:
93
+ return None
94
+ return {"ip": kv["ip"], "loc": kv.get("loc", "").upper(), "via": via}
95
+
96
+
97
+ def reachable(host: str, *, proxy: Proxy = None, timeout: float = 5.0, via: str = "") -> Result:
98
+ """某个域名能不能访问:先试 HTTPS,再试 HTTP。
99
+ 这里不校验证书:结果只是一个「连得上 / 连不上」的布尔值,不读取也不信任任何响应内容。"""
100
+ r = http(f"https://{host}/", proxy=proxy, timeout=timeout, via=via, method="HEAD", verify=False)
101
+ if r.ok:
102
+ return r
103
+ r2 = http(f"http://{host}/", proxy=proxy, timeout=timeout, via=via, method="HEAD")
104
+ return r2 if r2.ok else r
105
+
106
+
107
+ def tcp(host: str, port: int, *, proxy: Proxy = None, timeout: float = 5.0) -> bool:
108
+ """TCP 连通性。经代理时用 HTTP CONNECT,并在隧道里做一次 TLS 握手确认对端真的可达。"""
109
+ try:
110
+ if proxy is None:
111
+ with socket.create_connection((host, port), timeout=timeout):
112
+ return True
113
+ with socket.create_connection(proxy, timeout=timeout) as s:
114
+ target = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
115
+ s.sendall(f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n".encode())
116
+ head = s.recv(4096)
117
+ if b" 200" not in head.split(b"\r\n", 1)[0]:
118
+ return False
119
+ if port != 443:
120
+ return True
121
+ with _ssl_context(False).wrap_socket(s, server_hostname=None):
122
+ return True
123
+ except (OSError, ssl.SSLError):
124
+ return False
125
+
126
+
127
+ def doh(endpoint: str, name: str, *, proxy: Proxy = None, timeout: float = 5.0) -> list[str]:
128
+ """用 JSON 接口查询 A 和 AAAA 记录(阿里 /resolve、Cloudflare/Google /dns-query 都支持)。"""
129
+ ips: list[str] = []
130
+ for rtype, code in (("A", 1), ("AAAA", 28)):
131
+ q = urllib.parse.urlencode({"name": name, "type": rtype})
132
+ sep = "&" if "?" in endpoint else "?"
133
+ r = http(f"{endpoint}{sep}{q}", proxy=proxy, timeout=timeout,
134
+ headers={"Accept": "application/dns-json"}, max_bytes=65536) # 校验证书,防止解析结果被篡改
135
+ if not r.ok or r.status != 200:
136
+ continue
137
+ try:
138
+ answers = json.loads(r.body).get("Answer") or []
139
+ except ValueError:
140
+ continue
141
+ ips += [a["data"] for a in answers if a.get("type") == code and a.get("data")]
142
+ return ips
143
+
144
+
145
+ def system_resolve(name: str) -> list[str]:
146
+ """用系统解析器解析(TUN 模式下会被 sing-box 接管,等同于应用看到的结果)。"""
147
+ try:
148
+ return sorted({ai[4][0] for ai in socket.getaddrinfo(name, None)})
149
+ except OSError:
150
+ return []
151
+
152
+
153
+ def port_open(port: int, host: str = "127.0.0.1") -> bool:
154
+ try:
155
+ with socket.create_connection((host, port), timeout=1):
156
+ return True
157
+ except OSError:
158
+ return False