mihomo-cli 26.9.94 → 26.10.96
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 +55 -0
- package/README.md +4 -4
- package/dist/index.js +349 -301
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -271,7 +271,7 @@ function assertKnownFlags(args, known, command) {
|
|
|
271
271
|
if (!args) return;
|
|
272
272
|
const knownSet = new Set(known);
|
|
273
273
|
for (const a of args) {
|
|
274
|
-
if (!a.startsWith("-")
|
|
274
|
+
if (!a.startsWith("-")) continue;
|
|
275
275
|
if (knownSet.has(a)) continue;
|
|
276
276
|
const match = matchValueFlagToken(a);
|
|
277
277
|
if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
|
|
@@ -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
|
}
|
|
@@ -3973,6 +3964,11 @@ function assertValidParsedKey(rawKey, parsed) {
|
|
|
3973
3964
|
});
|
|
3974
3965
|
}
|
|
3975
3966
|
}
|
|
3967
|
+
function describeValueKind(value) {
|
|
3968
|
+
if (value === null) return "null";
|
|
3969
|
+
if (typeof value === "object") return "\u6620\u5C04";
|
|
3970
|
+
return `\u6807\u91CF\uFF08${typeof value}\uFF09`;
|
|
3971
|
+
}
|
|
3976
3972
|
function mergeConfigLevel(target, override, parseOperators) {
|
|
3977
3973
|
let t = target;
|
|
3978
3974
|
if (t === null || t === void 0) {
|
|
@@ -4006,13 +4002,10 @@ function mergeConfigLevel(target, override, parseOperators) {
|
|
|
4006
4002
|
const existingValue = result[key];
|
|
4007
4003
|
if (arrayPrepend || arrayAppend) {
|
|
4008
4004
|
if (existingValue !== void 0 && !Array.isArray(existingValue)) {
|
|
4009
|
-
throw new CliError(
|
|
4010
|
-
|
|
4011
|
-
{
|
|
4012
|
-
|
|
4013
|
-
hint: [`+${key} / ${key}+ \u7528\u4E8E\u5411\u6570\u7EC4\u524D\u7F6E/\u8FFD\u52A0\u5143\u7D20\uFF08\u5982 rules+\uFF09\u3002`, `\u82E5\u8981\u66FF\u6362\u975E\u6570\u7EC4\u7684 ${key}\uFF0C\u8BF7\u76F4\u63A5\u5199 ${key}: <\u503C>\u3002`]
|
|
4014
|
-
}
|
|
4015
|
-
);
|
|
4005
|
+
throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7684\u6570\u7EC4\u62FC\u63A5\u8BED\u4E49\u53EA\u9002\u7528\u4E8E\u6570\u7EC4\uFF0C\u4F46 "${key}" \u5F53\u524D\u662F ${describeValueKind(existingValue)}`, {
|
|
4006
|
+
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
4007
|
+
hint: [`+${key} / ${key}+ \u7528\u4E8E\u5411\u6570\u7EC4\u524D\u7F6E/\u8FFD\u52A0\u5143\u7D20\uFF08\u5982 rules+\uFF09\u3002`, `\u82E5\u8981\u66FF\u6362\u975E\u6570\u7EC4\u7684 ${key}\uFF0C\u8BF7\u76F4\u63A5\u5199 ${key}: <\u503C>\u3002`]
|
|
4008
|
+
});
|
|
4016
4009
|
}
|
|
4017
4010
|
const existingArr = Array.isArray(existingValue) ? existingValue : [];
|
|
4018
4011
|
const overrideArr = Array.isArray(value) ? value : [value];
|
|
@@ -4060,6 +4053,13 @@ function isOverwriteFilenameTypo(filename) {
|
|
|
4060
4053
|
const lower = filename.toLowerCase();
|
|
4061
4054
|
return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower);
|
|
4062
4055
|
}
|
|
4056
|
+
function listTypoOverwriteFiles() {
|
|
4057
|
+
try {
|
|
4058
|
+
return fs3.readdirSync(USER_DATA_DIR).filter(isOverwriteFilenameTypo);
|
|
4059
|
+
} catch {
|
|
4060
|
+
return [];
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
4063
4063
|
var MATCH_KEYS = /* @__PURE__ */ new Set(["name", "url-domain"]);
|
|
4064
4064
|
function normalizeMatch(raw, fileName) {
|
|
4065
4065
|
if (raw === void 0) return void 0;
|
|
@@ -4210,6 +4210,22 @@ function assertNoMetadataKeyLookalikes(config, fileName) {
|
|
|
4210
4210
|
}
|
|
4211
4211
|
}
|
|
4212
4212
|
}
|
|
4213
|
+
function assertFileLevelOperatorRules(config, fileName) {
|
|
4214
|
+
for (const rawKey of Object.keys(config)) {
|
|
4215
|
+
const parsed = parseOverrideKey(rawKey);
|
|
4216
|
+
assertValidParsedKey(rawKey, parsed);
|
|
4217
|
+
if (!parsed.arrayPrepend && !parsed.arrayAppend) continue;
|
|
4218
|
+
const base = BASE_CONFIG[parsed.key];
|
|
4219
|
+
if (base === void 0 || Array.isArray(base)) continue;
|
|
4220
|
+
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 ${describeValueKind(base)}\u3001\u4E0D\u662F\u6570\u7EC4`, {
|
|
4221
|
+
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
4222
|
+
hint: [
|
|
4223
|
+
`+${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`,
|
|
4224
|
+
`\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`
|
|
4225
|
+
]
|
|
4226
|
+
});
|
|
4227
|
+
}
|
|
4228
|
+
}
|
|
4213
4229
|
function normalizeEnabled(raw, fileName) {
|
|
4214
4230
|
if (raw === void 0) return true;
|
|
4215
4231
|
if (typeof raw === "boolean") return raw;
|
|
@@ -4264,7 +4280,7 @@ function readOverwriteFiles() {
|
|
|
4264
4280
|
if (!fs3.existsSync(USER_DATA_DIR)) return { ok, broken };
|
|
4265
4281
|
const entries = fs3.readdirSync(USER_DATA_DIR);
|
|
4266
4282
|
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(
|
|
4283
|
+
for (const typo of entries.filter(isOverwriteFilenameTypo)) {
|
|
4268
4284
|
console.warn(
|
|
4269
4285
|
`\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
4286
|
);
|
|
@@ -4281,6 +4297,7 @@ function readOverwriteFiles() {
|
|
|
4281
4297
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
4282
4298
|
const { match, enabled, ...config } = parsed;
|
|
4283
4299
|
assertNoMetadataKeyLookalikes(config, file);
|
|
4300
|
+
assertFileLevelOperatorRules(config, file);
|
|
4284
4301
|
ok.push({ name: file, path: filePath, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
|
|
4285
4302
|
} else if (parsed !== null) {
|
|
4286
4303
|
const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
|
|
@@ -4756,8 +4773,8 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
|
4756
4773
|
}
|
|
4757
4774
|
|
|
4758
4775
|
// src/service.ts
|
|
4759
|
-
import { spawnSync as
|
|
4760
|
-
import
|
|
4776
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
4777
|
+
import fs9 from "fs";
|
|
4761
4778
|
import path7 from "path";
|
|
4762
4779
|
|
|
4763
4780
|
// src/log-files.ts
|
|
@@ -4903,6 +4920,10 @@ function listLogs() {
|
|
|
4903
4920
|
return result;
|
|
4904
4921
|
}
|
|
4905
4922
|
|
|
4923
|
+
// src/process-stop.ts
|
|
4924
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
4925
|
+
import fs8 from "fs";
|
|
4926
|
+
|
|
4906
4927
|
// src/process-probe.ts
|
|
4907
4928
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
4908
4929
|
import fs6 from "fs";
|
|
@@ -4981,14 +5002,9 @@ function isPidFileOwnedByRoot() {
|
|
|
4981
5002
|
}
|
|
4982
5003
|
function checkStaleState() {
|
|
4983
5004
|
const allPids = getMihomoPids();
|
|
4984
|
-
const hasRootProcess = allPids.some((p) => isProcessRoot(p));
|
|
4985
|
-
const hasRootPidFile = isPidFileOwnedByRoot();
|
|
4986
5005
|
return {
|
|
4987
|
-
needsCleanup: allPids.length > 0 ||
|
|
4988
|
-
allPids
|
|
4989
|
-
hasRootProcess,
|
|
4990
|
-
hasRootPidFile,
|
|
4991
|
-
needsSudo: hasRootProcess || hasRootPidFile
|
|
5006
|
+
needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
|
|
5007
|
+
allPids
|
|
4992
5008
|
};
|
|
4993
5009
|
}
|
|
4994
5010
|
function getProcessInfo(pid) {
|
|
@@ -5028,6 +5044,9 @@ var SudoAuthError = class extends Error {
|
|
|
5028
5044
|
this.name = "SudoAuthError";
|
|
5029
5045
|
}
|
|
5030
5046
|
};
|
|
5047
|
+
function describeSudoFailure(e) {
|
|
5048
|
+
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
5049
|
+
}
|
|
5031
5050
|
function sudoExitToError(action, status, codeMessages) {
|
|
5032
5051
|
if (status === 1) return new SudoAuthError();
|
|
5033
5052
|
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
@@ -5059,6 +5078,143 @@ function sleep(ms) {
|
|
|
5059
5078
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
5060
5079
|
}
|
|
5061
5080
|
|
|
5081
|
+
// src/process-stop.ts
|
|
5082
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
5083
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
5084
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
5085
|
+
function clearRuntime() {
|
|
5086
|
+
if (fs8.existsSync(DIRS.runtime)) {
|
|
5087
|
+
rmrf(DIRS.runtime);
|
|
5088
|
+
}
|
|
5089
|
+
ensureDirs();
|
|
5090
|
+
}
|
|
5091
|
+
function describePidCleanupFailure(err) {
|
|
5092
|
+
return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
|
|
5093
|
+
}
|
|
5094
|
+
function warnPidCleanupFailed(err) {
|
|
5095
|
+
if (!err) return;
|
|
5096
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
5097
|
+
}
|
|
5098
|
+
function clearPid() {
|
|
5099
|
+
try {
|
|
5100
|
+
fs8.unlinkSync(PATHS.pidFile);
|
|
5101
|
+
return null;
|
|
5102
|
+
} catch (e) {
|
|
5103
|
+
if (e.code === "ENOENT") return null;
|
|
5104
|
+
return e;
|
|
5105
|
+
}
|
|
5106
|
+
}
|
|
5107
|
+
async function waitUntilNoMihomo(attempts = PROCESS_WAIT_ATTEMPTS, interval = PROCESS_WAIT_INTERVAL) {
|
|
5108
|
+
for (let i = 0; i < attempts; i++) {
|
|
5109
|
+
if (getMihomoPids().length === 0) return;
|
|
5110
|
+
await sleep(interval);
|
|
5111
|
+
}
|
|
5112
|
+
}
|
|
5113
|
+
async function reapPidWhenQuiet() {
|
|
5114
|
+
await waitUntilNoMihomo();
|
|
5115
|
+
if (getMihomoPids().length > 0) return null;
|
|
5116
|
+
return clearPid();
|
|
5117
|
+
}
|
|
5118
|
+
function killProcess(pid) {
|
|
5119
|
+
try {
|
|
5120
|
+
process.kill(pid, "SIGKILL");
|
|
5121
|
+
return true;
|
|
5122
|
+
} catch {
|
|
5123
|
+
return false;
|
|
5124
|
+
}
|
|
5125
|
+
}
|
|
5126
|
+
function killAllMihomo() {
|
|
5127
|
+
try {
|
|
5128
|
+
const result = spawnSync4("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
|
|
5129
|
+
if (result.error) return false;
|
|
5130
|
+
return result.status === 0 || result.status === 1;
|
|
5131
|
+
} catch {
|
|
5132
|
+
return false;
|
|
5133
|
+
}
|
|
5134
|
+
}
|
|
5135
|
+
function buildKernelCleanupScript() {
|
|
5136
|
+
return [
|
|
5137
|
+
"#!/bin/bash",
|
|
5138
|
+
// pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
|
|
5139
|
+
`pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
|
|
5140
|
+
"rc=$?",
|
|
5141
|
+
"[ $rc -le 1 ] || exit 2",
|
|
5142
|
+
"exit 0",
|
|
5143
|
+
""
|
|
5144
|
+
].join("\n");
|
|
5145
|
+
}
|
|
5146
|
+
async function cleanupAll() {
|
|
5147
|
+
const pids = getMihomoPids();
|
|
5148
|
+
if (pids.length === 0) {
|
|
5149
|
+
return { killed: 0, failed: 0, remaining: [], scriptError: null, pidError: clearPid() };
|
|
5150
|
+
}
|
|
5151
|
+
let killedCount = 0;
|
|
5152
|
+
const failedPids = [];
|
|
5153
|
+
let scriptError = null;
|
|
5154
|
+
const rootPids = pids.filter(isProcessRoot);
|
|
5155
|
+
if (rootPids.length > 0) {
|
|
5156
|
+
console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
|
|
5157
|
+
try {
|
|
5158
|
+
runSudoScript(buildKernelCleanupScript(), {
|
|
5159
|
+
action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
|
|
5160
|
+
file: "cleanup-residue.sh",
|
|
5161
|
+
codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
|
|
5162
|
+
});
|
|
5163
|
+
killedCount = pids.length;
|
|
5164
|
+
} catch (e) {
|
|
5165
|
+
scriptError = e;
|
|
5166
|
+
}
|
|
5167
|
+
} else if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
5168
|
+
if (killAllMihomo()) {
|
|
5169
|
+
killedCount = pids.length;
|
|
5170
|
+
} else {
|
|
5171
|
+
failedPids.push(...pids);
|
|
5172
|
+
}
|
|
5173
|
+
} else {
|
|
5174
|
+
for (const pid of pids) {
|
|
5175
|
+
if (!isMihomoProcess(pid)) {
|
|
5176
|
+
killedCount++;
|
|
5177
|
+
continue;
|
|
5178
|
+
}
|
|
5179
|
+
if (killProcess(pid)) {
|
|
5180
|
+
killedCount++;
|
|
5181
|
+
} else {
|
|
5182
|
+
failedPids.push(pid);
|
|
5183
|
+
}
|
|
5184
|
+
}
|
|
5185
|
+
}
|
|
5186
|
+
await waitUntilNoMihomo();
|
|
5187
|
+
const remaining = getMihomoPids();
|
|
5188
|
+
const pidError = remaining.length === 0 ? clearPid() : null;
|
|
5189
|
+
return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
|
|
5190
|
+
}
|
|
5191
|
+
async function stop() {
|
|
5192
|
+
const allPids = getMihomoPids();
|
|
5193
|
+
if (allPids.length === 0) {
|
|
5194
|
+
warnPidCleanupFailed(clearPid());
|
|
5195
|
+
clearRuntime();
|
|
5196
|
+
return { success: true, notRunning: true };
|
|
5197
|
+
}
|
|
5198
|
+
const result = await cleanupAll();
|
|
5199
|
+
if (result.remaining.length === 0) {
|
|
5200
|
+
warnPidCleanupFailed(result.pidError);
|
|
5201
|
+
if (result.scriptError) {
|
|
5202
|
+
console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo stop`));
|
|
5203
|
+
}
|
|
5204
|
+
}
|
|
5205
|
+
const remaining = getMihomoPids();
|
|
5206
|
+
if (remaining.length > 0) {
|
|
5207
|
+
console.log("");
|
|
5208
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5209
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5210
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
5211
|
+
console.log("");
|
|
5212
|
+
return { success: true, remaining };
|
|
5213
|
+
}
|
|
5214
|
+
clearRuntime();
|
|
5215
|
+
return { success: true, killed: result.killed };
|
|
5216
|
+
}
|
|
5217
|
+
|
|
5062
5218
|
// src/service.ts
|
|
5063
5219
|
function assertServiceLabelSafe() {
|
|
5064
5220
|
if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
|
|
@@ -5082,10 +5238,10 @@ function bootstrapDomain() {
|
|
|
5082
5238
|
return `gui/${process.getuid?.() ?? 0}`;
|
|
5083
5239
|
}
|
|
5084
5240
|
function isServiceInstalled() {
|
|
5085
|
-
return
|
|
5241
|
+
return fs9.existsSync(PATHS.userAgentPlist);
|
|
5086
5242
|
}
|
|
5087
5243
|
function detectLegacySystemInstall() {
|
|
5088
|
-
return
|
|
5244
|
+
return fs9.existsSync(PATHS.systemDaemonPlist);
|
|
5089
5245
|
}
|
|
5090
5246
|
function parseServicePrint(output) {
|
|
5091
5247
|
const stateMatch = output.match(/^\tstate = (.+)$/m);
|
|
@@ -5111,7 +5267,7 @@ function parseDisabledList(output, label) {
|
|
|
5111
5267
|
var LAUNCHCTL_NOT_LOADED = 113;
|
|
5112
5268
|
function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5113
5269
|
try {
|
|
5114
|
-
const result =
|
|
5270
|
+
const result = spawnSync5("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
|
|
5115
5271
|
return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
|
|
5116
5272
|
} catch {
|
|
5117
5273
|
return { status: null, stdout: "", stderr: "" };
|
|
@@ -5128,7 +5284,8 @@ function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
|
5128
5284
|
assertLaunchctlQueryOk(out.status, "print-disabled");
|
|
5129
5285
|
return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
|
|
5130
5286
|
}
|
|
5131
|
-
function getServiceStatus() {
|
|
5287
|
+
function getServiceStatus(options = {}) {
|
|
5288
|
+
const withDisabled = options.withDisabled !== false;
|
|
5132
5289
|
const installed = isServiceInstalled();
|
|
5133
5290
|
const print = runLaunchctl(["print", serviceTarget()]);
|
|
5134
5291
|
assertLaunchctlQueryOk(print.status, "print");
|
|
@@ -5137,27 +5294,27 @@ function getServiceStatus() {
|
|
|
5137
5294
|
return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null, lastTerminatingSignal: null };
|
|
5138
5295
|
}
|
|
5139
5296
|
const { state, pid, lastExitCode, lastTerminatingSignal } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null, lastTerminatingSignal: null };
|
|
5140
|
-
const disabled = isServiceDisabledInLaunchd();
|
|
5297
|
+
const disabled = withDisabled ? isServiceDisabledInLaunchd() : false;
|
|
5141
5298
|
return { installed, loaded, running: state === "running", pid, disabled, lastExitCode, lastTerminatingSignal };
|
|
5142
5299
|
}
|
|
5143
5300
|
async function waitServiceHealthy() {
|
|
5144
5301
|
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
5145
5302
|
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
5146
|
-
let last
|
|
5147
|
-
|
|
5303
|
+
let last;
|
|
5304
|
+
do {
|
|
5148
5305
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5149
|
-
last = getServiceStatus();
|
|
5306
|
+
last = getServiceStatus({ withDisabled: false });
|
|
5150
5307
|
if (isCrashed(last)) {
|
|
5151
5308
|
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5152
5309
|
}
|
|
5153
5310
|
if (!last.loaded) {
|
|
5154
5311
|
return { healthy: false, crashed: false, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5155
5312
|
}
|
|
5156
|
-
}
|
|
5313
|
+
} while (Date.now() < deadline);
|
|
5157
5314
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
5158
5315
|
while (Date.now() < graceDeadline) {
|
|
5159
5316
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5160
|
-
last = getServiceStatus();
|
|
5317
|
+
last = getServiceStatus({ withDisabled: false });
|
|
5161
5318
|
if (isCrashed(last)) {
|
|
5162
5319
|
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode, terminatingSignal: last.lastTerminatingSignal };
|
|
5163
5320
|
}
|
|
@@ -5211,18 +5368,18 @@ ${argsXml}
|
|
|
5211
5368
|
`;
|
|
5212
5369
|
}
|
|
5213
5370
|
function ensureServiceSymlink() {
|
|
5214
|
-
if (!
|
|
5371
|
+
if (!fs9.existsSync(PATHS.mihomoBinary)) {
|
|
5215
5372
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
5216
5373
|
}
|
|
5217
5374
|
try {
|
|
5218
|
-
const current =
|
|
5375
|
+
const current = fs9.readlinkSync(PATHS.serviceBinary);
|
|
5219
5376
|
if (current === "mihomo") return;
|
|
5220
|
-
|
|
5377
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5221
5378
|
} catch (e) {
|
|
5222
5379
|
const code = e.code;
|
|
5223
5380
|
if (code === "EINVAL") {
|
|
5224
5381
|
try {
|
|
5225
|
-
|
|
5382
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5226
5383
|
} catch {
|
|
5227
5384
|
}
|
|
5228
5385
|
} else if (code !== "ENOENT") {
|
|
@@ -5230,12 +5387,12 @@ function ensureServiceSymlink() {
|
|
|
5230
5387
|
}
|
|
5231
5388
|
}
|
|
5232
5389
|
try {
|
|
5233
|
-
|
|
5390
|
+
fs9.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
5234
5391
|
} catch (e) {
|
|
5235
5392
|
if (e.code !== "EEXIST") throw e;
|
|
5236
5393
|
let existing;
|
|
5237
5394
|
try {
|
|
5238
|
-
existing =
|
|
5395
|
+
existing = fs9.readlinkSync(PATHS.serviceBinary);
|
|
5239
5396
|
} catch {
|
|
5240
5397
|
throw e;
|
|
5241
5398
|
}
|
|
@@ -5284,64 +5441,31 @@ async function waitUntilUnloaded(target = serviceTarget()) {
|
|
|
5284
5441
|
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
5442
|
});
|
|
5286
5443
|
}
|
|
5287
|
-
function
|
|
5288
|
-
const
|
|
5289
|
-
|
|
5290
|
-
const
|
|
5291
|
-
|
|
5292
|
-
|
|
5293
|
-
|
|
5294
|
-
|
|
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;
|
|
5306
|
-
const hint = [
|
|
5307
|
-
ctx.mainOutcome,
|
|
5308
|
-
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${rootPids.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
|
-
`\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`
|
|
5310
|
-
];
|
|
5311
|
-
hint.push(hasKernelResidue ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5444
|
+
function buildRootResidueCleanupError(result, ctx) {
|
|
5445
|
+
const { scriptError, pidError } = result;
|
|
5446
|
+
const cancelled = scriptError instanceof SudoAuthError;
|
|
5447
|
+
const hasKernelResidue = result.remaining.length > 0;
|
|
5448
|
+
const pidList = `PID ${result.remaining.join(", ")}`;
|
|
5449
|
+
const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
|
|
5450
|
+
const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
|
|
5451
|
+
hint.push(hasKernelResidue || scriptError ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5312
5452
|
if (cancelled) {
|
|
5313
5453
|
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
5454
|
}
|
|
5315
|
-
return new CliError(
|
|
5316
|
-
}
|
|
5317
|
-
function currentRootResiduePids() {
|
|
5318
|
-
try {
|
|
5319
|
-
return getMihomoPids().filter(isProcessRoot);
|
|
5320
|
-
} catch {
|
|
5321
|
-
return [];
|
|
5322
|
-
}
|
|
5455
|
+
return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5323
5456
|
}
|
|
5324
|
-
function
|
|
5325
|
-
|
|
5326
|
-
|
|
5327
|
-
} catch (e) {
|
|
5328
|
-
if (e instanceof CliError) throw e;
|
|
5329
|
-
throw buildRootResidueCleanupError(e, ctx, currentRootResiduePids());
|
|
5330
|
-
}
|
|
5457
|
+
function classifyResidueCleanup(result) {
|
|
5458
|
+
if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
|
|
5459
|
+
return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
|
|
5331
5460
|
}
|
|
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);
|
|
5461
|
+
async function cleanupKernelsOrThrow(ctx) {
|
|
5462
|
+
const result = await cleanupAll();
|
|
5463
|
+
const verdict = classifyResidueCleanup(result);
|
|
5464
|
+
if (verdict === "ok") return;
|
|
5465
|
+
const err = buildRootResidueCleanupError(result, ctx);
|
|
5466
|
+
if (verdict === "throw") throw err;
|
|
5467
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
|
|
5468
|
+
for (const line of err.hint) console.warn(colors.gray(line));
|
|
5345
5469
|
}
|
|
5346
5470
|
async function installService(wasRunning) {
|
|
5347
5471
|
assertServiceLabelSafe();
|
|
@@ -5351,7 +5475,7 @@ async function installService(wasRunning) {
|
|
|
5351
5475
|
const stagePath = PATHS.servicePlistStage;
|
|
5352
5476
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5353
5477
|
try {
|
|
5354
|
-
const lint =
|
|
5478
|
+
const lint = spawnSync5("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
|
|
5355
5479
|
if (lint.status !== 0) {
|
|
5356
5480
|
throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
|
|
5357
5481
|
hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
|
|
@@ -5359,9 +5483,9 @@ async function installService(wasRunning) {
|
|
|
5359
5483
|
}
|
|
5360
5484
|
bootoutService();
|
|
5361
5485
|
await waitUntilUnloaded();
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5486
|
+
fs9.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
5487
|
+
fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
5488
|
+
fs9.chmodSync(PATHS.userAgentPlist, 420);
|
|
5365
5489
|
if (wasRunning) {
|
|
5366
5490
|
withFileLock(PATHS.serviceLock, () => {
|
|
5367
5491
|
if (shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch())) {
|
|
@@ -5374,7 +5498,7 @@ async function installService(wasRunning) {
|
|
|
5374
5498
|
}
|
|
5375
5499
|
} finally {
|
|
5376
5500
|
try {
|
|
5377
|
-
|
|
5501
|
+
fs9.unlinkSync(stagePath);
|
|
5378
5502
|
} catch {
|
|
5379
5503
|
}
|
|
5380
5504
|
}
|
|
@@ -5385,7 +5509,7 @@ async function installService(wasRunning) {
|
|
|
5385
5509
|
}
|
|
5386
5510
|
function readStopEpoch() {
|
|
5387
5511
|
try {
|
|
5388
|
-
const n = Number.parseInt(
|
|
5512
|
+
const n = Number.parseInt(fs9.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
5389
5513
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
5390
5514
|
} catch {
|
|
5391
5515
|
return 0;
|
|
@@ -5418,7 +5542,7 @@ async function startService() {
|
|
|
5418
5542
|
if (!isServiceInstalled()) {
|
|
5419
5543
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5420
5544
|
}
|
|
5421
|
-
if (!
|
|
5545
|
+
if (!fs9.existsSync(PATHS.configFile)) {
|
|
5422
5546
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
|
|
5423
5547
|
}
|
|
5424
5548
|
if (getConfigInfo()?.tun) {
|
|
@@ -5432,7 +5556,7 @@ async function startService() {
|
|
|
5432
5556
|
]
|
|
5433
5557
|
});
|
|
5434
5558
|
}
|
|
5435
|
-
|
|
5559
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
|
|
5436
5560
|
bootoutService();
|
|
5437
5561
|
await waitUntilUnloaded();
|
|
5438
5562
|
rotateAndCleanupLogs();
|
|
@@ -5464,7 +5588,7 @@ async function stopService() {
|
|
|
5464
5588
|
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5465
5589
|
});
|
|
5466
5590
|
await waitUntilUnloaded();
|
|
5467
|
-
|
|
5591
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
|
|
5468
5592
|
}
|
|
5469
5593
|
async function uninstallService() {
|
|
5470
5594
|
assertServiceLabelSafe();
|
|
@@ -5474,14 +5598,13 @@ async function uninstallService() {
|
|
|
5474
5598
|
});
|
|
5475
5599
|
await waitUntilUnloaded();
|
|
5476
5600
|
try {
|
|
5477
|
-
|
|
5601
|
+
fs9.rmSync(PATHS.userAgentPlist, { force: true });
|
|
5478
5602
|
} catch (e) {
|
|
5479
5603
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5480
5604
|
}
|
|
5481
|
-
|
|
5482
|
-
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5605
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5483
5606
|
try {
|
|
5484
|
-
|
|
5607
|
+
fs9.rmSync(PATHS.serviceBinary, { force: true });
|
|
5485
5608
|
} catch {
|
|
5486
5609
|
}
|
|
5487
5610
|
}
|
|
@@ -5499,7 +5622,6 @@ function buildLegacyCleanupScript() {
|
|
|
5499
5622
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5500
5623
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
5501
5624
|
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
5502
|
-
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
5503
5625
|
"exit 0",
|
|
5504
5626
|
""
|
|
5505
5627
|
].join("\n");
|
|
@@ -5514,7 +5636,7 @@ function cleanupLegacySystemInstall() {
|
|
|
5514
5636
|
codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
|
|
5515
5637
|
});
|
|
5516
5638
|
}
|
|
5517
|
-
function cleanupLegacyInstallOrThrow() {
|
|
5639
|
+
async function cleanupLegacyInstallOrThrow() {
|
|
5518
5640
|
try {
|
|
5519
5641
|
cleanupLegacySystemInstall();
|
|
5520
5642
|
} catch (e) {
|
|
@@ -5524,10 +5646,14 @@ function cleanupLegacyInstallOrThrow() {
|
|
|
5524
5646
|
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
5525
5647
|
});
|
|
5526
5648
|
}
|
|
5649
|
+
const pidError = await reapPidWhenQuiet();
|
|
5650
|
+
if (pidError) {
|
|
5651
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
5652
|
+
}
|
|
5527
5653
|
}
|
|
5528
5654
|
function logOversized() {
|
|
5529
5655
|
try {
|
|
5530
|
-
return
|
|
5656
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5531
5657
|
} catch {
|
|
5532
5658
|
return false;
|
|
5533
5659
|
}
|
|
@@ -5547,7 +5673,7 @@ async function tryHotReload() {
|
|
|
5547
5673
|
const info = await probe.json();
|
|
5548
5674
|
if (typeof info?.version !== "string") return false;
|
|
5549
5675
|
const port = getPorts().controller;
|
|
5550
|
-
const lsofResult =
|
|
5676
|
+
const lsofResult = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5551
5677
|
if (lsofResult.status !== 0) return false;
|
|
5552
5678
|
const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
|
|
5553
5679
|
if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
|
|
@@ -5577,8 +5703,8 @@ async function restartService() {
|
|
|
5577
5703
|
if (logOversized()) {
|
|
5578
5704
|
const archiveFile = allocateArchivePath();
|
|
5579
5705
|
try {
|
|
5580
|
-
|
|
5581
|
-
|
|
5706
|
+
fs9.copyFileSync(PATHS.logFile, archiveFile);
|
|
5707
|
+
fs9.writeFileSync(PATHS.logFile, "");
|
|
5582
5708
|
} catch {
|
|
5583
5709
|
}
|
|
5584
5710
|
}
|
|
@@ -6129,12 +6255,14 @@ async function tryUpdateOne(sub, signal) {
|
|
|
6129
6255
|
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
6130
6256
|
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
6131
6257
|
} catch (e) {
|
|
6132
|
-
return { name: sub.name, success: false, error: e.message };
|
|
6258
|
+
return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
|
|
6133
6259
|
}
|
|
6134
6260
|
}
|
|
6135
6261
|
function printUpdateResult(r) {
|
|
6136
6262
|
if (r.success) {
|
|
6137
6263
|
console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
|
|
6264
|
+
} else if (r.aborted) {
|
|
6265
|
+
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
6266
|
} else {
|
|
6139
6267
|
console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
|
|
6140
6268
|
}
|
|
@@ -6173,11 +6301,13 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6173
6301
|
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
6302
|
}
|
|
6175
6303
|
let updatedCount = 0;
|
|
6304
|
+
let failedCount = 0;
|
|
6176
6305
|
for (const r of results) {
|
|
6177
6306
|
if (r.success) updatedCount++;
|
|
6307
|
+
else if (!r.aborted) failedCount++;
|
|
6178
6308
|
printUpdateResult(r);
|
|
6179
6309
|
}
|
|
6180
|
-
return { total: staleSubs.length, updated: updatedCount, failed:
|
|
6310
|
+
return { total: staleSubs.length, updated: updatedCount, failed: failedCount };
|
|
6181
6311
|
}
|
|
6182
6312
|
|
|
6183
6313
|
// src/commands/config.ts
|
|
@@ -6268,7 +6398,7 @@ function viewLogWithTail(logPath, options) {
|
|
|
6268
6398
|
import readline from "readline";
|
|
6269
6399
|
|
|
6270
6400
|
// src/process-start.ts
|
|
6271
|
-
import
|
|
6401
|
+
import fs10 from "fs";
|
|
6272
6402
|
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6273
6403
|
function buildTunLaunchScript() {
|
|
6274
6404
|
const binary = shellQuote(PATHS.mihomoBinary);
|
|
@@ -6335,10 +6465,10 @@ exit 2
|
|
|
6335
6465
|
}
|
|
6336
6466
|
async function startTun() {
|
|
6337
6467
|
ensureDirs();
|
|
6338
|
-
if (!
|
|
6468
|
+
if (!fs10.existsSync(PATHS.mihomoBinary)) {
|
|
6339
6469
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
6340
6470
|
}
|
|
6341
|
-
if (!
|
|
6471
|
+
if (!fs10.existsSync(PATHS.configFile)) {
|
|
6342
6472
|
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
6343
6473
|
}
|
|
6344
6474
|
if (getServiceStatus().loaded) {
|
|
@@ -6348,12 +6478,12 @@ async function startTun() {
|
|
|
6348
6478
|
}
|
|
6349
6479
|
rotateAndCleanupLogs();
|
|
6350
6480
|
const logFile = PATHS.logFile;
|
|
6351
|
-
if (
|
|
6481
|
+
if (fs10.existsSync(logFile)) {
|
|
6352
6482
|
try {
|
|
6353
|
-
|
|
6483
|
+
fs10.accessSync(logFile, fs10.constants.W_OK);
|
|
6354
6484
|
} catch {
|
|
6355
6485
|
try {
|
|
6356
|
-
|
|
6486
|
+
fs10.unlinkSync(logFile);
|
|
6357
6487
|
} catch {
|
|
6358
6488
|
}
|
|
6359
6489
|
}
|
|
@@ -6456,7 +6586,7 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
6456
6586
|
}
|
|
6457
6587
|
|
|
6458
6588
|
// src/system-proxy.ts
|
|
6459
|
-
import { spawnSync as
|
|
6589
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6460
6590
|
function isLoopbackHost(host) {
|
|
6461
6591
|
const h = host.toLowerCase();
|
|
6462
6592
|
return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
|
|
@@ -6518,7 +6648,7 @@ function summarizeSystemProxy(view, mixedPort) {
|
|
|
6518
6648
|
function detectSystemProxy(mixedPort) {
|
|
6519
6649
|
let r;
|
|
6520
6650
|
try {
|
|
6521
|
-
r =
|
|
6651
|
+
r = spawnSync6("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
|
|
6522
6652
|
} catch {
|
|
6523
6653
|
return null;
|
|
6524
6654
|
}
|
|
@@ -6561,7 +6691,17 @@ function isProbeSuccessStatus(code) {
|
|
|
6561
6691
|
return code !== null && code >= 200 && code < 300;
|
|
6562
6692
|
}
|
|
6563
6693
|
var PROBE_TIMEOUT_MS = 2e3;
|
|
6694
|
+
var PROBE_CACHE_TTL_MS = 3e3;
|
|
6695
|
+
var probeCache = null;
|
|
6564
6696
|
async function probeProxyConnectivity(port) {
|
|
6697
|
+
if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
|
|
6698
|
+
return probeCache.result;
|
|
6699
|
+
}
|
|
6700
|
+
const result = await probeProxyConnectivityUncached(port);
|
|
6701
|
+
probeCache = { port, at: Date.now(), result };
|
|
6702
|
+
return result;
|
|
6703
|
+
}
|
|
6704
|
+
async function probeProxyConnectivityUncached(port) {
|
|
6565
6705
|
const start = Date.now();
|
|
6566
6706
|
try {
|
|
6567
6707
|
const { stdout } = await execFileAsync(
|
|
@@ -6640,8 +6780,10 @@ function buildStatusJson(args) {
|
|
|
6640
6780
|
// 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
|
|
6641
6781
|
// 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
|
|
6642
6782
|
applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : [],
|
|
6643
|
-
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors
|
|
6644
|
-
|
|
6783
|
+
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
|
|
6784
|
+
// hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
|
|
6785
|
+
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
6786
|
+
errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
|
|
6645
6787
|
},
|
|
6646
6788
|
service: {
|
|
6647
6789
|
installed: args.service.installed,
|
|
@@ -6785,7 +6927,7 @@ async function printStatus(args = []) {
|
|
|
6785
6927
|
console.log("");
|
|
6786
6928
|
}
|
|
6787
6929
|
function shortOverwriteName(name) {
|
|
6788
|
-
return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
6930
|
+
return name.replace(/\.(?:ya?ml|m?js|cjs)$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
6789
6931
|
}
|
|
6790
6932
|
function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
6791
6933
|
if (!enabled) {
|
|
@@ -6810,6 +6952,7 @@ function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
|
6810
6952
|
}
|
|
6811
6953
|
for (const b of broken) {
|
|
6812
6954
|
console.log(colors.red(` ${b.message}`));
|
|
6955
|
+
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
6813
6956
|
}
|
|
6814
6957
|
}
|
|
6815
6958
|
function printServiceLines(service, legacy) {
|
|
@@ -6846,18 +6989,18 @@ async function cmdStart(args) {
|
|
|
6846
6989
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
6847
6990
|
assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
|
|
6848
6991
|
const targetMode = resolveStartMode(args);
|
|
6992
|
+
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6993
|
+
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6849
6994
|
let disabledAutoStartForTun = false;
|
|
6850
6995
|
if (!hasKernel()) {
|
|
6851
6996
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
6852
6997
|
}
|
|
6853
|
-
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6854
|
-
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6855
6998
|
const serviceBefore = getServiceStatus();
|
|
6856
6999
|
if (targetMode === "tun") {
|
|
6857
7000
|
if (detectLegacySystemInstall()) {
|
|
6858
7001
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
|
|
6859
7002
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
6860
|
-
cleanupLegacyInstallOrThrow();
|
|
7003
|
+
await cleanupLegacyInstallOrThrow();
|
|
6861
7004
|
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
6862
7005
|
console.log("");
|
|
6863
7006
|
}
|
|
@@ -7032,12 +7175,12 @@ async function cmdDirectory(args) {
|
|
|
7032
7175
|
}
|
|
7033
7176
|
|
|
7034
7177
|
// src/commands/doctor.ts
|
|
7035
|
-
import { spawnSync as
|
|
7036
|
-
import
|
|
7178
|
+
import { spawnSync as spawnSync8 } from "child_process";
|
|
7179
|
+
import fs12 from "fs";
|
|
7037
7180
|
|
|
7038
7181
|
// src/kernel.ts
|
|
7039
|
-
import { execFile as execFile3, spawnSync as
|
|
7040
|
-
import
|
|
7182
|
+
import { execFile as execFile3, spawnSync as spawnSync7 } from "child_process";
|
|
7183
|
+
import fs11 from "fs";
|
|
7041
7184
|
import path8 from "path";
|
|
7042
7185
|
import { promisify as promisify3 } from "util";
|
|
7043
7186
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7079,7 +7222,7 @@ function resolveDownloadChannel(input) {
|
|
|
7079
7222
|
return { kind: "direct" };
|
|
7080
7223
|
}
|
|
7081
7224
|
function hasGh() {
|
|
7082
|
-
const result =
|
|
7225
|
+
const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
|
|
7083
7226
|
return !result.error && result.status === 0;
|
|
7084
7227
|
}
|
|
7085
7228
|
function getArch() {
|
|
@@ -7174,6 +7317,7 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
|
|
|
7174
7317
|
return await getLatestReleaseViaGh(repo, opts.signal);
|
|
7175
7318
|
} catch (e) {
|
|
7176
7319
|
if (opts.signal?.aborted) throw e;
|
|
7320
|
+
opts.onGhFallback?.();
|
|
7177
7321
|
}
|
|
7178
7322
|
}
|
|
7179
7323
|
if (opts.proxy) {
|
|
@@ -7206,7 +7350,12 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
|
|
|
7206
7350
|
}
|
|
7207
7351
|
async function checkUpdate(opts) {
|
|
7208
7352
|
const currentVersion = getKernelVersion();
|
|
7209
|
-
|
|
7353
|
+
let ghFallbackToDirect = false;
|
|
7354
|
+
const optsWithFallbackNote = {
|
|
7355
|
+
...opts,
|
|
7356
|
+
onGhFallback: opts.useGh && !opts.proxy ? () => ghFallbackToDirect = true : void 0
|
|
7357
|
+
};
|
|
7358
|
+
const latest = await getLatestRelease(GITHUB_REPO, optsWithFallbackNote);
|
|
7210
7359
|
const latestVersion = latest.tag_name;
|
|
7211
7360
|
let needsUpdate = false;
|
|
7212
7361
|
const currentDisplay = currentVersion || "\u672A\u5B89\u88C5";
|
|
@@ -7224,7 +7373,8 @@ async function checkUpdate(opts) {
|
|
|
7224
7373
|
latest: latestVersion,
|
|
7225
7374
|
needsUpdate,
|
|
7226
7375
|
assets: latest.assets,
|
|
7227
|
-
release: latest
|
|
7376
|
+
release: latest,
|
|
7377
|
+
ghFallbackToDirect
|
|
7228
7378
|
};
|
|
7229
7379
|
}
|
|
7230
7380
|
function buildKernelCurlArgs(args) {
|
|
@@ -7272,7 +7422,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7272
7422
|
}
|
|
7273
7423
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7274
7424
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7275
|
-
const tempDir =
|
|
7425
|
+
const tempDir = fs11.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
7276
7426
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
7277
7427
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7278
7428
|
try {
|
|
@@ -7286,7 +7436,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7286
7436
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
|
|
7287
7437
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7288
7438
|
}
|
|
7289
|
-
const ghResult =
|
|
7439
|
+
const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7290
7440
|
stdio: "inherit",
|
|
7291
7441
|
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7292
7442
|
});
|
|
@@ -7304,7 +7454,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7304
7454
|
}
|
|
7305
7455
|
} else {
|
|
7306
7456
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7307
|
-
const curlResult =
|
|
7457
|
+
const curlResult = spawnSync7(
|
|
7308
7458
|
"curl",
|
|
7309
7459
|
buildKernelCurlArgs({
|
|
7310
7460
|
url: downloadUrl,
|
|
@@ -7327,11 +7477,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7327
7477
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7328
7478
|
}
|
|
7329
7479
|
}
|
|
7330
|
-
if (!
|
|
7480
|
+
if (!fs11.existsSync(tempPath)) {
|
|
7331
7481
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7332
7482
|
}
|
|
7333
7483
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7334
|
-
const actual =
|
|
7484
|
+
const actual = fs11.statSync(tempPath).size;
|
|
7335
7485
|
if (actual !== asset.size) {
|
|
7336
7486
|
throw new Error(
|
|
7337
7487
|
`\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 +7496,15 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7346
7496
|
throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
|
|
7347
7497
|
}
|
|
7348
7498
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
7349
|
-
const gzipResult =
|
|
7499
|
+
const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7350
7500
|
if (gzipResult.error) throw gzipResult.error;
|
|
7351
7501
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7352
|
-
|
|
7502
|
+
fs11.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
|
|
7353
7503
|
if (progressCallback) {
|
|
7354
7504
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7355
7505
|
}
|
|
7356
|
-
|
|
7357
|
-
const check =
|
|
7506
|
+
fs11.chmodSync(foundBinary, 493);
|
|
7507
|
+
const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7358
7508
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7359
7509
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7360
7510
|
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 +7520,12 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7370
7520
|
}
|
|
7371
7521
|
}
|
|
7372
7522
|
const targetPath = PATHS.mihomoBinary;
|
|
7373
|
-
|
|
7374
|
-
|
|
7523
|
+
fs11.renameSync(foundBinary, targetPath);
|
|
7524
|
+
fs11.chmodSync(targetPath, 493);
|
|
7375
7525
|
return { version: latest.tag_name, path: targetPath };
|
|
7376
7526
|
} finally {
|
|
7377
7527
|
try {
|
|
7378
|
-
|
|
7528
|
+
fs11.rmSync(tempDir, { recursive: true, force: true });
|
|
7379
7529
|
} catch {
|
|
7380
7530
|
}
|
|
7381
7531
|
}
|
|
@@ -7460,7 +7610,7 @@ function withTimeout2(promise, ms) {
|
|
|
7460
7610
|
}
|
|
7461
7611
|
function isPortListening(port) {
|
|
7462
7612
|
try {
|
|
7463
|
-
const r =
|
|
7613
|
+
const r = spawnSync8("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
7464
7614
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
7465
7615
|
} catch {
|
|
7466
7616
|
return false;
|
|
@@ -7491,7 +7641,7 @@ async function collectChecks() {
|
|
|
7491
7641
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
7492
7642
|
} else {
|
|
7493
7643
|
const v = getKernelVersion();
|
|
7494
|
-
const r =
|
|
7644
|
+
const r = spawnSync8(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7495
7645
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
7496
7646
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
7497
7647
|
} else if (r.error) {
|
|
@@ -7501,13 +7651,13 @@ async function collectChecks() {
|
|
|
7501
7651
|
}
|
|
7502
7652
|
}
|
|
7503
7653
|
try {
|
|
7504
|
-
|
|
7654
|
+
fs12.accessSync(USER_DATA_DIR, fs12.constants.W_OK);
|
|
7505
7655
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
7506
7656
|
} catch {
|
|
7507
7657
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
7508
7658
|
}
|
|
7509
|
-
if (
|
|
7510
|
-
if (isValidSettingsContent(
|
|
7659
|
+
if (fs12.existsSync(PATHS.settingsFile)) {
|
|
7660
|
+
if (isValidSettingsContent(fs12.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
7511
7661
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
7512
7662
|
} else {
|
|
7513
7663
|
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 +7681,9 @@ async function collectChecks() {
|
|
|
7531
7681
|
if (cached?.updated_at) {
|
|
7532
7682
|
const rel = formatRelativeTime(cached.updated_at);
|
|
7533
7683
|
if (isSubscriptionStale(cached)) {
|
|
7534
|
-
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\
|
|
7684
|
+
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
7685
|
} else {
|
|
7536
|
-
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel
|
|
7686
|
+
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
7687
|
}
|
|
7538
7688
|
}
|
|
7539
7689
|
}
|
|
@@ -7891,6 +8041,9 @@ async function cmdKernel(args) {
|
|
|
7891
8041
|
}
|
|
7892
8042
|
throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
|
|
7893
8043
|
}
|
|
8044
|
+
if (info.ghFallbackToDirect) {
|
|
8045
|
+
console.log(colors.gray("gh \u67E5\u8BE2\u4E0D\u53EF\u7528\uFF0C\u5DF2\u56DE\u9000\u76F4\u8FDE GitHub API \u83B7\u53D6\u7248\u672C\u4FE1\u606F"));
|
|
8046
|
+
}
|
|
7894
8047
|
console.log(`\u5F53\u524D: ${info.current}`);
|
|
7895
8048
|
console.log(`\u6700\u65B0: ${info.latest}`);
|
|
7896
8049
|
if (!info.needsUpdate) {
|
|
@@ -8038,6 +8191,7 @@ function printOverwriteList() {
|
|
|
8038
8191
|
const num = seq < 10 ? ` ${seq}` : `${seq}`;
|
|
8039
8192
|
console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
|
|
8040
8193
|
console.log(colors.red(` ${b.message}`));
|
|
8194
|
+
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
8041
8195
|
});
|
|
8042
8196
|
console.log("");
|
|
8043
8197
|
}
|
|
@@ -8092,120 +8246,6 @@ async function cmdOverwrite(args) {
|
|
|
8092
8246
|
|
|
8093
8247
|
// src/commands/reset.ts
|
|
8094
8248
|
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
8249
|
var RESET_TARGETS = [
|
|
8210
8250
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
8211
8251
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -8289,7 +8329,7 @@ async function cmdReset(args) {
|
|
|
8289
8329
|
console.log("\u5DF2\u53D6\u6D88");
|
|
8290
8330
|
return;
|
|
8291
8331
|
}
|
|
8292
|
-
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
8332
|
+
if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
|
|
8293
8333
|
if (serviceActive) {
|
|
8294
8334
|
if (serviceTargeted) await uninstallService();
|
|
8295
8335
|
else if (needsStop) await stopService();
|
|
@@ -8302,6 +8342,13 @@ async function cmdReset(args) {
|
|
|
8302
8342
|
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
8303
8343
|
});
|
|
8304
8344
|
}
|
|
8345
|
+
if (classifyResidueCleanup(cleanup) === "warn") {
|
|
8346
|
+
const reason = cleanup.scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(cleanup.scriptError)}\uFF09\uFF0C\u53EF\u80FD\u4ECD\u6709\u6B8B\u7559\u8FDB\u7A0B` : cleanup.pidError ? describePidCleanupFailure(cleanup.pidError) : null;
|
|
8347
|
+
if (reason) {
|
|
8348
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${reason}`));
|
|
8349
|
+
console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo stop"));
|
|
8350
|
+
}
|
|
8351
|
+
}
|
|
8305
8352
|
recordServiceStopped();
|
|
8306
8353
|
}
|
|
8307
8354
|
const deleted = /* @__PURE__ */ new Set();
|
|
@@ -8336,6 +8383,13 @@ async function cmdReset(args) {
|
|
|
8336
8383
|
ensureDirs();
|
|
8337
8384
|
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
8338
8385
|
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
8386
|
+
if (ids.has("overwrites")) {
|
|
8387
|
+
const typos = listTypoOverwriteFiles();
|
|
8388
|
+
if (typos.length > 0) {
|
|
8389
|
+
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")}`));
|
|
8390
|
+
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"));
|
|
8391
|
+
}
|
|
8392
|
+
}
|
|
8339
8393
|
}
|
|
8340
8394
|
|
|
8341
8395
|
// src/commands/service.ts
|
|
@@ -8346,7 +8400,7 @@ async function handleLegacyInstall() {
|
|
|
8346
8400
|
console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
|
|
8347
8401
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
8348
8402
|
console.log("");
|
|
8349
|
-
cleanupLegacyInstallOrThrow();
|
|
8403
|
+
await cleanupLegacyInstallOrThrow();
|
|
8350
8404
|
console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
|
|
8351
8405
|
console.log("");
|
|
8352
8406
|
}
|
|
@@ -8416,7 +8470,7 @@ async function cmdUninstall(args) {
|
|
|
8416
8470
|
}
|
|
8417
8471
|
if (legacy) {
|
|
8418
8472
|
console.log(colors.gray("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801"));
|
|
8419
|
-
cleanupLegacyInstallOrThrow();
|
|
8473
|
+
await cleanupLegacyInstallOrThrow();
|
|
8420
8474
|
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
8421
8475
|
}
|
|
8422
8476
|
const remaining = getMihomoPids();
|
|
@@ -8444,7 +8498,7 @@ async function cmdStop(args) {
|
|
|
8444
8498
|
if (detectLegacySystemInstall()) {
|
|
8445
8499
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
|
|
8446
8500
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
8447
|
-
cleanupLegacyInstallOrThrow();
|
|
8501
|
+
await cleanupLegacyInstallOrThrow();
|
|
8448
8502
|
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
8449
8503
|
console.log("");
|
|
8450
8504
|
}
|
|
@@ -8527,14 +8581,6 @@ function printSubscriptionList() {
|
|
|
8527
8581
|
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
8528
8582
|
console.log("");
|
|
8529
8583
|
}
|
|
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
8584
|
function readUrlFromClipboard() {
|
|
8539
8585
|
if (!process.stdin.isTTY) return null;
|
|
8540
8586
|
try {
|
|
@@ -8574,7 +8620,6 @@ async function subAdd(args) {
|
|
|
8574
8620
|
if (!isValidHttpUrl(url)) {
|
|
8575
8621
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
8576
8622
|
}
|
|
8577
|
-
assertNotFlagLike(name, "mihomo sub add <url> [name]");
|
|
8578
8623
|
console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
|
|
8579
8624
|
addSubscription(url, name);
|
|
8580
8625
|
try {
|
|
@@ -8669,9 +8714,12 @@ async function subRemove(args) {
|
|
|
8669
8714
|
assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
|
|
8670
8715
|
const name = getNonFlagArg(args, 2);
|
|
8671
8716
|
const subs = getSubscriptions();
|
|
8717
|
+
if (subs.length === 0) {
|
|
8718
|
+
throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
|
|
8719
|
+
}
|
|
8672
8720
|
if (!name) {
|
|
8673
8721
|
throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
|
|
8674
|
-
hint:
|
|
8722
|
+
hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
|
|
8675
8723
|
});
|
|
8676
8724
|
}
|
|
8677
8725
|
const target = resolveSubscription(subs, name);
|