mihomo-cli 26.9.94 → 26.10.95
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.
- package/CHANGELOG.md +30 -0
- package/README.md +3 -3
- package/dist/index.js +315 -273
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [26.10.95] - 2026-10-01
|
|
4
|
+
|
|
5
|
+
### 修复
|
|
6
|
+
|
|
7
|
+
- **README 承诺的覆写反例现在真的报错**:`log-level+: warning`(数组操作符作用于系统默认的标量键)此前静默产出 `log-level: [warning]`,配置一路存活到内核 `-t`——类型检查只看得到订阅层,而该键只存在于系统默认配置(在合并之后才注入)。现在文件加载阶段即报错并给出改写指引
|
|
8
|
+
- **坏覆写文件在 `ow` / `status` 的结论与启动硬失败不再自相矛盾**:`~dns` 这类已移除操作符此前在 `ow`/status 被列为「已生效」(`status --json` 的 `applied` 也带着它),而 `start`/`config`/`doctor` 对同一文件硬失败。操作符形态错误(`~`/尖括号/互斥/空键)提前到加载阶段校验,诊断与合并两条路径看到同一份坏文件清单;坏文件的修复/迁移指引(hint)此前只在启动报错时可见,现在 `ow`、status 文本与 `status --json` 都带出
|
|
9
|
+
- `mihomo status` 里 JS 覆写脚本的短名显示修复:`overwrite.js` 不再显示成 `js`(正确是「主文件」),`overwrite.dns.js` 不再带 `.js` 尾巴(26.9.93 引入脚本时漏改)
|
|
10
|
+
- `mihomo doctor` 订阅新鲜度不再输出「N 分钟前**前**更新」;未来时间戳(时钟偏移)单独显示「更新时间记录异常」
|
|
11
|
+
- 自动更新整体超时后,没赶上的订阅显示灰色「跳过(更新超时,使用本地缓存)」,不再与真实网络失败同刷红叉英文(`The operation was aborted...`),也不计入失败数——超时用缓存启动本是正常降级
|
|
12
|
+
- 内核下载/解压中被强制终止后,`kernel/.tmp-*` 临时目录(可能几十 MB)不再永久残留:与原子写 `*.tmp` 同受按 1 小时龄的崩溃残留清扫,旧内核完好时无需手动 `reset kernel`
|
|
13
|
+
- 空环境 `mihomo sub remove <名字>` 改报「没有订阅」,与 `use`/`update` 同口径(旧报「未找到匹配」)
|
|
14
|
+
- `mihomo start -u 5s` 等非法选项值现在先报参数错误,不再先撞「未找到内核」
|
|
15
|
+
- 服务路径清理 root 残留内核后偶发误报「部分进程未终止」(重跑一次又正常)消除:杀进程统一走带死亡等待轮询的同一实现,不再在发出 SIGKILL 后立刻复核 pgrep;三处 root 提权(start/stop/uninstall)前都补了「为什么需要管理员密码」的预告,不再无预警弹英文 `Password:`
|
|
16
|
+
- 非交互终端(或取消密码)下 `mihomo stop`/`uninstall` 不再因一个无害的 root 属主 pid 文件残留而整体失败:无残留进程时该文件清理失败只警告(无进程读它、下次自愈),与旧服务路径「无进程不弹密码」的语义对齐;root 进程确实没杀掉仍照常报错
|
|
17
|
+
- `uninstall` 不再重复执行第二次 disable(锁内已写入并经 `print-disabled` 复核成功,第二次必成功,纯冗余)
|
|
18
|
+
|
|
19
|
+
### 新增
|
|
20
|
+
|
|
21
|
+
- `mihomo reset overwrites` 完成后,若目录里还有不被加载的疑似覆写文件(`overwrite.yml`、`overwrite.ts`、大小写变体),点名告知「N 个疑似文件保留未删」及原因(保守起见这些近失文件仍不自动删)
|
|
22
|
+
- `mihomo kernel` 首选 gh 认证查询但回退直连成功时,打印一行实际来源(spinner 说的「gh 认证通道」与实际响应不再可能悄悄不一致)
|
|
23
|
+
- 连续查看状态时连通性探测结果按端口缓存 3 秒:代理不通时连敲 `status`/`doctor` 不再每次干等 2 秒(代理状态秒级不可能翻转;`--no-probe` 不受影响)
|
|
24
|
+
- README 修正 JS 脚本可见性描述:`ctx.warn()` 与脚本执行期抛错只在 `config`/`doctor`/`start` 可见,`status` 只加载脚本、不执行函数体
|
|
25
|
+
|
|
26
|
+
### 内部
|
|
27
|
+
|
|
28
|
+
- 残留内核清理收敛为唯一入口 `cleanupAll`(服务启停/卸载/重置/游离内核共用),删除 service.ts 内与之重复的约 100 行实现(`killResidualKernels`/`cleanupRootResidue` 等);`cleanupAll`/`stop` 的 `forceSudo` 死参删除(无任何调用方传值)
|
|
29
|
+
- 删除 `withFileLock` 的 deadline 分支:过线后重新核对的还是循环顶部微秒前算过的同一个锁龄谓词,该分支永不产生行为差异;锁的心智模型回到「强夺唯一依据是锁龄」
|
|
30
|
+
- 健康轮询(每 100ms 一次、最坏 31 轮)不再白跑 `print-disabled`:健康判定从不读 disabled 字段,`getServiceStatus` 新增 `withDisabled` 选项,轮询关闭该查询以减少阻塞事件循环的 spawnSync;循环外从未被消费的首次快照一并删除
|
|
31
|
+
- 删除测试专用的第二合并入口 `deepMergeWithOverrides`,相关用例改走生产唯一入口 `applyOverwrite`
|
|
32
|
+
|
|
3
33
|
## [26.9.94] - 2026-09-30
|
|
4
34
|
|
|
5
35
|
### 破坏性变更(覆写执行顺序)
|
package/README.md
CHANGED
|
@@ -468,7 +468,7 @@ export default function (config, ctx) {
|
|
|
468
468
|
| `ctx.subscription.url` | 订阅原始 URL |
|
|
469
469
|
| `ctx.subscription.host` | 预解析的 URL hostname(解析失败为空串),按域名限定作用域时用它 |
|
|
470
470
|
| `ctx.mode` | 本次构建的运行模式:`'mixed'` 或 `'tun'` |
|
|
471
|
-
| `ctx.warn(message)` | 发一条提示进 warnings 通道,`
|
|
471
|
+
| `ctx.warn(message)` | 发一条提示进 warnings 通道,`config` / `doctor` / `start` 的输出可见(`status` 走诊断旁路、不执行脚本,看不到) |
|
|
472
472
|
|
|
473
473
|
约定与边界:
|
|
474
474
|
|
|
@@ -476,8 +476,8 @@ export default function (config, ctx) {
|
|
|
476
476
|
- **全信任**:脚本以你的用户身份运行(和 `.zshrc` 一个待遇),不做沙箱与超时——别装来路不明的覆写脚本
|
|
477
477
|
- **改不动系统锁定项**:`mixed-port`、`external-controller`、`allow-lan` 等入站与控制面键由 CLI 管理,脚本设置了会被剥除并提示(与 YAML 覆写同一条边界)
|
|
478
478
|
- **脚本先于 YAML 执行**:脚本看到的是订阅原始配置,读不到 YAML 覆写注入的内容;需要脚本处理 YAML 注入项时,把那段逻辑也写进脚本
|
|
479
|
-
-
|
|
480
|
-
-
|
|
479
|
+
- **只读命令也会加载脚本**:`ow` / `status` 扫描文件时会加载脚本,模块顶层代码随之执行(顶层只定义函数,变换都在导出函数里做);导出的变换函数在 `config` / `doctor` / `start` 构建时才调用,`status` 不调用、也不显示它的 `ctx.warn`
|
|
480
|
+
- 加载失败(语法错误、缺少导出、顶层抛错)与坏 YAML 同款姿态:`ow` / `status` 里「加载失败」可见,`config` / `start` / `doctor` 硬失败并带文件名;变换函数执行中抛错只在后三者报出(`ow` / `status` 不执行函数体)
|
|
481
481
|
- 脚本受 `mihomo ow off` 全局开关管理;想临时停用单个脚本,改个扩展名(如 `.bak`)即可
|
|
482
482
|
|
|
483
483
|
### 作用域限定(match)
|
package/dist/index.js
CHANGED
|
@@ -3550,18 +3550,24 @@ function rmrf(dir) {
|
|
|
3550
3550
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
3551
3551
|
}
|
|
3552
3552
|
function cleanupStaleTmpFiles() {
|
|
3553
|
-
|
|
3553
|
+
const cutoff = Date.now() - 60 * 60 * 1e3;
|
|
3554
|
+
for (const dir of [USER_DATA_DIR, DIRS.subscriptions, DIRS.runtime, DIRS.kernel]) {
|
|
3555
|
+
let entries;
|
|
3554
3556
|
try {
|
|
3555
|
-
|
|
3556
|
-
for (const entry of fs.readdirSync(dir)) {
|
|
3557
|
-
if (!entry.endsWith(".tmp")) continue;
|
|
3558
|
-
const full = path.join(dir, entry);
|
|
3559
|
-
try {
|
|
3560
|
-
if (fs.statSync(full).mtimeMs < cutoff) fs.rmSync(full, { force: true });
|
|
3561
|
-
} catch {
|
|
3562
|
-
}
|
|
3563
|
-
}
|
|
3557
|
+
entries = fs.readdirSync(dir);
|
|
3564
3558
|
} catch {
|
|
3559
|
+
continue;
|
|
3560
|
+
}
|
|
3561
|
+
for (const entry of entries) {
|
|
3562
|
+
const isAtomicTmpFile = entry.endsWith(".tmp");
|
|
3563
|
+
const isKernelTmpDir = dir === DIRS.kernel && entry.startsWith(".tmp-");
|
|
3564
|
+
if (!isAtomicTmpFile && !isKernelTmpDir) continue;
|
|
3565
|
+
const full = path.join(dir, entry);
|
|
3566
|
+
try {
|
|
3567
|
+
if (fs.statSync(full).mtimeMs >= cutoff) continue;
|
|
3568
|
+
fs.rmSync(full, { recursive: true, force: true });
|
|
3569
|
+
} catch {
|
|
3570
|
+
}
|
|
3565
3571
|
}
|
|
3566
3572
|
}
|
|
3567
3573
|
}
|
|
@@ -3569,7 +3575,6 @@ var LOCK_STALE_MS = 1e4;
|
|
|
3569
3575
|
var LOCK_RETRY_MS = 20;
|
|
3570
3576
|
function withFileLock(lockPath, fn, opts) {
|
|
3571
3577
|
const staleMs = opts?.staleMs ?? LOCK_STALE_MS;
|
|
3572
|
-
const deadline = Date.now() + (opts?.deadlineMs ?? LOCK_STALE_MS);
|
|
3573
3578
|
const token = `${process.pid}-${process.hrtime.bigint()}`;
|
|
3574
3579
|
let fd = null;
|
|
3575
3580
|
while (fd === null) {
|
|
@@ -3602,20 +3607,6 @@ function withFileLock(lockPath, fn, opts) {
|
|
|
3602
3607
|
}
|
|
3603
3608
|
continue;
|
|
3604
3609
|
}
|
|
3605
|
-
if (Date.now() > deadline) {
|
|
3606
|
-
let deadlineStale = false;
|
|
3607
|
-
try {
|
|
3608
|
-
deadlineStale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3609
|
-
} catch {
|
|
3610
|
-
}
|
|
3611
|
-
if (deadlineStale) {
|
|
3612
|
-
try {
|
|
3613
|
-
fs.rmSync(lockPath, { force: true });
|
|
3614
|
-
} catch {
|
|
3615
|
-
}
|
|
3616
|
-
continue;
|
|
3617
|
-
}
|
|
3618
|
-
}
|
|
3619
3610
|
sleepSyncMs(LOCK_RETRY_MS);
|
|
3620
3611
|
}
|
|
3621
3612
|
}
|
|
@@ -4060,6 +4051,13 @@ function isOverwriteFilenameTypo(filename) {
|
|
|
4060
4051
|
const lower = filename.toLowerCase();
|
|
4061
4052
|
return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower);
|
|
4062
4053
|
}
|
|
4054
|
+
function listTypoOverwriteFiles() {
|
|
4055
|
+
try {
|
|
4056
|
+
return fs3.readdirSync(USER_DATA_DIR).filter(isOverwriteFilenameTypo);
|
|
4057
|
+
} catch {
|
|
4058
|
+
return [];
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4063
4061
|
var MATCH_KEYS = /* @__PURE__ */ new Set(["name", "url-domain"]);
|
|
4064
4062
|
function normalizeMatch(raw, fileName) {
|
|
4065
4063
|
if (raw === void 0) return void 0;
|
|
@@ -4210,6 +4208,23 @@ function assertNoMetadataKeyLookalikes(config, fileName) {
|
|
|
4210
4208
|
}
|
|
4211
4209
|
}
|
|
4212
4210
|
}
|
|
4211
|
+
function assertFileLevelOperatorRules(config, fileName) {
|
|
4212
|
+
for (const rawKey of Object.keys(config)) {
|
|
4213
|
+
const parsed = parseOverrideKey(rawKey);
|
|
4214
|
+
assertValidParsedKey(rawKey, parsed);
|
|
4215
|
+
if (!parsed.arrayPrepend && !parsed.arrayAppend) continue;
|
|
4216
|
+
const base = BASE_CONFIG[parsed.key];
|
|
4217
|
+
if (base === void 0 || Array.isArray(base)) continue;
|
|
4218
|
+
const kind = base === null ? "null" : typeof base === "object" ? "\u6620\u5C04" : `\u6807\u91CF\uFF08${typeof base}\uFF09`;
|
|
4219
|
+
throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684\u952E "${rawKey}" \u7528\u4E86\u6570\u7EC4\u62FC\u63A5\uFF0C\u4F46\u7CFB\u7EDF\u914D\u7F6E "${parsed.key}" \u7684\u9ED8\u8BA4\u503C\u662F${kind}\u3001\u4E0D\u662F\u6570\u7EC4`, {
|
|
4220
|
+
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
4221
|
+
hint: [
|
|
4222
|
+
`+${parsed.key} / ${parsed.key}+ \u7528\u4E8E\u5411\u6570\u7EC4\u524D\u7F6E/\u8FFD\u52A0\u5143\u7D20\uFF08\u5982 rules+\uFF09\uFF1B\u7CFB\u7EDF\u9ED8\u8BA4\u7684 ${parsed.key} \u4E0D\u662F\u6570\u7EC4\uFF0C\u62FC\u63A5\u53EA\u4F1A\u4EA7\u51FA\u5185\u6838\u65E0\u6CD5\u89E3\u6790\u7684\u914D\u7F6E\u3002`,
|
|
4223
|
+
`\u82E5\u8981\u8986\u76D6 ${parsed.key}\uFF0C\u8BF7\u76F4\u63A5\u5199 ${parsed.key}: <\u503C>\uFF08\u8981\u6574\u5757\u66FF\u6362\u53EF\u7528 ${parsed.key}!: <\u503C>\uFF09\u3002`
|
|
4224
|
+
]
|
|
4225
|
+
});
|
|
4226
|
+
}
|
|
4227
|
+
}
|
|
4213
4228
|
function normalizeEnabled(raw, fileName) {
|
|
4214
4229
|
if (raw === void 0) return true;
|
|
4215
4230
|
if (typeof raw === "boolean") return raw;
|
|
@@ -4264,7 +4279,7 @@ function readOverwriteFiles() {
|
|
|
4264
4279
|
if (!fs3.existsSync(USER_DATA_DIR)) return { ok, broken };
|
|
4265
4280
|
const entries = fs3.readdirSync(USER_DATA_DIR);
|
|
4266
4281
|
const files = entries.filter(isOverwriteFilename).sort((a, b) => overwriteSortKey(a) < overwriteSortKey(b) ? -1 : overwriteSortKey(a) > overwriteSortKey(b) ? 1 : 0);
|
|
4267
|
-
for (const typo of entries.filter(
|
|
4282
|
+
for (const typo of entries.filter(isOverwriteFilenameTypo)) {
|
|
4268
4283
|
console.warn(
|
|
4269
4284
|
`\u8B66\u544A: "${typo}" \u4E0D\u4F1A\u88AB\u5F53\u4F5C\u8986\u5199\u6587\u4EF6\u52A0\u8F7D\uFF08\u5408\u6CD5\u6587\u4EF6\u540D: overwrite.yaml \u4E3B\u6587\u4EF6\u3001overwrite.*.yaml / overwrite.*.yml \u6269\u5C55\u6587\u4EF6\u3001overwrite.js \u4E3B\u811A\u672C\u3001overwrite.*.js / .mjs / .cjs \u6269\u5C55\u811A\u672C\uFF09\uFF1B\u82E5\u662F\u7B14\u8BEF\u8BF7\u6539\u540D`
|
|
4270
4285
|
);
|
|
@@ -4281,6 +4296,7 @@ function readOverwriteFiles() {
|
|
|
4281
4296
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
4282
4297
|
const { match, enabled, ...config } = parsed;
|
|
4283
4298
|
assertNoMetadataKeyLookalikes(config, file);
|
|
4299
|
+
assertFileLevelOperatorRules(config, file);
|
|
4284
4300
|
ok.push({ name: file, path: filePath, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
|
|
4285
4301
|
} else if (parsed !== null) {
|
|
4286
4302
|
const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
|
|
@@ -4756,8 +4772,8 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
|
4756
4772
|
}
|
|
4757
4773
|
|
|
4758
4774
|
// src/service.ts
|
|
4759
|
-
import { spawnSync as
|
|
4760
|
-
import
|
|
4775
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
4776
|
+
import fs9 from "fs";
|
|
4761
4777
|
import path7 from "path";
|
|
4762
4778
|
|
|
4763
4779
|
// src/log-files.ts
|
|
@@ -4903,6 +4919,10 @@ function listLogs() {
|
|
|
4903
4919
|
return result;
|
|
4904
4920
|
}
|
|
4905
4921
|
|
|
4922
|
+
// src/process-stop.ts
|
|
4923
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
4924
|
+
import fs8 from "fs";
|
|
4925
|
+
|
|
4906
4926
|
// src/process-probe.ts
|
|
4907
4927
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
4908
4928
|
import fs6 from "fs";
|
|
@@ -5059,6 +5079,144 @@ function sleep(ms) {
|
|
|
5059
5079
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
5060
5080
|
}
|
|
5061
5081
|
|
|
5082
|
+
// src/process-stop.ts
|
|
5083
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
5084
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
5085
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
5086
|
+
function clearRuntime() {
|
|
5087
|
+
if (fs8.existsSync(DIRS.runtime)) {
|
|
5088
|
+
rmrf(DIRS.runtime);
|
|
5089
|
+
}
|
|
5090
|
+
ensureDirs();
|
|
5091
|
+
}
|
|
5092
|
+
function warnPidCleanupFailed(outcome) {
|
|
5093
|
+
if (outcome === null) return;
|
|
5094
|
+
const cancelled = outcome === "cancelled" || outcome instanceof SudoAuthError;
|
|
5095
|
+
const reason = cancelled ? "sudo \u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : "sudo \u6267\u884C\u5931\u8D25";
|
|
5096
|
+
console.warn(colors.yellow(`\u8B66\u544A: root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${reason}\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
5097
|
+
}
|
|
5098
|
+
function pidCleanupError(outcome) {
|
|
5099
|
+
if (outcome === "cancelled") return new SudoAuthError();
|
|
5100
|
+
if (outcome === "failed") return new Error("\u5220\u9664 root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u5931\u8D25");
|
|
5101
|
+
return null;
|
|
5102
|
+
}
|
|
5103
|
+
function clearPid() {
|
|
5104
|
+
if (!fs8.existsSync(PATHS.pidFile)) return null;
|
|
5105
|
+
if (isPidFileOwnedByRoot()) {
|
|
5106
|
+
const result = spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
5107
|
+
if (result.status === 1) return "cancelled";
|
|
5108
|
+
if (result.error || result.status !== 0) {
|
|
5109
|
+
console.warn("\u8B66\u544A: root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08sudo \u5931\u8D25\u6216\u5DF2\u53D6\u6D88\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5");
|
|
5110
|
+
return "failed";
|
|
5111
|
+
}
|
|
5112
|
+
return null;
|
|
5113
|
+
}
|
|
5114
|
+
try {
|
|
5115
|
+
fs8.unlinkSync(PATHS.pidFile);
|
|
5116
|
+
} catch {
|
|
5117
|
+
}
|
|
5118
|
+
return null;
|
|
5119
|
+
}
|
|
5120
|
+
function killProcess(pid) {
|
|
5121
|
+
try {
|
|
5122
|
+
process.kill(pid, "SIGKILL");
|
|
5123
|
+
return true;
|
|
5124
|
+
} catch {
|
|
5125
|
+
return false;
|
|
5126
|
+
}
|
|
5127
|
+
}
|
|
5128
|
+
function killAllMihomo() {
|
|
5129
|
+
try {
|
|
5130
|
+
const result = spawnSync4("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
|
|
5131
|
+
if (result.error) return false;
|
|
5132
|
+
return result.status === 0 || result.status === 1;
|
|
5133
|
+
} catch {
|
|
5134
|
+
return false;
|
|
5135
|
+
}
|
|
5136
|
+
}
|
|
5137
|
+
function buildKernelCleanupScript() {
|
|
5138
|
+
return [
|
|
5139
|
+
"#!/bin/bash",
|
|
5140
|
+
// pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
|
|
5141
|
+
`pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
|
|
5142
|
+
"rc=$?",
|
|
5143
|
+
"[ $rc -le 1 ] || exit 2",
|
|
5144
|
+
`rm -f ${shellQuote(PATHS.pidFile)} 2>/dev/null || true`,
|
|
5145
|
+
"exit 0",
|
|
5146
|
+
""
|
|
5147
|
+
].join("\n");
|
|
5148
|
+
}
|
|
5149
|
+
async function cleanupAll() {
|
|
5150
|
+
const pids = getMihomoPids();
|
|
5151
|
+
if (pids.length === 0) {
|
|
5152
|
+
return { killed: 0, failed: 0, remaining: [], sudoError: pidCleanupError(clearPid()) };
|
|
5153
|
+
}
|
|
5154
|
+
let killedCount = 0;
|
|
5155
|
+
const failedPids = [];
|
|
5156
|
+
let sudoError = null;
|
|
5157
|
+
if (pids.some((p) => isProcessRoot(p))) {
|
|
5158
|
+
console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${pids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
|
|
5159
|
+
try {
|
|
5160
|
+
runSudoScript(buildKernelCleanupScript(), {
|
|
5161
|
+
action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
|
|
5162
|
+
file: "cleanup-residue.sh",
|
|
5163
|
+
codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
|
|
5164
|
+
});
|
|
5165
|
+
killedCount = pids.length;
|
|
5166
|
+
} catch (e) {
|
|
5167
|
+
sudoError = e;
|
|
5168
|
+
}
|
|
5169
|
+
} else if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
5170
|
+
if (killAllMihomo()) {
|
|
5171
|
+
killedCount = pids.length;
|
|
5172
|
+
} else {
|
|
5173
|
+
failedPids.push(...pids);
|
|
5174
|
+
}
|
|
5175
|
+
} else {
|
|
5176
|
+
for (const pid of pids) {
|
|
5177
|
+
if (!isMihomoProcess(pid)) {
|
|
5178
|
+
killedCount++;
|
|
5179
|
+
continue;
|
|
5180
|
+
}
|
|
5181
|
+
if (killProcess(pid)) {
|
|
5182
|
+
killedCount++;
|
|
5183
|
+
} else {
|
|
5184
|
+
failedPids.push(pid);
|
|
5185
|
+
}
|
|
5186
|
+
}
|
|
5187
|
+
}
|
|
5188
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
5189
|
+
if (getMihomoPids().length === 0) break;
|
|
5190
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
5191
|
+
}
|
|
5192
|
+
const pidError = pidCleanupError(clearPid());
|
|
5193
|
+
if (!sudoError) sudoError = pidError;
|
|
5194
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids(), sudoError };
|
|
5195
|
+
}
|
|
5196
|
+
async function stop() {
|
|
5197
|
+
const allPids = getMihomoPids();
|
|
5198
|
+
if (allPids.length === 0) {
|
|
5199
|
+
warnPidCleanupFailed(clearPid());
|
|
5200
|
+
clearRuntime();
|
|
5201
|
+
return { success: true, notRunning: true };
|
|
5202
|
+
}
|
|
5203
|
+
const result = await cleanupAll();
|
|
5204
|
+
if (result.remaining.length === 0 && result.sudoError) {
|
|
5205
|
+
warnPidCleanupFailed(result.sudoError);
|
|
5206
|
+
}
|
|
5207
|
+
const remaining = getMihomoPids();
|
|
5208
|
+
if (remaining.length > 0) {
|
|
5209
|
+
console.log("");
|
|
5210
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5211
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5212
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
5213
|
+
console.log("");
|
|
5214
|
+
return { success: true, remaining };
|
|
5215
|
+
}
|
|
5216
|
+
clearRuntime();
|
|
5217
|
+
return { success: true, killed: result.killed };
|
|
5218
|
+
}
|
|
5219
|
+
|
|
5062
5220
|
// src/service.ts
|
|
5063
5221
|
function assertServiceLabelSafe() {
|
|
5064
5222
|
if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
|
|
@@ -5082,10 +5240,10 @@ function bootstrapDomain() {
|
|
|
5082
5240
|
return `gui/${process.getuid?.() ?? 0}`;
|
|
5083
5241
|
}
|
|
5084
5242
|
function isServiceInstalled() {
|
|
5085
|
-
return
|
|
5243
|
+
return fs9.existsSync(PATHS.userAgentPlist);
|
|
5086
5244
|
}
|
|
5087
5245
|
function detectLegacySystemInstall() {
|
|
5088
|
-
return
|
|
5246
|
+
return fs9.existsSync(PATHS.systemDaemonPlist);
|
|
5089
5247
|
}
|
|
5090
5248
|
function parseServicePrint(output) {
|
|
5091
5249
|
const stateMatch = output.match(/^\tstate = (.+)$/m);
|
|
@@ -5111,7 +5269,7 @@ function parseDisabledList(output, label) {
|
|
|
5111
5269
|
var LAUNCHCTL_NOT_LOADED = 113;
|
|
5112
5270
|
function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5113
5271
|
try {
|
|
5114
|
-
const result =
|
|
5272
|
+
const result = spawnSync5("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
|
|
5115
5273
|
return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
|
|
5116
5274
|
} catch {
|
|
5117
5275
|
return { status: null, stdout: "", stderr: "" };
|
|
@@ -5128,7 +5286,8 @@ function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
|
5128
5286
|
assertLaunchctlQueryOk(out.status, "print-disabled");
|
|
5129
5287
|
return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
|
|
5130
5288
|
}
|
|
5131
|
-
function getServiceStatus() {
|
|
5289
|
+
function getServiceStatus(options = {}) {
|
|
5290
|
+
const withDisabled = options.withDisabled !== false;
|
|
5132
5291
|
const installed = isServiceInstalled();
|
|
5133
5292
|
const print = runLaunchctl(["print", serviceTarget()]);
|
|
5134
5293
|
assertLaunchctlQueryOk(print.status, "print");
|
|
@@ -5137,27 +5296,27 @@ function getServiceStatus() {
|
|
|
5137
5296
|
return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
|
|
5138
5297
|
}
|
|
5139
5298
|
const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
|
|
5140
|
-
const disabled = isServiceDisabledInLaunchd();
|
|
5299
|
+
const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
|
|
5141
5300
|
return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
|
|
5142
5301
|
}
|
|
5143
5302
|
async function waitServiceHealthy() {
|
|
5144
5303
|
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
5145
5304
|
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
5146
|
-
let last
|
|
5147
|
-
|
|
5305
|
+
let last;
|
|
5306
|
+
do {
|
|
5148
5307
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5149
|
-
last = getServiceStatus();
|
|
5308
|
+
last = getServiceStatus({ withDisabled: false });
|
|
5150
5309
|
if (isCrashed(last)) {
|
|
5151
5310
|
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5152
5311
|
}
|
|
5153
5312
|
if (!last.loaded) {
|
|
5154
5313
|
return { healthy: false, crashed: false, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5155
5314
|
}
|
|
5156
|
-
}
|
|
5315
|
+
} while (Date.now() < deadline);
|
|
5157
5316
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
5158
5317
|
while (Date.now() < graceDeadline) {
|
|
5159
5318
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5160
|
-
last = getServiceStatus();
|
|
5319
|
+
last = getServiceStatus({ withDisabled: false });
|
|
5161
5320
|
if (isCrashed(last)) {
|
|
5162
5321
|
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5163
5322
|
}
|
|
@@ -5211,18 +5370,18 @@ ${argsXml}
|
|
|
5211
5370
|
`;
|
|
5212
5371
|
}
|
|
5213
5372
|
function ensureServiceSymlink() {
|
|
5214
|
-
if (!
|
|
5373
|
+
if (!fs9.existsSync(PATHS.mihomoBinary)) {
|
|
5215
5374
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
5216
5375
|
}
|
|
5217
5376
|
try {
|
|
5218
|
-
const current =
|
|
5377
|
+
const current = fs9.readlinkSync(PATHS.serviceBinary);
|
|
5219
5378
|
if (current === "mihomo") return;
|
|
5220
|
-
|
|
5379
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5221
5380
|
} catch (e) {
|
|
5222
5381
|
const code = e.code;
|
|
5223
5382
|
if (code === "EINVAL") {
|
|
5224
5383
|
try {
|
|
5225
|
-
|
|
5384
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5226
5385
|
} catch {
|
|
5227
5386
|
}
|
|
5228
5387
|
} else if (code !== "ENOENT") {
|
|
@@ -5230,12 +5389,12 @@ function ensureServiceSymlink() {
|
|
|
5230
5389
|
}
|
|
5231
5390
|
}
|
|
5232
5391
|
try {
|
|
5233
|
-
|
|
5392
|
+
fs9.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
5234
5393
|
} catch (e) {
|
|
5235
5394
|
if (e.code !== "EEXIST") throw e;
|
|
5236
5395
|
let existing;
|
|
5237
5396
|
try {
|
|
5238
|
-
existing =
|
|
5397
|
+
existing = fs9.readlinkSync(PATHS.serviceBinary);
|
|
5239
5398
|
} catch {
|
|
5240
5399
|
throw e;
|
|
5241
5400
|
}
|
|
@@ -5284,64 +5443,33 @@ async function waitUntilUnloaded(target = serviceTarget()) {
|
|
|
5284
5443
|
hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
|
|
5285
5444
|
});
|
|
5286
5445
|
}
|
|
5287
|
-
function
|
|
5288
|
-
const
|
|
5289
|
-
|
|
5290
|
-
const script = [
|
|
5291
|
-
"#!/bin/bash",
|
|
5292
|
-
// pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
|
|
5293
|
-
// (与 killAllMihomo 只收 0/1 同一原则)
|
|
5294
|
-
`pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
|
|
5295
|
-
"rc=$?",
|
|
5296
|
-
"[ $rc -le 1 ] || exit 2",
|
|
5297
|
-
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
5298
|
-
"exit 0",
|
|
5299
|
-
""
|
|
5300
|
-
].join("\n");
|
|
5301
|
-
runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh", codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" } });
|
|
5302
|
-
}
|
|
5303
|
-
function buildRootResidueCleanupError(e, ctx, rootPids) {
|
|
5304
|
-
const cancelled = e instanceof SudoAuthError;
|
|
5305
|
-
const hasKernelResidue = rootPids.length > 0;
|
|
5446
|
+
function buildRootResidueCleanupError(result, ctx) {
|
|
5447
|
+
const cancelled = result.sudoError instanceof SudoAuthError;
|
|
5448
|
+
const hasKernelResidue = result.remaining.length > 0;
|
|
5306
5449
|
const hint = [
|
|
5307
5450
|
ctx.mainOutcome,
|
|
5308
|
-
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${
|
|
5451
|
+
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${result.remaining.join(", ")}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u88AB\u6E05\u7406: ${PATHS.pidFile}`,
|
|
5309
5452
|
`\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`
|
|
5310
5453
|
];
|
|
5311
5454
|
hint.push(hasKernelResidue ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5312
5455
|
if (cancelled) {
|
|
5313
5456
|
return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
|
|
5314
5457
|
}
|
|
5315
|
-
return new CliError(
|
|
5458
|
+
return new CliError(result.sudoError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5316
5459
|
}
|
|
5317
|
-
function
|
|
5318
|
-
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
return [];
|
|
5322
|
-
}
|
|
5323
|
-
}
|
|
5324
|
-
function cleanupRootResidueOrThrow(ctx) {
|
|
5325
|
-
try {
|
|
5326
|
-
cleanupRootResidue();
|
|
5327
|
-
} catch (e) {
|
|
5328
|
-
if (e instanceof CliError) throw e;
|
|
5329
|
-
throw buildRootResidueCleanupError(e, ctx, currentRootResiduePids());
|
|
5330
|
-
}
|
|
5460
|
+
function classifyResidueCleanup(result) {
|
|
5461
|
+
if (result.remaining.length > 0 && result.sudoError) return "throw";
|
|
5462
|
+
if (result.sudoError) return "warn";
|
|
5463
|
+
return "ok";
|
|
5331
5464
|
}
|
|
5332
|
-
function
|
|
5333
|
-
const
|
|
5334
|
-
|
|
5335
|
-
|
|
5336
|
-
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
process.kill(pid, "SIGKILL");
|
|
5341
|
-
} catch {
|
|
5342
|
-
}
|
|
5343
|
-
}
|
|
5344
|
-
if (rootPids.length > 0) cleanupRootResidueOrThrow(ctx);
|
|
5465
|
+
async function cleanupKernelsOrThrow(ctx) {
|
|
5466
|
+
const result = await cleanupAll();
|
|
5467
|
+
const verdict = classifyResidueCleanup(result);
|
|
5468
|
+
if (verdict === "ok") return;
|
|
5469
|
+
const err = buildRootResidueCleanupError(result, ctx);
|
|
5470
|
+
if (verdict === "throw") throw err;
|
|
5471
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
|
|
5472
|
+
for (const line of err.hint) console.warn(colors.gray(line));
|
|
5345
5473
|
}
|
|
5346
5474
|
async function installService(wasRunning) {
|
|
5347
5475
|
assertServiceLabelSafe();
|
|
@@ -5351,7 +5479,7 @@ async function installService(wasRunning) {
|
|
|
5351
5479
|
const stagePath = PATHS.servicePlistStage;
|
|
5352
5480
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5353
5481
|
try {
|
|
5354
|
-
const lint =
|
|
5482
|
+
const lint = spawnSync5("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
|
|
5355
5483
|
if (lint.status !== 0) {
|
|
5356
5484
|
throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
|
|
5357
5485
|
hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
|
|
@@ -5359,9 +5487,9 @@ async function installService(wasRunning) {
|
|
|
5359
5487
|
}
|
|
5360
5488
|
bootoutService();
|
|
5361
5489
|
await waitUntilUnloaded();
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5490
|
+
fs9.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
5491
|
+
fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
5492
|
+
fs9.chmodSync(PATHS.userAgentPlist, 420);
|
|
5365
5493
|
if (wasRunning) {
|
|
5366
5494
|
withFileLock(PATHS.serviceLock, () => {
|
|
5367
5495
|
if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
|
|
@@ -5374,7 +5502,7 @@ async function installService(wasRunning) {
|
|
|
5374
5502
|
}
|
|
5375
5503
|
} finally {
|
|
5376
5504
|
try {
|
|
5377
|
-
|
|
5505
|
+
fs9.unlinkSync(stagePath);
|
|
5378
5506
|
} catch {
|
|
5379
5507
|
}
|
|
5380
5508
|
}
|
|
@@ -5385,7 +5513,7 @@ async function installService(wasRunning) {
|
|
|
5385
5513
|
}
|
|
5386
5514
|
function readStopEpoch() {
|
|
5387
5515
|
try {
|
|
5388
|
-
const n = Number.parseInt(
|
|
5516
|
+
const n = Number.parseInt(fs9.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
5389
5517
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
5390
5518
|
} catch {
|
|
5391
5519
|
return 0;
|
|
@@ -5418,7 +5546,7 @@ async function startService() {
|
|
|
5418
5546
|
if (!isServiceInstalled()) {
|
|
5419
5547
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5420
5548
|
}
|
|
5421
|
-
if (!
|
|
5549
|
+
if (!fs9.existsSync(PATHS.configFile)) {
|
|
5422
5550
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
|
|
5423
5551
|
}
|
|
5424
5552
|
if (getConfigInfo()?.tun) {
|
|
@@ -5432,7 +5560,7 @@ async function startService() {
|
|
|
5432
5560
|
]
|
|
5433
5561
|
});
|
|
5434
5562
|
}
|
|
5435
|
-
|
|
5563
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
|
|
5436
5564
|
bootoutService();
|
|
5437
5565
|
await waitUntilUnloaded();
|
|
5438
5566
|
rotateAndCleanupLogs();
|
|
@@ -5464,7 +5592,7 @@ async function stopService() {
|
|
|
5464
5592
|
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5465
5593
|
});
|
|
5466
5594
|
await waitUntilUnloaded();
|
|
5467
|
-
|
|
5595
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
|
|
5468
5596
|
}
|
|
5469
5597
|
async function uninstallService() {
|
|
5470
5598
|
assertServiceLabelSafe();
|
|
@@ -5474,14 +5602,13 @@ async function uninstallService() {
|
|
|
5474
5602
|
});
|
|
5475
5603
|
await waitUntilUnloaded();
|
|
5476
5604
|
try {
|
|
5477
|
-
|
|
5605
|
+
fs9.rmSync(PATHS.userAgentPlist, { force: true });
|
|
5478
5606
|
} catch (e) {
|
|
5479
5607
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5480
5608
|
}
|
|
5481
|
-
|
|
5482
|
-
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5609
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5483
5610
|
try {
|
|
5484
|
-
|
|
5611
|
+
fs9.rmSync(PATHS.serviceBinary, { force: true });
|
|
5485
5612
|
} catch {
|
|
5486
5613
|
}
|
|
5487
5614
|
}
|
|
@@ -5527,7 +5654,7 @@ function cleanupLegacyInstallOrThrow() {
|
|
|
5527
5654
|
}
|
|
5528
5655
|
function logOversized() {
|
|
5529
5656
|
try {
|
|
5530
|
-
return
|
|
5657
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5531
5658
|
} catch {
|
|
5532
5659
|
return false;
|
|
5533
5660
|
}
|
|
@@ -5547,7 +5674,7 @@ async function tryHotReload() {
|
|
|
5547
5674
|
const info = await probe.json();
|
|
5548
5675
|
if (typeof info?.version !== "string") return false;
|
|
5549
5676
|
const port = getPorts().controller;
|
|
5550
|
-
const lsofResult =
|
|
5677
|
+
const lsofResult = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5551
5678
|
if (lsofResult.status !== 0) return false;
|
|
5552
5679
|
const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
|
|
5553
5680
|
if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
|
|
@@ -5577,8 +5704,8 @@ async function restartService() {
|
|
|
5577
5704
|
if (logOversized()) {
|
|
5578
5705
|
const archiveFile = allocateArchivePath();
|
|
5579
5706
|
try {
|
|
5580
|
-
|
|
5581
|
-
|
|
5707
|
+
fs9.copyFileSync(PATHS.logFile, archiveFile);
|
|
5708
|
+
fs9.writeFileSync(PATHS.logFile, "");
|
|
5582
5709
|
} catch {
|
|
5583
5710
|
}
|
|
5584
5711
|
}
|
|
@@ -6129,12 +6256,14 @@ async function tryUpdateOne(sub, signal) {
|
|
|
6129
6256
|
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
6130
6257
|
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
6131
6258
|
} catch (e) {
|
|
6132
|
-
return { name: sub.name, success: false, error: e.message };
|
|
6259
|
+
return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
|
|
6133
6260
|
}
|
|
6134
6261
|
}
|
|
6135
6262
|
function printUpdateResult(r) {
|
|
6136
6263
|
if (r.success) {
|
|
6137
6264
|
console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
|
|
6265
|
+
} else if (r.aborted) {
|
|
6266
|
+
console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
|
|
6138
6267
|
} else {
|
|
6139
6268
|
console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
|
|
6140
6269
|
}
|
|
@@ -6173,11 +6302,13 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6173
6302
|
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
6174
6303
|
}
|
|
6175
6304
|
let updatedCount = 0;
|
|
6305
|
+
let failedCount = 0;
|
|
6176
6306
|
for (const r of results) {
|
|
6177
6307
|
if (r.success) updatedCount++;
|
|
6308
|
+
else if (!r.aborted) failedCount++;
|
|
6178
6309
|
printUpdateResult(r);
|
|
6179
6310
|
}
|
|
6180
|
-
return { total: staleSubs.length, updated: updatedCount, failed:
|
|
6311
|
+
return { total: staleSubs.length, updated: updatedCount, failed: failedCount };
|
|
6181
6312
|
}
|
|
6182
6313
|
|
|
6183
6314
|
// src/commands/config.ts
|
|
@@ -6268,7 +6399,7 @@ function viewLogWithTail(logPath, options) {
|
|
|
6268
6399
|
import readline from "readline";
|
|
6269
6400
|
|
|
6270
6401
|
// src/process-start.ts
|
|
6271
|
-
import
|
|
6402
|
+
import fs10 from "fs";
|
|
6272
6403
|
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6273
6404
|
function buildTunLaunchScript() {
|
|
6274
6405
|
const binary = shellQuote(PATHS.mihomoBinary);
|
|
@@ -6335,10 +6466,10 @@ exit 2
|
|
|
6335
6466
|
}
|
|
6336
6467
|
async function startTun() {
|
|
6337
6468
|
ensureDirs();
|
|
6338
|
-
if (!
|
|
6469
|
+
if (!fs10.existsSync(PATHS.mihomoBinary)) {
|
|
6339
6470
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
6340
6471
|
}
|
|
6341
|
-
if (!
|
|
6472
|
+
if (!fs10.existsSync(PATHS.configFile)) {
|
|
6342
6473
|
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
6343
6474
|
}
|
|
6344
6475
|
if (getServiceStatus().loaded) {
|
|
@@ -6348,12 +6479,12 @@ async function startTun() {
|
|
|
6348
6479
|
}
|
|
6349
6480
|
rotateAndCleanupLogs();
|
|
6350
6481
|
const logFile = PATHS.logFile;
|
|
6351
|
-
if (
|
|
6482
|
+
if (fs10.existsSync(logFile)) {
|
|
6352
6483
|
try {
|
|
6353
|
-
|
|
6484
|
+
fs10.accessSync(logFile, fs10.constants.W_OK);
|
|
6354
6485
|
} catch {
|
|
6355
6486
|
try {
|
|
6356
|
-
|
|
6487
|
+
fs10.unlinkSync(logFile);
|
|
6357
6488
|
} catch {
|
|
6358
6489
|
}
|
|
6359
6490
|
}
|
|
@@ -6456,7 +6587,7 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
6456
6587
|
}
|
|
6457
6588
|
|
|
6458
6589
|
// src/system-proxy.ts
|
|
6459
|
-
import { spawnSync as
|
|
6590
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6460
6591
|
function isLoopbackHost(host) {
|
|
6461
6592
|
const h = host.toLowerCase();
|
|
6462
6593
|
return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
|
|
@@ -6518,7 +6649,7 @@ function summarizeSystemProxy(view, mixedPort) {
|
|
|
6518
6649
|
function detectSystemProxy(mixedPort) {
|
|
6519
6650
|
let r;
|
|
6520
6651
|
try {
|
|
6521
|
-
r =
|
|
6652
|
+
r = spawnSync6("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
|
|
6522
6653
|
} catch {
|
|
6523
6654
|
return null;
|
|
6524
6655
|
}
|
|
@@ -6561,7 +6692,17 @@ function isProbeSuccessStatus(code) {
|
|
|
6561
6692
|
return code !== null && code >= 200 && code < 300;
|
|
6562
6693
|
}
|
|
6563
6694
|
var PROBE_TIMEOUT_MS = 2e3;
|
|
6695
|
+
var PROBE_CACHE_TTL_MS = 3e3;
|
|
6696
|
+
var probeCache = null;
|
|
6564
6697
|
async function probeProxyConnectivity(port) {
|
|
6698
|
+
if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
|
|
6699
|
+
return probeCache.result;
|
|
6700
|
+
}
|
|
6701
|
+
const result = await probeProxyConnectivityUncached(port);
|
|
6702
|
+
probeCache = { port, at: Date.now(), result };
|
|
6703
|
+
return result;
|
|
6704
|
+
}
|
|
6705
|
+
async function probeProxyConnectivityUncached(port) {
|
|
6565
6706
|
const start = Date.now();
|
|
6566
6707
|
try {
|
|
6567
6708
|
const { stdout } = await execFileAsync(
|
|
@@ -6640,8 +6781,10 @@ function buildStatusJson(args) {
|
|
|
6640
6781
|
// 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
|
|
6641
6782
|
// 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
|
|
6642
6783
|
applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : [],
|
|
6643
|
-
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors
|
|
6644
|
-
|
|
6784
|
+
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
|
|
6785
|
+
// hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
|
|
6786
|
+
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
6787
|
+
errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
|
|
6645
6788
|
},
|
|
6646
6789
|
service: {
|
|
6647
6790
|
installed: args.service.installed,
|
|
@@ -6785,7 +6928,7 @@ async function printStatus(args = []) {
|
|
|
6785
6928
|
console.log("");
|
|
6786
6929
|
}
|
|
6787
6930
|
function shortOverwriteName(name) {
|
|
6788
|
-
return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
6931
|
+
return name.replace(/\.(?:ya?ml|m?js|cjs)$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
6789
6932
|
}
|
|
6790
6933
|
function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
6791
6934
|
if (!enabled) {
|
|
@@ -6810,6 +6953,7 @@ function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
|
6810
6953
|
}
|
|
6811
6954
|
for (const b of broken) {
|
|
6812
6955
|
console.log(colors.red(` ${b.message}`));
|
|
6956
|
+
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
6813
6957
|
}
|
|
6814
6958
|
}
|
|
6815
6959
|
function printServiceLines(service, legacy) {
|
|
@@ -6846,12 +6990,12 @@ async function cmdStart(args) {
|
|
|
6846
6990
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
6847
6991
|
assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
|
|
6848
6992
|
const targetMode = resolveStartMode(args);
|
|
6993
|
+
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6994
|
+
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6849
6995
|
let disabledAutoStartForTun = false;
|
|
6850
6996
|
if (!hasKernel()) {
|
|
6851
6997
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
6852
6998
|
}
|
|
6853
|
-
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6854
|
-
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6855
6999
|
const serviceBefore = getServiceStatus();
|
|
6856
7000
|
if (targetMode === "tun") {
|
|
6857
7001
|
if (detectLegacySystemInstall()) {
|
|
@@ -7032,12 +7176,12 @@ async function cmdDirectory(args) {
|
|
|
7032
7176
|
}
|
|
7033
7177
|
|
|
7034
7178
|
// src/commands/doctor.ts
|
|
7035
|
-
import { spawnSync as
|
|
7036
|
-
import
|
|
7179
|
+
import { spawnSync as spawnSync8 } from "child_process";
|
|
7180
|
+
import fs12 from "fs";
|
|
7037
7181
|
|
|
7038
7182
|
// src/kernel.ts
|
|
7039
|
-
import { execFile as execFile3, spawnSync as
|
|
7040
|
-
import
|
|
7183
|
+
import { execFile as execFile3, spawnSync as spawnSync7 } from "child_process";
|
|
7184
|
+
import fs11 from "fs";
|
|
7041
7185
|
import path8 from "path";
|
|
7042
7186
|
import { promisify as promisify3 } from "util";
|
|
7043
7187
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7079,7 +7223,7 @@ function resolveDownloadChannel(input) {
|
|
|
7079
7223
|
return { kind: "direct" };
|
|
7080
7224
|
}
|
|
7081
7225
|
function hasGh() {
|
|
7082
|
-
const result =
|
|
7226
|
+
const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
|
|
7083
7227
|
return !result.error && result.status === 0;
|
|
7084
7228
|
}
|
|
7085
7229
|
function getArch() {
|
|
@@ -7174,6 +7318,7 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
|
|
|
7174
7318
|
return await getLatestReleaseViaGh(repo, opts.signal);
|
|
7175
7319
|
} catch (e) {
|
|
7176
7320
|
if (opts.signal?.aborted) throw e;
|
|
7321
|
+
opts.onGhFallback?.();
|
|
7177
7322
|
}
|
|
7178
7323
|
}
|
|
7179
7324
|
if (opts.proxy) {
|
|
@@ -7206,7 +7351,12 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
|
|
|
7206
7351
|
}
|
|
7207
7352
|
async function checkUpdate(opts) {
|
|
7208
7353
|
const currentVersion = getKernelVersion();
|
|
7209
|
-
|
|
7354
|
+
let ghFallbackToDirect = false;
|
|
7355
|
+
const optsWithFallbackNote = {
|
|
7356
|
+
...opts,
|
|
7357
|
+
onGhFallback: opts.useGh && !opts.proxy ? () => ghFallbackToDirect = true : void 0
|
|
7358
|
+
};
|
|
7359
|
+
const latest = await getLatestRelease(GITHUB_REPO, optsWithFallbackNote);
|
|
7210
7360
|
const latestVersion = latest.tag_name;
|
|
7211
7361
|
let needsUpdate = false;
|
|
7212
7362
|
const currentDisplay = currentVersion || "\u672A\u5B89\u88C5";
|
|
@@ -7224,7 +7374,8 @@ async function checkUpdate(opts) {
|
|
|
7224
7374
|
latest: latestVersion,
|
|
7225
7375
|
needsUpdate,
|
|
7226
7376
|
assets: latest.assets,
|
|
7227
|
-
release: latest
|
|
7377
|
+
release: latest,
|
|
7378
|
+
ghFallbackToDirect
|
|
7228
7379
|
};
|
|
7229
7380
|
}
|
|
7230
7381
|
function buildKernelCurlArgs(args) {
|
|
@@ -7272,7 +7423,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7272
7423
|
}
|
|
7273
7424
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7274
7425
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7275
|
-
const tempDir =
|
|
7426
|
+
const tempDir = fs11.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
7276
7427
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
7277
7428
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7278
7429
|
try {
|
|
@@ -7286,7 +7437,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7286
7437
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
|
|
7287
7438
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7288
7439
|
}
|
|
7289
|
-
const ghResult =
|
|
7440
|
+
const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7290
7441
|
stdio: "inherit",
|
|
7291
7442
|
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7292
7443
|
});
|
|
@@ -7304,7 +7455,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7304
7455
|
}
|
|
7305
7456
|
} else {
|
|
7306
7457
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7307
|
-
const curlResult =
|
|
7458
|
+
const curlResult = spawnSync7(
|
|
7308
7459
|
"curl",
|
|
7309
7460
|
buildKernelCurlArgs({
|
|
7310
7461
|
url: downloadUrl,
|
|
@@ -7327,11 +7478,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7327
7478
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7328
7479
|
}
|
|
7329
7480
|
}
|
|
7330
|
-
if (!
|
|
7481
|
+
if (!fs11.existsSync(tempPath)) {
|
|
7331
7482
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7332
7483
|
}
|
|
7333
7484
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7334
|
-
const actual =
|
|
7485
|
+
const actual = fs11.statSync(tempPath).size;
|
|
7335
7486
|
if (actual !== asset.size) {
|
|
7336
7487
|
throw new Error(
|
|
7337
7488
|
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
@@ -7346,15 +7497,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7346
7497
|
throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
|
|
7347
7498
|
}
|
|
7348
7499
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
7349
|
-
const gzipResult =
|
|
7500
|
+
const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7350
7501
|
if (gzipResult.error) throw gzipResult.error;
|
|
7351
7502
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7352
|
-
|
|
7503
|
+
fs11.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
|
|
7353
7504
|
if (progressCallback) {
|
|
7354
7505
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7355
7506
|
}
|
|
7356
|
-
|
|
7357
|
-
const check =
|
|
7507
|
+
fs11.chmodSync(foundBinary, 493);
|
|
7508
|
+
const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7358
7509
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7359
7510
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7360
7511
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
|
|
@@ -7370,12 +7521,12 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7370
7521
|
}
|
|
7371
7522
|
}
|
|
7372
7523
|
const targetPath = PATHS.mihomoBinary;
|
|
7373
|
-
|
|
7374
|
-
|
|
7524
|
+
fs11.renameSync(foundBinary, targetPath);
|
|
7525
|
+
fs11.chmodSync(targetPath, 493);
|
|
7375
7526
|
return { version: latest.tag_name, path: targetPath };
|
|
7376
7527
|
} finally {
|
|
7377
7528
|
try {
|
|
7378
|
-
|
|
7529
|
+
fs11.rmSync(tempDir, { recursive: true, force: true });
|
|
7379
7530
|
} catch {
|
|
7380
7531
|
}
|
|
7381
7532
|
}
|
|
@@ -7460,7 +7611,7 @@ function withTimeout2(promise, ms) {
|
|
|
7460
7611
|
}
|
|
7461
7612
|
function isPortListening(port) {
|
|
7462
7613
|
try {
|
|
7463
|
-
const r =
|
|
7614
|
+
const r = spawnSync8("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
7464
7615
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
7465
7616
|
} catch {
|
|
7466
7617
|
return false;
|
|
@@ -7491,7 +7642,7 @@ async function collectChecks() {
|
|
|
7491
7642
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
7492
7643
|
} else {
|
|
7493
7644
|
const v = getKernelVersion();
|
|
7494
|
-
const r =
|
|
7645
|
+
const r = spawnSync8(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7495
7646
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
7496
7647
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
7497
7648
|
} else if (r.error) {
|
|
@@ -7501,13 +7652,13 @@ async function collectChecks() {
|
|
|
7501
7652
|
}
|
|
7502
7653
|
}
|
|
7503
7654
|
try {
|
|
7504
|
-
|
|
7655
|
+
fs12.accessSync(USER_DATA_DIR, fs12.constants.W_OK);
|
|
7505
7656
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
7506
7657
|
} catch {
|
|
7507
7658
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
7508
7659
|
}
|
|
7509
|
-
if (
|
|
7510
|
-
if (isValidSettingsContent(
|
|
7660
|
+
if (fs12.existsSync(PATHS.settingsFile)) {
|
|
7661
|
+
if (isValidSettingsContent(fs12.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
7511
7662
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
7512
7663
|
} else {
|
|
7513
7664
|
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
@@ -7531,9 +7682,9 @@ async function collectChecks() {
|
|
|
7531
7682
|
if (cached?.updated_at) {
|
|
7532
7683
|
const rel = formatRelativeTime(cached.updated_at);
|
|
7533
7684
|
if (isSubscriptionStale(cached)) {
|
|
7534
|
-
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\
|
|
7685
|
+
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
|
|
7535
7686
|
} else {
|
|
7536
|
-
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel
|
|
7687
|
+
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", rel ? `${rel}\u66F4\u65B0` : `\u66F4\u65B0\u65F6\u95F4\u8BB0\u5F55\u5F02\u5E38\uFF08${formatDate(cached.updated_at)}\uFF09`);
|
|
7537
7688
|
}
|
|
7538
7689
|
}
|
|
7539
7690
|
}
|
|
@@ -7891,6 +8042,9 @@ async function cmdKernel(args) {
|
|
|
7891
8042
|
}
|
|
7892
8043
|
throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
|
|
7893
8044
|
}
|
|
8045
|
+
if (info.ghFallbackToDirect) {
|
|
8046
|
+
console.log(colors.gray("gh \u67E5\u8BE2\u4E0D\u53EF\u7528\uFF0C\u5DF2\u56DE\u9000\u76F4\u8FDE GitHub API \u83B7\u53D6\u7248\u672C\u4FE1\u606F"));
|
|
8047
|
+
}
|
|
7894
8048
|
console.log(`\u5F53\u524D: ${info.current}`);
|
|
7895
8049
|
console.log(`\u6700\u65B0: ${info.latest}`);
|
|
7896
8050
|
if (!info.needsUpdate) {
|
|
@@ -8038,6 +8192,7 @@ function printOverwriteList() {
|
|
|
8038
8192
|
const num = seq < 10 ? ` ${seq}` : `${seq}`;
|
|
8039
8193
|
console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
|
|
8040
8194
|
console.log(colors.red(` ${b.message}`));
|
|
8195
|
+
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
8041
8196
|
});
|
|
8042
8197
|
console.log("");
|
|
8043
8198
|
}
|
|
@@ -8092,120 +8247,6 @@ async function cmdOverwrite(args) {
|
|
|
8092
8247
|
|
|
8093
8248
|
// src/commands/reset.ts
|
|
8094
8249
|
import fs13 from "fs";
|
|
8095
|
-
|
|
8096
|
-
// src/process-stop.ts
|
|
8097
|
-
import { spawnSync as spawnSync8 } from "child_process";
|
|
8098
|
-
import fs12 from "fs";
|
|
8099
|
-
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
8100
|
-
var PROCESS_WAIT_INTERVAL = 100;
|
|
8101
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
8102
|
-
function clearRuntime() {
|
|
8103
|
-
if (fs12.existsSync(DIRS.runtime)) {
|
|
8104
|
-
rmrf(DIRS.runtime);
|
|
8105
|
-
}
|
|
8106
|
-
ensureDirs();
|
|
8107
|
-
}
|
|
8108
|
-
function clearPid() {
|
|
8109
|
-
if (!fs12.existsSync(PATHS.pidFile)) return;
|
|
8110
|
-
if (isPidFileOwnedByRoot()) {
|
|
8111
|
-
const result = spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
8112
|
-
if (result.error || result.status !== 0) {
|
|
8113
|
-
console.warn("\u8B66\u544A: root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08sudo \u5931\u8D25\u6216\u5DF2\u53D6\u6D88\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5");
|
|
8114
|
-
}
|
|
8115
|
-
} else {
|
|
8116
|
-
try {
|
|
8117
|
-
fs12.unlinkSync(PATHS.pidFile);
|
|
8118
|
-
} catch {
|
|
8119
|
-
}
|
|
8120
|
-
}
|
|
8121
|
-
}
|
|
8122
|
-
function killProcess(pid) {
|
|
8123
|
-
try {
|
|
8124
|
-
process.kill(pid, "SIGKILL");
|
|
8125
|
-
return true;
|
|
8126
|
-
} catch {
|
|
8127
|
-
return false;
|
|
8128
|
-
}
|
|
8129
|
-
}
|
|
8130
|
-
function killAllMihomo(forceSudo = false) {
|
|
8131
|
-
const pattern = MAIN_INSTANCE_PATTERN;
|
|
8132
|
-
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
8133
|
-
const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
|
|
8134
|
-
try {
|
|
8135
|
-
const result = spawnSync8(argv[0], argv[1], options);
|
|
8136
|
-
if (result.error) return false;
|
|
8137
|
-
return result.status === 0 || result.status === 1;
|
|
8138
|
-
} catch {
|
|
8139
|
-
return false;
|
|
8140
|
-
}
|
|
8141
|
-
}
|
|
8142
|
-
async function cleanupAll(forceSudo = false) {
|
|
8143
|
-
const pids = getMihomoPids();
|
|
8144
|
-
if (pids.length === 0) {
|
|
8145
|
-
clearPid();
|
|
8146
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
8147
|
-
}
|
|
8148
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
8149
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
8150
|
-
let killedCount = 0;
|
|
8151
|
-
const failedPids = [];
|
|
8152
|
-
if (needsSudo) {
|
|
8153
|
-
const success = killAllMihomo(true);
|
|
8154
|
-
if (success) {
|
|
8155
|
-
killedCount = pids.length;
|
|
8156
|
-
} else {
|
|
8157
|
-
failedPids.push(...pids);
|
|
8158
|
-
}
|
|
8159
|
-
} else {
|
|
8160
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
8161
|
-
if (killAllMihomo(false)) {
|
|
8162
|
-
killedCount = pids.length;
|
|
8163
|
-
} else {
|
|
8164
|
-
failedPids.push(...pids);
|
|
8165
|
-
}
|
|
8166
|
-
} else {
|
|
8167
|
-
for (const pid of pids) {
|
|
8168
|
-
if (!isMihomoProcess(pid)) {
|
|
8169
|
-
killedCount++;
|
|
8170
|
-
continue;
|
|
8171
|
-
}
|
|
8172
|
-
if (killProcess(pid)) {
|
|
8173
|
-
killedCount++;
|
|
8174
|
-
} else {
|
|
8175
|
-
failedPids.push(pid);
|
|
8176
|
-
}
|
|
8177
|
-
}
|
|
8178
|
-
}
|
|
8179
|
-
}
|
|
8180
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
8181
|
-
if (getMihomoPids().length === 0) break;
|
|
8182
|
-
await sleep(PROCESS_WAIT_INTERVAL);
|
|
8183
|
-
}
|
|
8184
|
-
clearPid();
|
|
8185
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
8186
|
-
}
|
|
8187
|
-
async function stop(forceSudo = false) {
|
|
8188
|
-
const allPids = getMihomoPids();
|
|
8189
|
-
if (allPids.length === 0) {
|
|
8190
|
-
clearPid();
|
|
8191
|
-
clearRuntime();
|
|
8192
|
-
return { success: true, notRunning: true };
|
|
8193
|
-
}
|
|
8194
|
-
const result = await cleanupAll(forceSudo);
|
|
8195
|
-
const remaining = getMihomoPids();
|
|
8196
|
-
if (remaining.length > 0) {
|
|
8197
|
-
console.log("");
|
|
8198
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
8199
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
8200
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
8201
|
-
console.log("");
|
|
8202
|
-
return { success: true, remaining };
|
|
8203
|
-
}
|
|
8204
|
-
clearRuntime();
|
|
8205
|
-
return { success: true, killed: result.killed };
|
|
8206
|
-
}
|
|
8207
|
-
|
|
8208
|
-
// src/commands/reset.ts
|
|
8209
8250
|
var RESET_TARGETS = [
|
|
8210
8251
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
8211
8252
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -8336,6 +8377,13 @@ async function cmdReset(args) {
|
|
|
8336
8377
|
ensureDirs();
|
|
8337
8378
|
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
8338
8379
|
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
8380
|
+
if (ids.has("overwrites")) {
|
|
8381
|
+
const typos = listTypoOverwriteFiles();
|
|
8382
|
+
if (typos.length > 0) {
|
|
8383
|
+
console.log(colors.yellow(`\u53E6\u6709 ${typos.length} \u4E2A\u7591\u4F3C\u8986\u5199\u6587\u4EF6\u672A\u88AB\u8BC6\u522B\u3001\u4FDD\u7559\u672A\u5220: ${typos.join("\u3001")}`));
|
|
8384
|
+
console.log(colors.gray(" \u8FD9\u4E9B\u6587\u4EF6\u540D\u4E0D\u4F1A\u88AB\u52A0\u8F7D\uFF08\u5408\u6CD5\uFF1Aoverwrite.yaml\u3001overwrite.*.yaml/yml\u3001overwrite.js \u7B49\uFF09\uFF1B\u786E\u8BA4\u65E0\u7528\u53EF\u624B\u52A8\u5220\u9664"));
|
|
8385
|
+
}
|
|
8386
|
+
}
|
|
8339
8387
|
}
|
|
8340
8388
|
|
|
8341
8389
|
// src/commands/service.ts
|
|
@@ -8527,14 +8575,6 @@ function printSubscriptionList() {
|
|
|
8527
8575
|
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
8528
8576
|
console.log("");
|
|
8529
8577
|
}
|
|
8530
|
-
function assertNotFlagLike(name, usage) {
|
|
8531
|
-
if (name.startsWith("-")) {
|
|
8532
|
-
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
8533
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8534
|
-
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
8535
|
-
});
|
|
8536
|
-
}
|
|
8537
|
-
}
|
|
8538
8578
|
function readUrlFromClipboard() {
|
|
8539
8579
|
if (!process.stdin.isTTY) return null;
|
|
8540
8580
|
try {
|
|
@@ -8574,7 +8614,6 @@ async function subAdd(args) {
|
|
|
8574
8614
|
if (!isValidHttpUrl(url)) {
|
|
8575
8615
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
8576
8616
|
}
|
|
8577
|
-
assertNotFlagLike(name, "mihomo sub add <url> [name]");
|
|
8578
8617
|
console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
|
|
8579
8618
|
addSubscription(url, name);
|
|
8580
8619
|
try {
|
|
@@ -8674,6 +8713,9 @@ async function subRemove(args) {
|
|
|
8674
8713
|
hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
|
|
8675
8714
|
});
|
|
8676
8715
|
}
|
|
8716
|
+
if (subs.length === 0) {
|
|
8717
|
+
throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
|
|
8718
|
+
}
|
|
8677
8719
|
const target = resolveSubscription(subs, name);
|
|
8678
8720
|
const isExact = target.name === name;
|
|
8679
8721
|
const skipConfirm = hasFlag(args, "-y", "--yes");
|