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_core/fetch.py ADDED
@@ -0,0 +1,158 @@
1
+ """取得、校验并解出 sing-box 二进制。锁定数据必须与 third_party/singbox.lock.toml 一致。
2
+
3
+ 校验顺序:SHA-256 与锁定值一致 → 解出二进制 → 调用方再用 `sing-box version` 核对版本。
4
+ 摘要是从发布页转录的,尚未对真实文件复核(docs/decisions/0002)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import os
11
+ import platform
12
+ import tarfile
13
+ import urllib.request
14
+ import zipfile
15
+ from pathlib import Path
16
+ from typing import Callable
17
+
18
+ from .errors import EXIT_DEPENDENCY, EXIT_EXTERNAL, NorainError
19
+ from .singbox import PINNED_VERSION
20
+
21
+ BASE_URL = f"https://github.com/SagerNet/sing-box/releases/download/v{PINNED_VERSION}/"
22
+ ASSETS: dict[str, tuple[str, str]] = {
23
+ "linux-amd64": (f"sing-box-{PINNED_VERSION}-linux-amd64.tar.gz",
24
+ "699a1b510aa4396b2176d32d1181920399ebf1e267835da6f3b598d0f7c24968"),
25
+ "linux-arm64": (f"sing-box-{PINNED_VERSION}-linux-arm64.tar.gz",
26
+ "436441f76ee2f7fe21b5b2d426d3cb261a480455a704865789ad533e4273ec26"),
27
+ "windows-amd64": (f"sing-box-{PINNED_VERSION}-windows-amd64.zip",
28
+ "99185d75d314a07dbba4a130c8ad986cbeb629a07927975636b341ca61f991df"),
29
+ "windows-arm64": (f"sing-box-{PINNED_VERSION}-windows-arm64.zip",
30
+ "8cd0a4d0cd8cd480be5731ac31f17038969a42d12add9feb6e031fd43d85bbae"),
31
+ }
32
+ _ARCH = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}
33
+
34
+ Downloader = Callable[[str, Path], None]
35
+
36
+
37
+ def target(system: str | None = None, machine: str | None = None) -> str:
38
+ system = (system or platform.system()).lower()
39
+ arch = _ARCH.get((machine or platform.machine()).lower())
40
+ key = f"{system}-{arch}"
41
+ if key not in ASSETS:
42
+ raise NorainError(f"不支持的平台:{system} {machine or platform.machine()}",
43
+ exit_code=EXIT_DEPENDENCY, business_code=150, module="fetch")
44
+ return key
45
+
46
+
47
+ def sha256_file(path: Path) -> str:
48
+ h = hashlib.sha256()
49
+ with path.open("rb") as f:
50
+ for chunk in iter(lambda: f.read(1 << 20), b""):
51
+ h.update(chunk)
52
+ return h.hexdigest()
53
+
54
+
55
+ def _download(url: str, dest: Path) -> None:
56
+ with urllib.request.urlopen(url, timeout=120) as r, dest.open("wb") as f: # noqa: S310
57
+ while chunk := r.read(1 << 20):
58
+ f.write(chunk)
59
+
60
+
61
+ def obtain(tgt: str, cache_dir: Path, *, archive: Path | None = None,
62
+ expected_sha256: str | None = None, downloader: Downloader = _download) -> Path:
63
+ """返回通过校验的压缩包路径。archive 为本地文件时不联网。"""
64
+ name, pinned = ASSETS[tgt]
65
+ expected = (expected_sha256 or pinned).lower()
66
+ cache_dir.mkdir(parents=True, exist_ok=True)
67
+ dest = cache_dir / name
68
+ if archive is not None:
69
+ if not archive.is_file():
70
+ raise NorainError(f"压缩包不存在:{archive}", exit_code=EXIT_DEPENDENCY, module="fetch")
71
+ src = archive
72
+ else:
73
+ src = dest
74
+ if not (dest.is_file() and sha256_file(dest) == expected):
75
+ tmp = dest.with_suffix(dest.suffix + ".part")
76
+ try:
77
+ downloader(BASE_URL + name, tmp)
78
+ except OSError as e:
79
+ tmp.unlink(missing_ok=True)
80
+ raise NorainError(f"下载 sing-box 失败:{e}", exit_code=EXIT_EXTERNAL, module="fetch",
81
+ retryable=True,
82
+ hint=f"手动下载 {BASE_URL + name} 后用 --singbox-archive 指定") from None
83
+ os.replace(tmp, dest)
84
+ actual = sha256_file(src)
85
+ if actual != expected:
86
+ if src == dest:
87
+ dest.unlink(missing_ok=True)
88
+ raise NorainError(f"sing-box 压缩包的 SHA-256 不符:期望 {expected},实际 {actual}",
89
+ exit_code=EXIT_DEPENDENCY, business_code=150, module="fetch",
90
+ hint="文件可能损坏或被替换,已拒绝安装")
91
+ if src != dest:
92
+ dest.write_bytes(src.read_bytes())
93
+ return dest
94
+
95
+
96
+ def extract_binary(archive: Path, dest: Path) -> None:
97
+ """只读取名为 sing-box / sing-box.exe 的成员的内容写到 dest,不按压缩包里的路径落盘。"""
98
+ data = None
99
+ if archive.name.endswith(".zip"):
100
+ with zipfile.ZipFile(archive) as z:
101
+ for n in z.namelist():
102
+ if n.rsplit("/", 1)[-1] == "sing-box.exe":
103
+ data = z.read(n)
104
+ else:
105
+ with tarfile.open(archive, "r:gz") as t:
106
+ for m in t.getmembers():
107
+ if m.isfile() and m.name.rsplit("/", 1)[-1] == "sing-box":
108
+ data = t.extractfile(m).read()
109
+ if data is None:
110
+ raise NorainError(f"压缩包里没有 sing-box 可执行文件:{archive}", exit_code=EXIT_DEPENDENCY,
111
+ business_code=150, module="fetch")
112
+ dest.parent.mkdir(parents=True, exist_ok=True)
113
+ tmp = dest.with_name(dest.name + ".new")
114
+ tmp.write_bytes(data)
115
+ os.chmod(tmp, 0o755)
116
+ os.replace(tmp, dest)
117
+
118
+
119
+ def install_singbox(dest: Path, cache_dir: Path, *, archive: Path | None = None,
120
+ expected_sha256: str | None = None, existing: Path | None = None,
121
+ need_tags: set[str] | None = None):
122
+ """把通过校验的 sing-box 安装到 dest,返回 BinaryInfo。
123
+
124
+ 来源优先级:existing(已有的可执行文件,直接复制)→ archive(本地压缩包)→ 下载。
125
+ 新二进制的版本或构建标签不符时恢复原文件并抛出错误。
126
+ """
127
+ import shutil
128
+
129
+ from . import singbox
130
+
131
+ backup = dest.with_name(dest.name + ".bak")
132
+ had_old = dest.is_file()
133
+ if had_old:
134
+ shutil.copy2(dest, backup)
135
+ try:
136
+ if existing is not None:
137
+ if not existing.is_file():
138
+ raise NorainError(f"sing-box 不存在:{existing}", exit_code=EXIT_DEPENDENCY,
139
+ business_code=150, module="fetch")
140
+ dest.parent.mkdir(parents=True, exist_ok=True)
141
+ if existing.resolve() != dest.resolve():
142
+ tmp = dest.with_name(dest.name + ".new")
143
+ shutil.copy2(existing, tmp)
144
+ os.chmod(tmp, 0o755)
145
+ os.replace(tmp, dest)
146
+ else:
147
+ pkg = obtain(target(), cache_dir, archive=archive, expected_sha256=expected_sha256)
148
+ extract_binary(pkg, dest)
149
+ info = singbox.inspect(dest)
150
+ singbox.require(info, need_tags=need_tags or set())
151
+ except NorainError:
152
+ if had_old:
153
+ os.replace(backup, dest)
154
+ else:
155
+ dest.unlink(missing_ok=True)
156
+ raise
157
+ backup.unlink(missing_ok=True)
158
+ return info
norain_core/log.py ADDED
@@ -0,0 +1,104 @@
1
+ """结构化日志:JSON Lines,统一脱敏,按大小轮转。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import threading
9
+ import time
10
+ import uuid
11
+ from pathlib import Path
12
+
13
+ from .redact import REDACTOR
14
+
15
+ LEVELS = {"debug": 10, "info": 20, "warn": 30, "error": 40}
16
+
17
+
18
+ def new_op_id() -> str:
19
+ return uuid.uuid4().hex[:12]
20
+
21
+
22
+ _APPEND = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_BINARY", 0)
23
+ _PATH_LOCKS: dict[str, threading.Lock] = {}
24
+ _PATH_LOCKS_GUARD = threading.Lock()
25
+
26
+
27
+ def _lock_for(path: Path) -> threading.Lock:
28
+ """同一进程里指向同一个文件的 RotatingFile 共用一把锁,否则两个对象可能同时轮转。"""
29
+ key = os.path.normcase(os.path.abspath(path))
30
+ with _PATH_LOCKS_GUARD:
31
+ return _PATH_LOCKS.setdefault(key, threading.Lock())
32
+
33
+
34
+ class RotatingFile:
35
+ def __init__(self, path: Path, *, max_bytes: int, keep: int) -> None:
36
+ self.path, self.max_bytes, self.keep = path, max_bytes, max(keep, 1)
37
+ self._lock = _lock_for(path)
38
+
39
+ def write_line(self, line: str) -> None:
40
+ """追加一行。sing-box 的每一行输出都会走这里,所以只做必要的系统调用。"""
41
+ data = (line.rstrip("\n") + "\n").encode("utf-8", "replace")
42
+ with self._lock:
43
+ try:
44
+ try:
45
+ size = os.stat(self.path).st_size
46
+ except FileNotFoundError:
47
+ size = 0
48
+ if size and size + len(data) > self.max_bytes:
49
+ try:
50
+ self._rotate()
51
+ except OSError:
52
+ pass # 轮转失败(Windows 上文件正被 `logs -f` 打开)时照常追加,不丢日志
53
+ try:
54
+ fd = os.open(self.path, _APPEND, 0o640)
55
+ except FileNotFoundError: # 日志目录只在缺失时才创建
56
+ self.path.parent.mkdir(parents=True, exist_ok=True)
57
+ fd = os.open(self.path, _APPEND, 0o640)
58
+ try:
59
+ os.write(fd, data)
60
+ finally:
61
+ os.close(fd)
62
+ except OSError:
63
+ pass # 日志写失败不能拖垮主流程
64
+
65
+ def _rotate(self) -> None:
66
+ name = self.path.name
67
+ self.path.with_name(f"{name}.{self.keep}").unlink(missing_ok=True)
68
+ for i in range(self.keep - 1, 0, -1):
69
+ src = self.path.with_name(f"{name}.{i}")
70
+ if src.exists():
71
+ os.replace(src, self.path.with_name(f"{name}.{i + 1}"))
72
+ os.replace(self.path, self.path.with_name(f"{name}.1"))
73
+
74
+
75
+ class Logger:
76
+ def __init__(self, module: str, *, op_id: str | None = None, sink: RotatingFile | None = None,
77
+ stderr: bool = True, level: str = "info") -> None:
78
+ self.module, self.op_id, self.sink = module, op_id or new_op_id(), sink
79
+ self.stderr, self.level = stderr, LEVELS.get(level, 20)
80
+
81
+ def log(self, level: str, event: str, /, **detail) -> None:
82
+ # level / event 只收位置参数:调用方常用 log.info("evt", **obj.as_dict()),
83
+ # 而 dict 里出现 "level" 或 "event" 键时,普通参数会报
84
+ # 「got multiple values for argument 'level'」。
85
+ if LEVELS[level] < self.level:
86
+ return
87
+ record = {
88
+ "time": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
89
+ "level": level,
90
+ "module": self.module,
91
+ "op_id": self.op_id,
92
+ "event": event,
93
+ "detail": REDACTOR.redact_obj(detail),
94
+ }
95
+ line = json.dumps(record, ensure_ascii=False, sort_keys=True)
96
+ if self.sink:
97
+ self.sink.write_line(line)
98
+ if self.stderr:
99
+ print(line, file=sys.stderr, flush=True)
100
+
101
+ def debug(self, event, **d): self.log("debug", event, **d)
102
+ def info(self, event, **d): self.log("info", event, **d)
103
+ def warn(self, event, **d): self.log("warn", event, **d)
104
+ def error(self, event, **d): self.log("error", event, **d)
norain_core/migrate.py ADDED
@@ -0,0 +1,86 @@
1
+ """配置 Schema 的迁移入口。
2
+
3
+ 迁移规则集中在这里,按版本逐级执行;配置模型只负责字段校验,不再各自实现
4
+ 一套迁移规则。当前 Schema 只有版本 1,所以唯一的迁移是「0 → 1」:旧配置
5
+ 没有顶层 ``schema``,补上并按版本 1 处理,同时返回可展示的 warning。
6
+
7
+ 版本策略(docs/decisions/0004 通用规则 1):
8
+
9
+ - 缺失 ``schema``:按版本 1 处理并给出 warning;
10
+ - 版本高于当前:拒绝加载,错误路径固定为 ``schema``;
11
+ - 版本低于当前:从该版本开始逐级迁移到当前版本。
12
+
13
+ 迁移只作用于内存里的字典,不写回配置文件,所以这里没有「迁移前备份原文件」
14
+ 这一步。唯一会写盘的路径是命令行的改配置(``norain/cli.py`` 的 ``_save_config``),
15
+ 它在写之前本来就会 ``atomic.backup``。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Callable
21
+ from dataclasses import dataclass
22
+
23
+ from .errors import FieldError, config_error
24
+
25
+ SCHEMA_VERSION = 1
26
+ """当前配置 Schema 版本。两端模型都从这里取,避免各写一个常量。"""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class MigrationResult:
31
+ data: dict
32
+ warnings: tuple[str, ...] = ()
33
+
34
+
35
+ def _step_0_to_1(data: dict) -> dict:
36
+ """版本 1 之前的配置没有顶层 ``schema``;补上即可,字段含义没有变化。"""
37
+ out = dict(data)
38
+ out["schema"] = 1
39
+ return out
40
+
41
+
42
+ # 版本 N 的配置 -> 版本 N+1 的配置。每一级只处理自己这一版的变化。
43
+ _STEPS: dict[int, Callable[[dict], dict]] = {0: _step_0_to_1}
44
+
45
+
46
+ def migrate(data: dict, *, current: int = SCHEMA_VERSION, source: str = "配置") -> MigrationResult:
47
+ """把输入数据迁移到当前 Schema,并返回需要展示的 warning。
48
+
49
+ 版本字段本身不可用(类型不对、为负、高于当前)时在这里就拒绝,不等字段
50
+ 校验:否则「版本更高但含有新字段」的配置会先撞上「未知字段」,用户看不到
51
+ 真正的原因。
52
+ """
53
+ raw = data.get("schema")
54
+ if raw is None:
55
+ version = 0
56
+ elif not isinstance(raw, int) or isinstance(raw, bool):
57
+ # 类型不对交给配置模型报字段类型错误,这里不抢答。
58
+ return MigrationResult(data)
59
+ elif raw < 0 or raw > current:
60
+ raise config_error([FieldError("schema", f"不支持的配置版本 {raw},本程序支持 {current}")])
61
+ elif raw == current:
62
+ return MigrationResult(data)
63
+ else:
64
+ version = raw
65
+
66
+ migrated = data
67
+ for v in range(version, current):
68
+ step = _STEPS.get(v)
69
+ if step is None:
70
+ raise config_error([FieldError("schema", f"缺少从版本 {v} 到版本 {v + 1} 的迁移规则")])
71
+ migrated = step(migrated)
72
+
73
+ warnings: tuple[str, ...] = ()
74
+ if version == 0:
75
+ warnings = (f"{source} 缺少顶层 schema,已按版本 {current} 处理;建议补上 schema = {current}",)
76
+ return MigrationResult(migrated, warnings)
77
+
78
+
79
+ def attach_warnings(cfg: object, result: MigrationResult) -> None:
80
+ """把迁移 warning 挂到配置对象上,供展示入口读取。"""
81
+ cfg._config_warnings = list(result.warnings) # noqa: SLF001 两端模型都声明了这个 PrivateAttr
82
+
83
+
84
+ def migration_warnings(cfg: object) -> list[str]:
85
+ """配置加载时的迁移 warning(两端模型通用)。"""
86
+ return list(getattr(cfg, "_config_warnings", ()) or ())
norain_core/osutil.py ADDED
@@ -0,0 +1,332 @@
1
+ """系统适配:管理员判断、外部命令、后台进程、持久环境变量、PATH、启动器、弹窗、计划任务。
2
+
3
+ Windows 与 Linux 的差异都收在这里,上层模块不直接拼系统命令。
4
+ 已实测:Windows 计划任务(schtasks 增删查)、systemd(服务端 install/update)、apt 安装前置依赖。
5
+ 其余命令按官方文档书写,未逐一实测。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shlex
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from .errors import EXIT_EXTERNAL, EXIT_PERMISSION, NorainError
18
+ from .redact import redact
19
+
20
+ IS_WINDOWS = os.name == "nt"
21
+
22
+ # 设置了这个环境变量后,任何会读写系统网络 / 防火墙 / 计划任务 / 服务 / 注册表的命令都不执行
23
+ # (返回退出码 126)。测试套件用它保证不碰真实的系统设置。
24
+ NO_SYSTEM_ENV = "NORAIN_NO_SYSTEM_CHANGES"
25
+ _SYSTEM_COMMANDS = frozenset({
26
+ "netsh", "nft", "ufw", "firewall-cmd", "iptables", "ip6tables", "schtasks", "setx", "systemctl",
27
+ "powershell", "pwsh", "reg", "sysctl", "ip", "route", "resolvectl", "networksetup", "wall",
28
+ "runuser", "useradd", "userdel",
29
+ })
30
+
31
+
32
+ def system_changes_disabled() -> bool:
33
+ return os.environ.get(NO_SYSTEM_ENV, "") not in ("", "0")
34
+
35
+
36
+ def _is_system_command(args: list[str]) -> bool:
37
+ name = Path(str(args[0])).name.lower()
38
+ return (name[:-4] if name.endswith(".exe") else name) in _SYSTEM_COMMANDS
39
+
40
+
41
+ # ---- 权限与命令 ----------------------------------------------------------------
42
+
43
+ def is_admin() -> bool:
44
+ if IS_WINDOWS:
45
+ try:
46
+ import ctypes
47
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
48
+ except Exception: # noqa: BLE001
49
+ return False
50
+ return os.geteuid() == 0
51
+
52
+
53
+ def require_admin(what: str, *, module: str = "core") -> None:
54
+ if not is_admin():
55
+ raise NorainError(f"{what}需要管理员权限", exit_code=EXIT_PERMISSION, module=module,
56
+ hint="Windows 用「以管理员身份运行」的终端;Linux 用 root 或 sudo")
57
+
58
+
59
+ def run(args: list[str], *, timeout: float = 60, input_text: str | None = None) -> subprocess.CompletedProcess:
60
+ """执行外部命令并捕获输出。命令不存在时返回 returncode=127,而不是抛异常。"""
61
+ if system_changes_disabled() and _is_system_command(args):
62
+ return subprocess.CompletedProcess(args, 126, "", f"已禁用系统命令({NO_SYSTEM_ENV}):{args[0]}")
63
+ extra = {"creationflags": subprocess.CREATE_NO_WINDOW} if IS_WINDOWS else {}
64
+ try:
65
+ return subprocess.run(args, capture_output=True, text=True, errors="replace", timeout=timeout,
66
+ input=input_text, **extra)
67
+ except FileNotFoundError:
68
+ return subprocess.CompletedProcess(args, 127, "", f"找不到命令:{args[0]}")
69
+ except subprocess.TimeoutExpired:
70
+ return subprocess.CompletedProcess(args, 124, "", f"命令超时({timeout:.0f} 秒):{args[0]}")
71
+ except OSError as e:
72
+ return subprocess.CompletedProcess(args, 126, "", f"无法执行 {args[0]}:{e}")
73
+
74
+
75
+ def run_checked(args: list[str], *, what: str, module: str = "core", timeout: float = 60) -> str:
76
+ """执行失败时抛出带具体原因的错误(不静默忽略)。"""
77
+ proc = run(args, timeout=timeout)
78
+ if proc.returncode != 0:
79
+ detail = redact((proc.stderr or proc.stdout or "").strip())[-800:]
80
+ low = detail.lower()
81
+ denied = "denied" in low or "拒绝访问" in detail or "permission" in low or "需要提升" in detail
82
+ raise NorainError(f"{what}失败({' '.join(args[:3])} 退出码 {proc.returncode}):{detail}",
83
+ exit_code=EXIT_PERMISSION if denied else EXIT_EXTERNAL, module=module,
84
+ hint="用管理员/root 权限重试" if denied else "")
85
+ return proc.stdout
86
+
87
+
88
+ def powershell(script: str, *, timeout: float = 60) -> subprocess.CompletedProcess:
89
+ return run(["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
90
+ "-Command", script], timeout=timeout)
91
+
92
+
93
+ def python_exe(*, windowless: bool = False) -> str:
94
+ """当前解释器。windowless=True 时在 Windows 上优先用 pythonw.exe(不弹控制台窗口)。"""
95
+ exe = Path(sys.executable)
96
+ if windowless and IS_WINDOWS:
97
+ w = exe.with_name("pythonw.exe")
98
+ if w.is_file():
99
+ return str(w)
100
+ return str(exe)
101
+
102
+
103
+ def spawn_detached(args: list[str], *, log_file: Path | None = None, env: dict | None = None) -> subprocess.Popen:
104
+ """启动一个脱离当前终端和进程组的后台进程。"""
105
+ extra: dict = {}
106
+ if IS_WINDOWS:
107
+ extra["creationflags"] = (subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
108
+ | subprocess.CREATE_NO_WINDOW)
109
+ else:
110
+ extra["start_new_session"] = True
111
+ if log_file is not None:
112
+ log_file.parent.mkdir(parents=True, exist_ok=True)
113
+ with open(log_file, "ab") as out:
114
+ return subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
115
+ close_fds=True, env=env, **extra)
116
+ return subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
117
+ stderr=subprocess.DEVNULL, close_fds=True, env=env, **extra)
118
+
119
+
120
+ # ---- 持久环境变量与 PATH ------------------------------------------------------
121
+
122
+ _WIN_ENV_USER = r"Environment"
123
+ _WIN_ENV_SYSTEM = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
124
+
125
+
126
+ def _win_broadcast_env() -> None:
127
+ try:
128
+ import ctypes
129
+ ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x001A, 0, "Environment", 0x0002, 3000, None)
130
+ except Exception: # noqa: BLE001 通知失败只影响已打开的窗口,新终端仍会读到
131
+ pass
132
+
133
+
134
+ def _win_env_key(system: bool, write: bool):
135
+ import winreg
136
+ if write and system_changes_disabled():
137
+ raise NorainError(f"已禁用系统改动({NO_SYSTEM_ENV}),不写注册表", exit_code=EXIT_PERMISSION, module="core")
138
+ root = winreg.HKEY_LOCAL_MACHINE if system else winreg.HKEY_CURRENT_USER
139
+ access = winreg.KEY_READ | (winreg.KEY_SET_VALUE if write else 0)
140
+ return winreg.OpenKey(root, _WIN_ENV_SYSTEM if system else _WIN_ENV_USER, 0, access)
141
+
142
+
143
+ def _profile_file(name: str, system: bool) -> Path:
144
+ if system:
145
+ return Path("/etc/profile.d") / f"{name}.sh"
146
+ return Path.home() / ".config" / name / "env.sh"
147
+
148
+
149
+ _PROFILE_HOOK = "# norain-env:{name}\n[ -f {path} ] && . {path}\n"
150
+
151
+
152
+ def persist_env(variables: dict[str, str], *, system: bool, name: str,
153
+ path_dirs: tuple[str, ...] = ()) -> list[str]:
154
+ """持久写入环境变量,并把 path_dirs 加入 PATH。返回做了什么的说明。
155
+
156
+ Windows:setx(系统级加 /M);PATH 直接改注册表,避免 setx 的 1024 字符截断。
157
+ Linux:系统级写 /etc/profile.d/<name>.sh;用户级写 ~/.config/<name>/env.sh 并在 ~/.profile 里引用。
158
+ """
159
+ done: list[str] = []
160
+ if IS_WINDOWS:
161
+ for k, v in variables.items():
162
+ run_checked(["setx", k, v, *(["/M"] if system else [])], what=f"写入环境变量 {k}")
163
+ done.append(f"setx {k}")
164
+ if path_dirs:
165
+ import winreg
166
+ with _win_env_key(system, True) as key:
167
+ try:
168
+ current, kind = winreg.QueryValueEx(key, "Path")
169
+ except FileNotFoundError:
170
+ current, kind = "", winreg.REG_EXPAND_SZ
171
+ parts = [p for p in current.split(";") if p]
172
+ lowered = {p.lower().rstrip("\\") for p in parts}
173
+ for d in path_dirs:
174
+ if d.lower().rstrip("\\") not in lowered:
175
+ parts.append(d)
176
+ done.append(f"PATH += {d}")
177
+ winreg.SetValueEx(key, "Path", 0, kind, ";".join(parts))
178
+ _win_broadcast_env()
179
+ return done
180
+ lines = [f"# 由 {name} 生成,卸载时删除"]
181
+ lines += [f"export {k}={shlex.quote(v)}" for k, v in variables.items()]
182
+ for d in path_dirs:
183
+ quoted = shlex.quote(d)
184
+ lines.append(f'case ":$PATH:" in *":{quoted}:"*) ;; *) export PATH="$PATH":{quoted} ;; esac')
185
+ f = _profile_file(name, system)
186
+ f.parent.mkdir(parents=True, exist_ok=True)
187
+ f.write_text("\n".join(lines) + "\n", encoding="utf-8")
188
+ os.chmod(f, 0o644)
189
+ done.append(f"写入 {f}")
190
+ if not system:
191
+ profile = Path.home() / ".profile"
192
+ quoted = shlex.quote(str(f))
193
+ hook = _PROFILE_HOOK.format(name=name, path=quoted)
194
+ text = profile.read_text(encoding="utf-8") if profile.exists() else ""
195
+ if f"# norain-env:{name}" not in text:
196
+ profile.write_text(text + ("" if text.endswith("\n") or not text else "\n") + hook,
197
+ encoding="utf-8")
198
+ done.append(f"在 {profile} 中引用")
199
+ return done
200
+
201
+
202
+ def unpersist_env(names: list[str], *, system: bool, name: str, path_dirs: tuple[str, ...] = ()) -> list[str]:
203
+ done: list[str] = []
204
+ if IS_WINDOWS:
205
+ import winreg
206
+ try:
207
+ with _win_env_key(system, True) as key:
208
+ for k in names:
209
+ try:
210
+ winreg.DeleteValue(key, k)
211
+ done.append(f"删除环境变量 {k}")
212
+ except FileNotFoundError:
213
+ pass
214
+ if path_dirs:
215
+ try:
216
+ current, kind = winreg.QueryValueEx(key, "Path")
217
+ drop = {d.lower().rstrip("\\") for d in path_dirs}
218
+ parts = [p for p in current.split(";") if p and p.lower().rstrip("\\") not in drop]
219
+ winreg.SetValueEx(key, "Path", 0, kind, ";".join(parts))
220
+ done.append("从 PATH 移除 Norain 目录")
221
+ except FileNotFoundError:
222
+ pass
223
+ except PermissionError:
224
+ raise NorainError("没有权限修改环境变量", exit_code=EXIT_PERMISSION, module="core") from None
225
+ _win_broadcast_env()
226
+ return done
227
+ f = _profile_file(name, system)
228
+ if f.exists():
229
+ f.unlink()
230
+ done.append(f"删除 {f}")
231
+ if not system:
232
+ profile = Path.home() / ".profile"
233
+ if profile.exists():
234
+ lines = profile.read_text(encoding="utf-8").splitlines(keepends=True)
235
+ out, skip = [], 0
236
+ for line in lines:
237
+ if line.startswith(f"# norain-env:{name}"):
238
+ skip = 1 # 连同下一行(引用行)一起删除
239
+ continue
240
+ if skip:
241
+ skip = 0
242
+ continue
243
+ out.append(line)
244
+ if len(out) != len(lines):
245
+ profile.write_text("".join(out), encoding="utf-8")
246
+ done.append(f"清理 {profile}")
247
+ return done
248
+
249
+
250
+ # ---- 启动器 --------------------------------------------------------------------
251
+
252
+ _MARK = "norain-launcher"
253
+
254
+
255
+ def write_launcher(directory: Path, name: str, module: str) -> Path:
256
+ """生成 `<name>` 命令的启动器,调用 `<当前解释器> -m <module>`。"""
257
+ directory.mkdir(parents=True, exist_ok=True)
258
+ if IS_WINDOWS:
259
+ path = directory / f"{name}.cmd"
260
+ path.write_text(f'@echo off\r\nrem {_MARK}\r\n"{sys.executable}" -m {module} %*\r\n', encoding="utf-8")
261
+ else:
262
+ path = directory / name
263
+ path.write_text(f'#!/bin/sh\n# {_MARK}\nexec "{sys.executable}" -m {module} "$@"\n', encoding="utf-8")
264
+ os.chmod(path, 0o755)
265
+ return path
266
+
267
+
268
+ def remove_launcher(directory: Path, name: str) -> bool:
269
+ """只删除本程序生成的启动器,不动 pip 等其他来源安装的同名命令。"""
270
+ path = directory / (f"{name}.cmd" if IS_WINDOWS else name)
271
+ try:
272
+ if path.is_file() and _MARK in path.read_text(encoding="utf-8", errors="replace"):
273
+ path.unlink()
274
+ return True
275
+ except OSError:
276
+ pass
277
+ return False
278
+
279
+
280
+ # ---- 弹窗 ----------------------------------------------------------------------
281
+
282
+ def popup(title: str, text: str) -> bool:
283
+ """给用户一个不阻塞调用方的提醒窗口。没有图形界面时返回 False(调用方另行写日志)。"""
284
+ if IS_WINDOWS:
285
+ # MessageBoxW 会阻塞到用户点击,所以放到独立进程里
286
+ code = ("import ctypes,sys;"
287
+ "ctypes.windll.user32.MessageBoxW(0, sys.argv[2], sys.argv[1], 0x30 | 0x1000 | 0x40000)")
288
+ try:
289
+ spawn_detached([python_exe(windowless=True), "-c", code, title, text])
290
+ return True
291
+ except OSError:
292
+ return False
293
+ for cmd in (["zenity", "--warning", "--no-wrap", f"--title={title}", f"--text={text}"],
294
+ ["kdialog", "--title", title, "--sorry", text],
295
+ ["notify-send", "-u", "critical", title, text]):
296
+ if shutil.which(cmd[0]) and (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
297
+ try:
298
+ spawn_detached(cmd)
299
+ return True
300
+ except OSError:
301
+ continue
302
+ if shutil.which("wall"):
303
+ run(["wall", f"{title}\n{text}"], timeout=5)
304
+ return True
305
+ return False
306
+
307
+
308
+ # ---- Windows 计划任务 ----------------------------------------------------------
309
+
310
+ def task_create(name: str, command: str, *, trigger: str, highest: bool, as_system: bool = False) -> None:
311
+ """trigger: ONLOGON(用户登录时)或 ONSTART(开机时)。已存在则覆盖(幂等)。"""
312
+ args = ["schtasks", "/Create", "/TN", name, "/TR", command, "/SC", trigger, "/F"]
313
+ if highest:
314
+ args += ["/RL", "HIGHEST"]
315
+ if as_system:
316
+ args += ["/RU", "SYSTEM"]
317
+ run_checked(args, what=f"注册计划任务 {name}")
318
+
319
+
320
+ def task_delete(name: str) -> bool:
321
+ if not task_exists(name):
322
+ return False
323
+ run_checked(["schtasks", "/Delete", "/TN", name, "/F"], what=f"删除计划任务 {name}")
324
+ return True
325
+
326
+
327
+ def task_exists(name: str) -> bool:
328
+ return run(["schtasks", "/Query", "/TN", name], timeout=20).returncode == 0
329
+
330
+
331
+ def quote_cmd(args: list[str]) -> str:
332
+ return subprocess.list2cmdline(args)