mihomo-cli 26.10.113 → 26.10.115
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 +26 -19
- package/README.md +25 -7
- package/dist/index.js +841 -313
- package/docs/overwrite.md +0 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import
|
|
4
|
+
import fs20 from "fs";
|
|
5
5
|
|
|
6
6
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
7
7
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
@@ -3580,10 +3580,73 @@ var CHOMPING_CLIP = CHOMPING_MODE.CLIP;
|
|
|
3580
3580
|
var CHOMPING_STRIP = CHOMPING_MODE.STRIP;
|
|
3581
3581
|
var CHOMPING_KEEP = CHOMPING_MODE.KEEP;
|
|
3582
3582
|
|
|
3583
|
+
// src/config-graph.ts
|
|
3584
|
+
var CONFIG_GRAPH_MAX_EXPANDED_NODES = 1e5;
|
|
3585
|
+
var CONFIG_GRAPH_MAX_DEPTH = 200;
|
|
3586
|
+
var SCALAR_NODE = { cost: 1, height: 0 };
|
|
3587
|
+
function cycleError(source) {
|
|
3588
|
+
return new CliError(`${source}\u5305\u542B\u5FAA\u73AF\u5F15\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u5904\u7406\u914D\u7F6E\u56FE`, {
|
|
3589
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3590
|
+
hint: ["\u68C0\u67E5 YAML \u522B\u540D\u662F\u5426\u5F15\u7528\u4E86\u81EA\u8EAB\u6216\u7956\u5148\uFF1B\u82E5\u7531\u8986\u5199\u811A\u672C\u4EA7\u751F\uFF0C\u8BF7\u79FB\u9664\u5199\u56DE\u7956\u5148\u5BF9\u8C61\u7684\u5F15\u7528\u3002"]
|
|
3591
|
+
});
|
|
3592
|
+
}
|
|
3593
|
+
function depthError(source) {
|
|
3594
|
+
return new CliError(`${source}\u7684\u5D4C\u5957\u6DF1\u5EA6\u8D85\u8FC7 ${CONFIG_GRAPH_MAX_DEPTH} \u5C42\uFF0C\u65E0\u6CD5\u5B89\u5168\u9012\u5F52\u5904\u7406`, {
|
|
3595
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3596
|
+
hint: ["\u8BF7\u7F29\u51CF\u914D\u7F6E\u5D4C\u5957\uFF1BYAML \u522B\u540D\u4E0E\u8986\u5199\u811A\u672C\u90FD\u4E0D\u80FD\u751F\u6210\u8FC7\u6DF1\u7684\u914D\u7F6E\u56FE\u3002"]
|
|
3597
|
+
});
|
|
3598
|
+
}
|
|
3599
|
+
function budgetError(source) {
|
|
3600
|
+
return new CliError(`${source}\u5C55\u5F00\u540E\u7684\u8282\u70B9\u6570\u8D85\u8FC7 ${CONFIG_GRAPH_MAX_EXPANDED_NODES}\uFF0C\u5DF2\u62D2\u7EDD\u5904\u7406\u4EE5\u907F\u514D\u8D44\u6E90\u8017\u5C3D`, {
|
|
3601
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3602
|
+
hint: ["\u51CF\u5C11\u5171\u4EAB YAML \u522B\u540D\u6216\u8986\u5199\u811A\u672C\u4EA7\u751F\u7684\u91CD\u590D\u5F15\u7528\uFF1B\u914D\u7F6E\u5C55\u793A\u4E0E JSON \u5E8F\u5217\u5316\u9700\u8981\u5C55\u5F00\u8FD9\u4E9B\u5F15\u7528\u3002"]
|
|
3603
|
+
});
|
|
3604
|
+
}
|
|
3605
|
+
function addCost(left, right, source, checkExpansionBudget) {
|
|
3606
|
+
const total = left + right;
|
|
3607
|
+
if (checkExpansionBudget && total > CONFIG_GRAPH_MAX_EXPANDED_NODES) throw budgetError(source);
|
|
3608
|
+
return total;
|
|
3609
|
+
}
|
|
3610
|
+
function assertConfigGraphSafe(root, source = "\u914D\u7F6E") {
|
|
3611
|
+
assertConfigGraph(root, source, false);
|
|
3612
|
+
}
|
|
3613
|
+
function assertConfigGraphExpansionSafe(root, source = "\u914D\u7F6E") {
|
|
3614
|
+
assertConfigGraph(root, source, true);
|
|
3615
|
+
}
|
|
3616
|
+
function assertConfigGraph(root, source, checkExpansionBudget) {
|
|
3617
|
+
const active = /* @__PURE__ */ new WeakSet();
|
|
3618
|
+
const completed = /* @__PURE__ */ new WeakMap();
|
|
3619
|
+
const visit2 = (value, depth) => {
|
|
3620
|
+
if (depth > CONFIG_GRAPH_MAX_DEPTH) throw depthError(source);
|
|
3621
|
+
if (value === null || typeof value !== "object") return SCALAR_NODE;
|
|
3622
|
+
if (active.has(value)) throw cycleError(source);
|
|
3623
|
+
const cached = completed.get(value);
|
|
3624
|
+
if (cached !== void 0) {
|
|
3625
|
+
if (depth + cached.height > CONFIG_GRAPH_MAX_DEPTH) throw depthError(source);
|
|
3626
|
+
return cached;
|
|
3627
|
+
}
|
|
3628
|
+
active.add(value);
|
|
3629
|
+
const children = Array.isArray(value) ? value : Object.values(value);
|
|
3630
|
+
let cost = 1;
|
|
3631
|
+
let height = 0;
|
|
3632
|
+
for (const child of children) {
|
|
3633
|
+
const childResult = visit2(child, depth + 1);
|
|
3634
|
+
cost = addCost(cost, childResult.cost, source, checkExpansionBudget);
|
|
3635
|
+
height = Math.max(height, childResult.height + 1);
|
|
3636
|
+
}
|
|
3637
|
+
active.delete(value);
|
|
3638
|
+
const result = { cost, height };
|
|
3639
|
+
completed.set(value, result);
|
|
3640
|
+
return result;
|
|
3641
|
+
};
|
|
3642
|
+
visit2(root, 0);
|
|
3643
|
+
}
|
|
3644
|
+
|
|
3583
3645
|
// src/overwrite.ts
|
|
3584
3646
|
import fs3 from "fs";
|
|
3585
3647
|
import { createRequire as createRequire2 } from "module";
|
|
3586
3648
|
import path3 from "path";
|
|
3649
|
+
import { isDeepStrictEqual } from "util";
|
|
3587
3650
|
|
|
3588
3651
|
// src/paths.ts
|
|
3589
3652
|
import fs from "fs";
|
|
@@ -3621,6 +3684,8 @@ var PATHS = {
|
|
|
3621
3684
|
subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
|
|
3622
3685
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
3623
3686
|
logFile: path.join(DIRS.logs, "mihomo.log"),
|
|
3687
|
+
/** CLI 结构化操作事件;独立于内核文本日志及其归档编号,由 diagnostic-events.ts 自管轮转 */
|
|
3688
|
+
diagnosticEventsFile: path.join(DIRS.logs, "diagnostic.jsonl"),
|
|
3624
3689
|
pidFile: path.join(DIRS.runtime, "pid"),
|
|
3625
3690
|
/**
|
|
3626
3691
|
* installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
|
|
@@ -3643,9 +3708,11 @@ var PATHS = {
|
|
|
3643
3708
|
* 各锁的可达竞态路径:
|
|
3644
3709
|
* - serviceLock:慢速 start(订阅更新约 10s)持锁期间另一终端 stop
|
|
3645
3710
|
* - subscriptionCacheLock:慢速 `sub update`(并行下载、逐条回写缓存)期间另一终端 `reset`
|
|
3711
|
+
* - subscriptionCommitLock:同一订阅的 YAML 与缓存提交、缓存失败回滚必须作为一个串行区间
|
|
3646
3712
|
*/
|
|
3647
3713
|
settingsLock: path.join(USER_DATA_DIR, "settings.lock"),
|
|
3648
3714
|
subscriptionCacheLock: path.join(USER_DATA_DIR, "subscription-cache.lock"),
|
|
3715
|
+
subscriptionCommitLock: path.join(USER_DATA_DIR, "subscription-commit.lock"),
|
|
3649
3716
|
serviceLock: path.join(USER_DATA_DIR, "service.lock"),
|
|
3650
3717
|
/**
|
|
3651
3718
|
* 「服务被要求停止」的单调计数(`stop-epoch.ts` 的 `bumpStopEpoch`/`readStopEpoch`,
|
|
@@ -3709,6 +3776,10 @@ function rmrf(dir) {
|
|
|
3709
3776
|
}
|
|
3710
3777
|
function cleanupStaleTmpFiles() {
|
|
3711
3778
|
const cutoff = Date.now() - 60 * 60 * 1e3;
|
|
3779
|
+
const isCliMkdtempEntry = (entry, prefix) => {
|
|
3780
|
+
const suffix = entry.startsWith(prefix) ? entry.slice(prefix.length) : "";
|
|
3781
|
+
return /^[A-Za-z0-9]{6}$/.test(suffix) && /[A-Z0-9]/.test(suffix);
|
|
3782
|
+
};
|
|
3712
3783
|
for (const dir of [USER_DATA_DIR, DIRS.subscriptions, DIRS.runtime, DIRS.kernel]) {
|
|
3713
3784
|
let entries;
|
|
3714
3785
|
try {
|
|
@@ -3717,14 +3788,17 @@ function cleanupStaleTmpFiles() {
|
|
|
3717
3788
|
continue;
|
|
3718
3789
|
}
|
|
3719
3790
|
for (const entry of entries) {
|
|
3720
|
-
const isAtomicTmpFile = entry
|
|
3721
|
-
const isKernelTmpDir = dir === DIRS.kernel && entry
|
|
3722
|
-
const isConfigCheckTmpDir = dir === USER_DATA_DIR && entry
|
|
3791
|
+
const isAtomicTmpFile = /^.+\.\d+\.\d+\.tmp$/.test(entry);
|
|
3792
|
+
const isKernelTmpDir = dir === DIRS.kernel && isCliMkdtempEntry(entry, ".tmp-");
|
|
3793
|
+
const isConfigCheckTmpDir = dir === USER_DATA_DIR && isCliMkdtempEntry(entry, "check-");
|
|
3723
3794
|
const isPlistStage = dir === USER_DATA_DIR && entry === "service.plist.stage";
|
|
3724
3795
|
if (!isAtomicTmpFile && !isKernelTmpDir && !isConfigCheckTmpDir && !isPlistStage) continue;
|
|
3725
3796
|
const full = path.join(dir, entry);
|
|
3726
3797
|
try {
|
|
3727
|
-
|
|
3798
|
+
const stat = fs.lstatSync(full);
|
|
3799
|
+
if ((isAtomicTmpFile || isPlistStage) && !stat.isFile()) continue;
|
|
3800
|
+
if ((isKernelTmpDir || isConfigCheckTmpDir) && !stat.isDirectory()) continue;
|
|
3801
|
+
if (stat.mtimeMs >= cutoff) continue;
|
|
3728
3802
|
fs.rmSync(full, { recursive: true, force: true });
|
|
3729
3803
|
} catch {
|
|
3730
3804
|
}
|
|
@@ -3976,8 +4050,12 @@ function addSubscription(url, name) {
|
|
|
3976
4050
|
validateSubscriptionName(name);
|
|
3977
4051
|
updateSettings((settings) => {
|
|
3978
4052
|
const subs = getSubscriptions(settings);
|
|
3979
|
-
|
|
3980
|
-
|
|
4053
|
+
const normalizedName = name.toLowerCase();
|
|
4054
|
+
const existing = subs.find((s) => s.name.toLowerCase() === normalizedName);
|
|
4055
|
+
if (existing) {
|
|
4056
|
+
throw new CliError(
|
|
4057
|
+
`\u8BA2\u9605\u540D\u79F0 "${name}" \u4E0E\u73B0\u6709\u8BA2\u9605 "${existing.name}" \u51B2\u7A81\uFF08\u540D\u79F0\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo-cli sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo-cli sub remove ${existing.name}\uFF09`
|
|
4058
|
+
);
|
|
3981
4059
|
}
|
|
3982
4060
|
subs.push({ name, url });
|
|
3983
4061
|
const updates = { subscriptions: subs };
|
|
@@ -4516,6 +4594,7 @@ function readOverwriteFiles() {
|
|
|
4516
4594
|
const content = fs3.readFileSync(filePath, "utf8");
|
|
4517
4595
|
if (isBlankYamlDocument(content)) continue;
|
|
4518
4596
|
const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
|
|
4597
|
+
assertConfigGraphSafe(parsed, `\u8986\u5199\u6587\u4EF6 "${file}"`);
|
|
4519
4598
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
4520
4599
|
const { match, enabled, ...config } = parsed;
|
|
4521
4600
|
assertNoMetadataKeyLookalikes(config, file);
|
|
@@ -4558,13 +4637,13 @@ function snapshotLockedKeys(config) {
|
|
|
4558
4637
|
for (const k of EFFECTIVELY_LOCKED_KEYS) {
|
|
4559
4638
|
if (k in config) snap[k] = config[k];
|
|
4560
4639
|
}
|
|
4561
|
-
return snap;
|
|
4640
|
+
return structuredClone(snap);
|
|
4562
4641
|
}
|
|
4563
4642
|
function diffLockedKeys(before, after) {
|
|
4564
4643
|
return EFFECTIVELY_LOCKED_KEYS.filter((k) => {
|
|
4565
4644
|
const had = k in before;
|
|
4566
4645
|
const has = k in after;
|
|
4567
|
-
return had !== has ? has : had && before[k]
|
|
4646
|
+
return had !== has ? has : had && !isDeepStrictEqual(before[k], after[k]);
|
|
4568
4647
|
});
|
|
4569
4648
|
}
|
|
4570
4649
|
function applyOverwrite(baseConfig, files, opts) {
|
|
@@ -4575,12 +4654,14 @@ function applyOverwrite(baseConfig, files, opts) {
|
|
|
4575
4654
|
const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
|
|
4576
4655
|
for (const file of files) {
|
|
4577
4656
|
if (file.transform) {
|
|
4578
|
-
const before = snapshotLockedKeys(result);
|
|
4579
4657
|
const notes = [];
|
|
4580
4658
|
const ctx = { subscription, mode: opts.mode, warn: (message) => notes.push(message) };
|
|
4659
|
+
let before;
|
|
4581
4660
|
let returned;
|
|
4582
4661
|
try {
|
|
4662
|
+
before = snapshotLockedKeys(result);
|
|
4583
4663
|
returned = file.transform(result, ctx);
|
|
4664
|
+
assertConfigGraphSafe(result);
|
|
4584
4665
|
} catch (e) {
|
|
4585
4666
|
throw new CliError(`\u8986\u5199\u811A\u672C "${file.name}" \u6267\u884C\u5931\u8D25: ${firstLine(e.message ?? String(e))}`, {
|
|
4586
4667
|
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
@@ -4638,6 +4719,7 @@ function parseConfigContent(content, errorMsg) {
|
|
|
4638
4719
|
if (result == null || typeof result !== "object" || Array.isArray(result)) {
|
|
4639
4720
|
throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
4640
4721
|
}
|
|
4722
|
+
assertConfigGraphSafe(result, label);
|
|
4641
4723
|
return result;
|
|
4642
4724
|
}
|
|
4643
4725
|
function dumpYaml(obj) {
|
|
@@ -4784,6 +4866,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4784
4866
|
"skip-domain": ["+.push.apple.com"]
|
|
4785
4867
|
};
|
|
4786
4868
|
}
|
|
4869
|
+
if (overwriteFiles.some((file) => !file.transform)) assertConfigGraphSafe(merged, "\u5408\u5E76\u540E\u7684\u914D\u7F6E");
|
|
4787
4870
|
assertConfigShape(merged);
|
|
4788
4871
|
return { config: merged, warnings: lockedWarnings, overwriteSummaries };
|
|
4789
4872
|
}
|
|
@@ -4829,13 +4912,13 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
|
|
|
4829
4912
|
);
|
|
4830
4913
|
return hint;
|
|
4831
4914
|
}
|
|
4832
|
-
async function validateConfigWithKernel(
|
|
4915
|
+
async function validateConfigWithKernel(configContent, overwriteSummaries) {
|
|
4833
4916
|
assertKernelInstalled();
|
|
4834
4917
|
ensureDirs();
|
|
4835
4918
|
const stageDir = fs4.mkdtempSync(path4.join(USER_DATA_DIR, "check-"));
|
|
4836
4919
|
const stageFile = path4.join(stageDir, "config.yaml");
|
|
4837
4920
|
try {
|
|
4838
|
-
fs4.writeFileSync(stageFile,
|
|
4921
|
+
fs4.writeFileSync(stageFile, configContent, { mode: 384 });
|
|
4839
4922
|
try {
|
|
4840
4923
|
await promisify(execFile)(PATHS.mihomoBinary, ["-t", "-d", DIRS.data, "-f", stageFile], {
|
|
4841
4924
|
encoding: "utf8",
|
|
@@ -4852,9 +4935,15 @@ ${error.stderr || ""}`).trim();
|
|
|
4852
4935
|
hint: buildKernelRejectHint("", [], { timedOut: true })
|
|
4853
4936
|
});
|
|
4854
4937
|
}
|
|
4938
|
+
if (typeof error.code !== "number") {
|
|
4939
|
+
const reason = detail || sanitizeTerminal(error.message);
|
|
4940
|
+
const hint = ["", ...reason.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
|
|
4941
|
+
hint.push("", `${HINT_INDENT}\u8BF7\u68C0\u67E5\u5185\u6838\u6587\u4EF6\u662F\u5426\u53EF\u6267\u884C\uFF08\u6743\u9650\u4E0E\u7CFB\u7EDF\u67B6\u6784\uFF09\uFF0C\u6216\u8FD0\u884C mihomo-cli kernel \u91CD\u65B0\u5B89\u88C5\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
|
|
4942
|
+
throw new CliError("\u5185\u6838\u672A\u6267\u884C\u6216\u5F02\u5E38\u7EC8\u6B62\uFF0C\u914D\u7F6E\u6821\u9A8C\u672A\u5B8C\u6210", { label: "\u5185\u6838\u9519\u8BEF", hint });
|
|
4943
|
+
}
|
|
4855
4944
|
throw new CliError("\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
|
|
4856
4945
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4857
|
-
hint: buildKernelRejectHint(detail || error.message, overwriteSummaries)
|
|
4946
|
+
hint: buildKernelRejectHint(detail || sanitizeTerminal(error.message), overwriteSummaries)
|
|
4858
4947
|
});
|
|
4859
4948
|
}
|
|
4860
4949
|
} finally {
|
|
@@ -5115,15 +5204,19 @@ function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
|
5115
5204
|
}
|
|
5116
5205
|
var UNLOADED_POLL_ATTEMPTS = 25;
|
|
5117
5206
|
var UNLOADED_POLL_INTERVAL_MS = 200;
|
|
5118
|
-
async function waitUntilUnloaded(target = serviceTarget()) {
|
|
5207
|
+
async function waitUntilUnloaded(target = serviceTarget(), options = {}) {
|
|
5119
5208
|
for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
|
|
5120
5209
|
const result = runLaunchctl(["print", target]);
|
|
5121
|
-
if (result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
5210
|
+
if (result.status === LAUNCHCTL_NOT_LOADED) return "unloaded";
|
|
5122
5211
|
if (result.status !== 0) {
|
|
5123
5212
|
throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
5124
5213
|
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
|
|
5125
5214
|
});
|
|
5126
5215
|
}
|
|
5216
|
+
if (options.acceptReplacement) {
|
|
5217
|
+
const { state, pid } = parseServicePrint(result.stdout);
|
|
5218
|
+
if (state === "running" && pid !== null && options.acceptReplacement(pid)) return "replacement-running";
|
|
5219
|
+
}
|
|
5127
5220
|
await sleep(UNLOADED_POLL_INTERVAL_MS);
|
|
5128
5221
|
}
|
|
5129
5222
|
throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
|
|
@@ -5317,10 +5410,242 @@ function walk(node, withinProvider, state) {
|
|
|
5317
5410
|
return node;
|
|
5318
5411
|
}
|
|
5319
5412
|
function redactConfigSecrets(config) {
|
|
5413
|
+
assertConfigGraphExpansionSafe(config);
|
|
5320
5414
|
const state = { changed: false };
|
|
5321
5415
|
return { config: walk(config, false, state), changed: state.changed };
|
|
5322
5416
|
}
|
|
5323
5417
|
|
|
5418
|
+
// src/diagnostic-events.ts
|
|
5419
|
+
import { createHash, randomUUID } from "crypto";
|
|
5420
|
+
import fs7 from "fs";
|
|
5421
|
+
|
|
5422
|
+
// src/log-files.ts
|
|
5423
|
+
import fs6 from "fs";
|
|
5424
|
+
import path5 from "path";
|
|
5425
|
+
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5426
|
+
var LOG_TAIL_LINES = 15;
|
|
5427
|
+
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5428
|
+
function isArchiveLogFilename(filename) {
|
|
5429
|
+
return ARCHIVE_LOG_RE.test(filename);
|
|
5430
|
+
}
|
|
5431
|
+
function rotateAndCleanupLogs() {
|
|
5432
|
+
rotateLog();
|
|
5433
|
+
cleanupOldLogs();
|
|
5434
|
+
}
|
|
5435
|
+
function readLogTail() {
|
|
5436
|
+
const TAIL_BYTES = 64 * 1024;
|
|
5437
|
+
let fd = null;
|
|
5438
|
+
try {
|
|
5439
|
+
const size = fs6.statSync(PATHS.logFile).size;
|
|
5440
|
+
if (size === 0) return [];
|
|
5441
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
5442
|
+
const length = size - start;
|
|
5443
|
+
const buf = Buffer.alloc(length);
|
|
5444
|
+
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5445
|
+
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5446
|
+
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5447
|
+
} catch {
|
|
5448
|
+
return [];
|
|
5449
|
+
} finally {
|
|
5450
|
+
if (fd !== null) {
|
|
5451
|
+
try {
|
|
5452
|
+
fs6.closeSync(fd);
|
|
5453
|
+
} catch {
|
|
5454
|
+
}
|
|
5455
|
+
}
|
|
5456
|
+
}
|
|
5457
|
+
}
|
|
5458
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5459
|
+
function allocateArchivePath(prefix = "mihomo", extension = "log") {
|
|
5460
|
+
const timestamp = formatLocalTimestamp();
|
|
5461
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5462
|
+
const name = seq === 0 ? `${prefix}.${timestamp}.${extension}` : `${prefix}.${timestamp}.${seq}.${extension}`;
|
|
5463
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
5464
|
+
let fd = null;
|
|
5465
|
+
try {
|
|
5466
|
+
fd = fs6.openSync(archivePath, "wx");
|
|
5467
|
+
} catch (e) {
|
|
5468
|
+
if (e.code === "EEXIST") continue;
|
|
5469
|
+
throw e;
|
|
5470
|
+
}
|
|
5471
|
+
try {
|
|
5472
|
+
fs6.closeSync(fd);
|
|
5473
|
+
} catch {
|
|
5474
|
+
}
|
|
5475
|
+
return archivePath;
|
|
5476
|
+
}
|
|
5477
|
+
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
5478
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
5479
|
+
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
5480
|
+
});
|
|
5481
|
+
}
|
|
5482
|
+
function rotateFile(filePath, minBytes, prefix = "mihomo", extension = "log") {
|
|
5483
|
+
let stat;
|
|
5484
|
+
try {
|
|
5485
|
+
stat = fs6.statSync(filePath);
|
|
5486
|
+
} catch (e) {
|
|
5487
|
+
if (e.code === "ENOENT") return false;
|
|
5488
|
+
throw e;
|
|
5489
|
+
}
|
|
5490
|
+
if (stat.size < minBytes) return false;
|
|
5491
|
+
const rotatedPath = allocateArchivePath(prefix, extension);
|
|
5492
|
+
try {
|
|
5493
|
+
fs6.renameSync(filePath, rotatedPath);
|
|
5494
|
+
return true;
|
|
5495
|
+
} catch (e) {
|
|
5496
|
+
try {
|
|
5497
|
+
fs6.unlinkSync(rotatedPath);
|
|
5498
|
+
} catch {
|
|
5499
|
+
}
|
|
5500
|
+
if (e.code === "ENOENT") return false;
|
|
5501
|
+
throw e;
|
|
5502
|
+
}
|
|
5503
|
+
}
|
|
5504
|
+
function rotateLog() {
|
|
5505
|
+
rotateFile(PATHS.logFile, 1);
|
|
5506
|
+
}
|
|
5507
|
+
function cleanupOldArchives(isArchive) {
|
|
5508
|
+
const logsDir = DIRS.logs;
|
|
5509
|
+
if (!fs6.existsSync(logsDir)) return;
|
|
5510
|
+
const files = fs6.readdirSync(logsDir);
|
|
5511
|
+
const now = Date.now();
|
|
5512
|
+
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5513
|
+
for (const file of files) {
|
|
5514
|
+
if (!isArchive(file)) continue;
|
|
5515
|
+
try {
|
|
5516
|
+
const filePath = path5.join(logsDir, file);
|
|
5517
|
+
const stat = fs6.statSync(filePath);
|
|
5518
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5519
|
+
fs6.unlinkSync(filePath);
|
|
5520
|
+
}
|
|
5521
|
+
} catch {
|
|
5522
|
+
}
|
|
5523
|
+
}
|
|
5524
|
+
}
|
|
5525
|
+
function cleanupOldLogs() {
|
|
5526
|
+
cleanupOldArchives(isArchiveLogFilename);
|
|
5527
|
+
}
|
|
5528
|
+
function listLogs() {
|
|
5529
|
+
const logsDir = DIRS.logs;
|
|
5530
|
+
const result = { current: null, archives: [] };
|
|
5531
|
+
if (fs6.existsSync(PATHS.logFile)) {
|
|
5532
|
+
const stat = fs6.statSync(PATHS.logFile);
|
|
5533
|
+
result.current = {
|
|
5534
|
+
name: "mihomo.log (\u5F53\u524D)",
|
|
5535
|
+
path: PATHS.logFile,
|
|
5536
|
+
size: stat.size,
|
|
5537
|
+
mtime: stat.mtime,
|
|
5538
|
+
isCurrent: true
|
|
5539
|
+
};
|
|
5540
|
+
}
|
|
5541
|
+
if (!fs6.existsSync(logsDir)) return result;
|
|
5542
|
+
const files = fs6.readdirSync(logsDir);
|
|
5543
|
+
for (const file of files) {
|
|
5544
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
5545
|
+
try {
|
|
5546
|
+
const filePath = path5.join(logsDir, file);
|
|
5547
|
+
const stat = fs6.statSync(filePath);
|
|
5548
|
+
result.archives.push({
|
|
5549
|
+
name: file,
|
|
5550
|
+
path: filePath,
|
|
5551
|
+
size: stat.size,
|
|
5552
|
+
mtime: stat.mtime,
|
|
5553
|
+
isCurrent: false
|
|
5554
|
+
});
|
|
5555
|
+
} catch {
|
|
5556
|
+
}
|
|
5557
|
+
}
|
|
5558
|
+
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
5559
|
+
return result;
|
|
5560
|
+
}
|
|
5561
|
+
|
|
5562
|
+
// src/diagnostic-events.ts
|
|
5563
|
+
var context = null;
|
|
5564
|
+
var exitHookRegistered = false;
|
|
5565
|
+
var DIAGNOSTIC_LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
5566
|
+
var DIAGNOSTIC_ARCHIVE_RE = /^diagnostic\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/;
|
|
5567
|
+
function beginDiagnosticOperation(command) {
|
|
5568
|
+
context = { operationId: randomUUID(), command, startedAt: Date.now() };
|
|
5569
|
+
if (exitHookRegistered) return;
|
|
5570
|
+
exitHookRegistered = true;
|
|
5571
|
+
process.once("exit", (exitCode) => {
|
|
5572
|
+
if (!context) return;
|
|
5573
|
+
recordDiagnosticEvent("cli.command", exitCode === 0 ? "success" : "failure", {
|
|
5574
|
+
exitCode,
|
|
5575
|
+
durationMs: Date.now() - context.startedAt
|
|
5576
|
+
});
|
|
5577
|
+
});
|
|
5578
|
+
}
|
|
5579
|
+
function setDiagnosticCommand(command) {
|
|
5580
|
+
if (context) context.command = command;
|
|
5581
|
+
}
|
|
5582
|
+
function hashDiagnosticContent(content) {
|
|
5583
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
5584
|
+
}
|
|
5585
|
+
function hashDiagnosticFile(filePath) {
|
|
5586
|
+
try {
|
|
5587
|
+
return hashDiagnosticContent(fs7.readFileSync(filePath, "utf8"));
|
|
5588
|
+
} catch {
|
|
5589
|
+
return null;
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
5592
|
+
var KNOWN_ERROR_NAMES = /* @__PURE__ */ new Set(["Error", "TypeError", "RangeError", "SyntaxError", "CliError", "AbortError", "TimeoutError", "SudoAuthError"]);
|
|
5593
|
+
function safeErrorCode(value) {
|
|
5594
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
5595
|
+
if (typeof value === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(value)) return value;
|
|
5596
|
+
return void 0;
|
|
5597
|
+
}
|
|
5598
|
+
function safeHttpStatus(value) {
|
|
5599
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : void 0;
|
|
5600
|
+
}
|
|
5601
|
+
function diagnosticErrorDetails(error) {
|
|
5602
|
+
if (!(error instanceof Error)) return { errorType: "NonError" };
|
|
5603
|
+
const details = {};
|
|
5604
|
+
let current = error;
|
|
5605
|
+
for (let depth = 0; depth < 6 && current instanceof Error; depth++) {
|
|
5606
|
+
details.errorType = KNOWN_ERROR_NAMES.has(current.name) ? current.name : "Error";
|
|
5607
|
+
if (current instanceof CliError) details.errorLabel = current.label;
|
|
5608
|
+
if (current.name === "AbortError") details.aborted = true;
|
|
5609
|
+
const withMetadata = current;
|
|
5610
|
+
const errorCode = safeErrorCode(withMetadata.code);
|
|
5611
|
+
const httpStatus = safeHttpStatus(withMetadata.response?.status);
|
|
5612
|
+
if (details.errorCode === void 0 && errorCode !== void 0) details.errorCode = errorCode;
|
|
5613
|
+
if (details.httpStatus === void 0 && httpStatus !== void 0) details.httpStatus = httpStatus;
|
|
5614
|
+
current = withMetadata.cause;
|
|
5615
|
+
}
|
|
5616
|
+
return details;
|
|
5617
|
+
}
|
|
5618
|
+
function rotateDiagnosticLogIfNeeded() {
|
|
5619
|
+
if (rotateFile(PATHS.diagnosticEventsFile, DIAGNOSTIC_LOG_MAX_BYTES, "diagnostic", "jsonl")) {
|
|
5620
|
+
cleanupOldArchives((file) => DIAGNOSTIC_ARCHIVE_RE.test(file));
|
|
5621
|
+
}
|
|
5622
|
+
}
|
|
5623
|
+
function recordDiagnosticEvent(event, result, details = {}) {
|
|
5624
|
+
if (!context) return;
|
|
5625
|
+
try {
|
|
5626
|
+
const line = `${JSON.stringify({
|
|
5627
|
+
v: 1,
|
|
5628
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5629
|
+
event,
|
|
5630
|
+
result,
|
|
5631
|
+
operationId: context.operationId,
|
|
5632
|
+
command: context.command,
|
|
5633
|
+
pid: process.pid,
|
|
5634
|
+
...details
|
|
5635
|
+
})}
|
|
5636
|
+
`;
|
|
5637
|
+
rotateDiagnosticLogIfNeeded();
|
|
5638
|
+
try {
|
|
5639
|
+
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5640
|
+
} catch (e) {
|
|
5641
|
+
if (e.code !== "ENOENT") throw e;
|
|
5642
|
+
fs7.mkdirSync(DIRS.logs, { recursive: true, mode: 448 });
|
|
5643
|
+
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5644
|
+
}
|
|
5645
|
+
} catch {
|
|
5646
|
+
}
|
|
5647
|
+
}
|
|
5648
|
+
|
|
5324
5649
|
// src/http.ts
|
|
5325
5650
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5326
5651
|
var MAX_REDIRECTS = 20;
|
|
@@ -5384,8 +5709,7 @@ function createHttpClient(options = {}) {
|
|
|
5384
5709
|
throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
|
|
5385
5710
|
}
|
|
5386
5711
|
const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
|
|
5387
|
-
|
|
5388
|
-
return { data, headers: response.headers };
|
|
5712
|
+
return { data: text, headers: response.headers };
|
|
5389
5713
|
} catch (e) {
|
|
5390
5714
|
if (controller.signal.aborted && e.name === "AbortError") {
|
|
5391
5715
|
throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
|
|
@@ -5560,6 +5884,15 @@ function resolveSubscription(subs, pattern) {
|
|
|
5560
5884
|
includes.push(s);
|
|
5561
5885
|
}
|
|
5562
5886
|
}
|
|
5887
|
+
if (exact.length > 1) {
|
|
5888
|
+
throw new CliError(`\u8BA2\u9605\u540D\u79F0 "${pattern}" \u6709\u591A\u4E2A\u7CBE\u786E\u5339\u914D\uFF08\u540D\u79F0\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09`, {
|
|
5889
|
+
hint: [
|
|
5890
|
+
"\u8BF7\u624B\u5DE5\u7F16\u8F91 settings.json\uFF0C\u5220\u9664\u591A\u4F59\u6761\u76EE\uFF0C\u6216\u5C06\u540D\u79F0\u4E0E\u5BF9\u5E94 YAML \u6587\u4EF6\u4E00\u8D77\u6539\u540D\uFF0C\u786E\u4FDD\u5FFD\u7565\u5927\u5C0F\u5199\u540E\u4ECD\u552F\u4E00",
|
|
5891
|
+
"\u51B2\u7A81\u7684\u8BA2\u9605:",
|
|
5892
|
+
...exact.map((s) => ` ${s.name}`)
|
|
5893
|
+
]
|
|
5894
|
+
});
|
|
5895
|
+
}
|
|
5563
5896
|
const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
|
|
5564
5897
|
if (matched.length === 0) {
|
|
5565
5898
|
throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
|
|
@@ -5589,66 +5922,145 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
5589
5922
|
});
|
|
5590
5923
|
}
|
|
5591
5924
|
async function downloadSubscription(url, subName, signal) {
|
|
5592
|
-
|
|
5925
|
+
const startedAt = Date.now();
|
|
5926
|
+
let stage = "http";
|
|
5927
|
+
let rollback;
|
|
5593
5928
|
try {
|
|
5594
|
-
response
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5599
|
-
|
|
5600
|
-
|
|
5601
|
-
|
|
5602
|
-
|
|
5929
|
+
let response;
|
|
5930
|
+
try {
|
|
5931
|
+
response = await HTTP_CLIENT.get(url, { signal });
|
|
5932
|
+
} catch (e) {
|
|
5933
|
+
const maskedUrl = maskUrl(url);
|
|
5934
|
+
let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
|
|
5935
|
+
const err = e;
|
|
5936
|
+
if (err.response) {
|
|
5937
|
+
errorMsg += ` (HTTP ${err.response.status})`;
|
|
5938
|
+
}
|
|
5939
|
+
errorMsg += `
|
|
5603
5940
|
URL: ${maskedUrl}`;
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
|
|
5609
|
-
|
|
5610
|
-
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5941
|
+
throw new Error(errorMsg, { cause: e });
|
|
5942
|
+
}
|
|
5943
|
+
stage = "empty-response";
|
|
5944
|
+
const content = response.data;
|
|
5945
|
+
if (!content?.trim()) {
|
|
5946
|
+
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5947
|
+
}
|
|
5948
|
+
stage = "parse";
|
|
5949
|
+
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5950
|
+
stage = "content-validation";
|
|
5951
|
+
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5952
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5953
|
+
const rawAfterSha256 = hashDiagnosticContent(content);
|
|
5954
|
+
const meta = extractSubscriptionMeta(response.headers);
|
|
5955
|
+
stage = "raw-commit";
|
|
5956
|
+
const previousContent = withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5957
|
+
const previousContent2 = readSubscriptionRawConfig(subName);
|
|
5958
|
+
saveSubscriptionRawConfig(subName, content);
|
|
5959
|
+
stage = "cache-commit";
|
|
5960
|
+
try {
|
|
5961
|
+
saveSubscriptionMeta(subName, meta);
|
|
5962
|
+
} catch (e) {
|
|
5963
|
+
let rollbackHint;
|
|
5964
|
+
try {
|
|
5965
|
+
if (previousContent2 === null) {
|
|
5966
|
+
removeSubscriptionRawConfig(subName);
|
|
5967
|
+
rollback = "deleted";
|
|
5968
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
|
|
5969
|
+
} else {
|
|
5970
|
+
saveSubscriptionRawConfig(subName, previousContent2);
|
|
5971
|
+
rollback = "restored";
|
|
5972
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
|
|
5973
|
+
}
|
|
5974
|
+
} catch (rollbackError) {
|
|
5975
|
+
rollback = "failed";
|
|
5976
|
+
rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
|
|
5977
|
+
}
|
|
5978
|
+
throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
|
|
5979
|
+
label: "\u66F4\u65B0\u5931\u8D25",
|
|
5980
|
+
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5981
|
+
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5982
|
+
hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
5983
|
+
});
|
|
5984
|
+
}
|
|
5985
|
+
return previousContent2;
|
|
5986
|
+
});
|
|
5987
|
+
const changed = previousContent !== content;
|
|
5988
|
+
const rawBeforeSha256 = previousContent === null ? null : changed ? hashDiagnosticContent(previousContent) : rawAfterSha256;
|
|
5989
|
+
recordDiagnosticEvent("subscription.download", "success", {
|
|
5990
|
+
stage: "commit",
|
|
5991
|
+
durationMs: Date.now() - startedAt,
|
|
5992
|
+
rawBeforeSha256,
|
|
5993
|
+
rawAfterSha256,
|
|
5994
|
+
changed,
|
|
5995
|
+
proxies,
|
|
5996
|
+
proxyGroups
|
|
5997
|
+
});
|
|
5998
|
+
return { proxies, proxyGroups };
|
|
5616
5999
|
} catch (e) {
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
label: "\u66F4\u65B0\u5931\u8D25",
|
|
5623
|
-
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5624
|
-
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5625
|
-
hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
6000
|
+
recordDiagnosticEvent("subscription.download", signal?.aborted === true ? "aborted" : "failure", {
|
|
6001
|
+
stage,
|
|
6002
|
+
durationMs: Date.now() - startedAt,
|
|
6003
|
+
rollback,
|
|
6004
|
+
...diagnosticErrorDetails(e)
|
|
5626
6005
|
});
|
|
6006
|
+
throw e;
|
|
5627
6007
|
}
|
|
5628
|
-
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5629
|
-
return { proxies, proxyGroups };
|
|
5630
6008
|
}
|
|
5631
|
-
async function prepareConfigForStart(mode, subName) {
|
|
5632
|
-
|
|
6009
|
+
async function prepareConfigForStart(mode, subName, purpose = "start") {
|
|
6010
|
+
const startedAt = Date.now();
|
|
6011
|
+
let stage = "read";
|
|
6012
|
+
let sourceRawSha256;
|
|
6013
|
+
let candidateSha256;
|
|
5633
6014
|
try {
|
|
5634
|
-
rawContent
|
|
5635
|
-
|
|
5636
|
-
|
|
5637
|
-
|
|
5638
|
-
|
|
5639
|
-
|
|
6015
|
+
let rawContent;
|
|
6016
|
+
try {
|
|
6017
|
+
rawContent = requireSubscriptionRawConfig(subName);
|
|
6018
|
+
} catch (e) {
|
|
6019
|
+
if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
|
|
6020
|
+
throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
|
|
6021
|
+
hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
|
|
6022
|
+
});
|
|
6023
|
+
}
|
|
6024
|
+
throw e;
|
|
5640
6025
|
}
|
|
6026
|
+
sourceRawSha256 = hashDiagnosticContent(rawContent);
|
|
6027
|
+
stage = "build";
|
|
6028
|
+
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
6029
|
+
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
6030
|
+
const candidateContent = dumpYaml(buildResult.config);
|
|
6031
|
+
candidateSha256 = hashDiagnosticContent(candidateContent);
|
|
6032
|
+
stage = "validate";
|
|
6033
|
+
await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
|
|
6034
|
+
const info = countConfigNodes(buildResult.config);
|
|
6035
|
+
recordDiagnosticEvent("config.prepare", "success", {
|
|
6036
|
+
stage,
|
|
6037
|
+
purpose,
|
|
6038
|
+
mode,
|
|
6039
|
+
durationMs: Date.now() - startedAt,
|
|
6040
|
+
sourceRawSha256,
|
|
6041
|
+
candidateSha256,
|
|
6042
|
+
...info
|
|
6043
|
+
});
|
|
6044
|
+
return {
|
|
6045
|
+
buildResult,
|
|
6046
|
+
info,
|
|
6047
|
+
diagnostic: { sourceRawSha256, candidateSha256 }
|
|
6048
|
+
};
|
|
6049
|
+
} catch (e) {
|
|
6050
|
+
recordDiagnosticEvent("config.prepare", "failure", {
|
|
6051
|
+
stage,
|
|
6052
|
+
purpose,
|
|
6053
|
+
mode,
|
|
6054
|
+
durationMs: Date.now() - startedAt,
|
|
6055
|
+
sourceRawSha256,
|
|
6056
|
+
candidateSha256,
|
|
6057
|
+
...diagnosticErrorDetails(e)
|
|
6058
|
+
});
|
|
5641
6059
|
throw e;
|
|
5642
6060
|
}
|
|
5643
|
-
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5644
|
-
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5645
|
-
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
5646
|
-
return {
|
|
5647
|
-
buildResult,
|
|
5648
|
-
info: countConfigNodes(buildResult.config)
|
|
5649
|
-
};
|
|
5650
6061
|
}
|
|
5651
6062
|
function commitPreparedConfig(prepared) {
|
|
6063
|
+
const startedAt = Date.now();
|
|
5652
6064
|
const { buildResult } = prepared;
|
|
5653
6065
|
if (buildResult.warnings.length > 0) {
|
|
5654
6066
|
for (const warning of buildResult.warnings) {
|
|
@@ -5656,7 +6068,30 @@ function commitPreparedConfig(prepared) {
|
|
|
5656
6068
|
}
|
|
5657
6069
|
console.log("");
|
|
5658
6070
|
}
|
|
5659
|
-
|
|
6071
|
+
const runtimeBeforeSha256 = hashDiagnosticFile(PATHS.configFile);
|
|
6072
|
+
try {
|
|
6073
|
+
writeMihomoConfig(buildResult.config);
|
|
6074
|
+
} catch (e) {
|
|
6075
|
+
recordDiagnosticEvent("config.commit", "failure", {
|
|
6076
|
+
stage: "write",
|
|
6077
|
+
durationMs: Date.now() - startedAt,
|
|
6078
|
+
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6079
|
+
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6080
|
+
runtimeBeforeSha256,
|
|
6081
|
+
...diagnosticErrorDetails(e)
|
|
6082
|
+
});
|
|
6083
|
+
throw e;
|
|
6084
|
+
}
|
|
6085
|
+
recordDiagnosticEvent("config.commit", "success", {
|
|
6086
|
+
stage: "write",
|
|
6087
|
+
durationMs: Date.now() - startedAt,
|
|
6088
|
+
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6089
|
+
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6090
|
+
runtimeBeforeSha256,
|
|
6091
|
+
runtimeAfterSha256: prepared.diagnostic.candidateSha256,
|
|
6092
|
+
changed: runtimeBeforeSha256 === null ? null : runtimeBeforeSha256 !== prepared.diagnostic.candidateSha256,
|
|
6093
|
+
...prepared.info
|
|
6094
|
+
});
|
|
5660
6095
|
return prepared.info;
|
|
5661
6096
|
}
|
|
5662
6097
|
function needsAutoUpdate(sub) {
|
|
@@ -5689,6 +6124,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5689
6124
|
const allSubs = getSubscriptionsWithCache();
|
|
5690
6125
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
5691
6126
|
if (staleSubs.length === 0) {
|
|
6127
|
+
recordDiagnosticEvent("subscription.auto-update", "skipped", { reason: "fresh", staleCount: 0 });
|
|
5692
6128
|
return;
|
|
5693
6129
|
}
|
|
5694
6130
|
if (staleSubs.length === 1) {
|
|
@@ -5718,9 +6154,24 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5718
6154
|
});
|
|
5719
6155
|
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`));
|
|
5720
6156
|
}
|
|
6157
|
+
const timedOut = controller.signal.aborted;
|
|
6158
|
+
let succeeded = 0;
|
|
6159
|
+
let abortedCount = 0;
|
|
6160
|
+
let failed = 0;
|
|
5721
6161
|
for (const r of results) {
|
|
5722
6162
|
printUpdateResult(r);
|
|
5723
|
-
|
|
6163
|
+
if (r.success) succeeded++;
|
|
6164
|
+
else if (r.aborted === true) abortedCount++;
|
|
6165
|
+
else failed++;
|
|
6166
|
+
}
|
|
6167
|
+
recordDiagnosticEvent("subscription.auto-update", timedOut ? "timeout" : failed > 0 ? "failure" : "success", {
|
|
6168
|
+
staleCount: staleSubs.length,
|
|
6169
|
+
timeoutMs,
|
|
6170
|
+
timedOut,
|
|
6171
|
+
succeeded,
|
|
6172
|
+
failed,
|
|
6173
|
+
abortedCount
|
|
6174
|
+
});
|
|
5724
6175
|
}
|
|
5725
6176
|
|
|
5726
6177
|
// src/commands/config.ts
|
|
@@ -5736,6 +6187,7 @@ function cmdConfig(args = []) {
|
|
|
5736
6187
|
const rawContent = requireSubscriptionRawConfig(active.name);
|
|
5737
6188
|
const mode = deriveRuntimeMode(getConfigInfo());
|
|
5738
6189
|
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
6190
|
+
if (asJson && reveal) assertConfigGraphExpansionSafe(config);
|
|
5739
6191
|
const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
|
|
5740
6192
|
const shown = redacted.config;
|
|
5741
6193
|
if (asJson) {
|
|
@@ -5757,6 +6209,7 @@ function cmdConfig(args = []) {
|
|
|
5757
6209
|
|
|
5758
6210
|
// src/open.ts
|
|
5759
6211
|
import { spawn } from "child_process";
|
|
6212
|
+
import os2 from "os";
|
|
5760
6213
|
|
|
5761
6214
|
// src/lifecycle.ts
|
|
5762
6215
|
var silentSigint = false;
|
|
@@ -5766,6 +6219,21 @@ function setSilentSigint(value) {
|
|
|
5766
6219
|
function isSilentSigint() {
|
|
5767
6220
|
return silentSigint;
|
|
5768
6221
|
}
|
|
6222
|
+
var activeChildren = /* @__PURE__ */ new Set();
|
|
6223
|
+
function trackChildProcess(child) {
|
|
6224
|
+
activeChildren.add(child);
|
|
6225
|
+
const untrack = () => activeChildren.delete(child);
|
|
6226
|
+
child.once("close", untrack);
|
|
6227
|
+
return untrack;
|
|
6228
|
+
}
|
|
6229
|
+
function terminateActiveChildren(signal) {
|
|
6230
|
+
for (const child of activeChildren) {
|
|
6231
|
+
try {
|
|
6232
|
+
child.kill(signal);
|
|
6233
|
+
} catch {
|
|
6234
|
+
}
|
|
6235
|
+
}
|
|
6236
|
+
}
|
|
5769
6237
|
|
|
5770
6238
|
// src/open.ts
|
|
5771
6239
|
function openUrl(url) {
|
|
@@ -5777,6 +6245,14 @@ function openUrl(url) {
|
|
|
5777
6245
|
} catch {
|
|
5778
6246
|
}
|
|
5779
6247
|
}
|
|
6248
|
+
function tailExitCode(code, signal) {
|
|
6249
|
+
if (code !== null) return code;
|
|
6250
|
+
if (signal !== null) {
|
|
6251
|
+
const signalNumber = os2.constants.signals[signal];
|
|
6252
|
+
if (typeof signalNumber === "number") return 128 + signalNumber;
|
|
6253
|
+
}
|
|
6254
|
+
return 1;
|
|
6255
|
+
}
|
|
5780
6256
|
function viewLogWithTail(logPath, options) {
|
|
5781
6257
|
const follow = options?.follow;
|
|
5782
6258
|
const lines = options?.lines || 100;
|
|
@@ -5792,9 +6268,14 @@ function viewLogWithTail(logPath, options) {
|
|
|
5792
6268
|
tailArgs.push("-n", lines.toString());
|
|
5793
6269
|
tailArgs.push(logPath);
|
|
5794
6270
|
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
6271
|
+
const untrackTail = trackChildProcess(tail);
|
|
5795
6272
|
if (follow) setSilentSigint(true);
|
|
5796
|
-
tail.on("close", (code) =>
|
|
6273
|
+
tail.on("close", (code, signal) => {
|
|
6274
|
+
untrackTail();
|
|
6275
|
+
process.exit(tailExitCode(code, signal));
|
|
6276
|
+
});
|
|
5797
6277
|
tail.on("error", (e) => {
|
|
6278
|
+
untrackTail();
|
|
5798
6279
|
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5799
6280
|
process.exit(1);
|
|
5800
6281
|
});
|
|
@@ -5803,143 +6284,9 @@ function viewLogWithTail(logPath, options) {
|
|
|
5803
6284
|
// src/commands/shared.ts
|
|
5804
6285
|
import readline from "readline";
|
|
5805
6286
|
|
|
5806
|
-
// src/log-files.ts
|
|
5807
|
-
import fs6 from "fs";
|
|
5808
|
-
import path5 from "path";
|
|
5809
|
-
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5810
|
-
var LOG_TAIL_LINES = 15;
|
|
5811
|
-
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5812
|
-
function isArchiveLogFilename(filename) {
|
|
5813
|
-
return ARCHIVE_LOG_RE.test(filename);
|
|
5814
|
-
}
|
|
5815
|
-
function rotateAndCleanupLogs() {
|
|
5816
|
-
rotateLog();
|
|
5817
|
-
cleanupOldLogs();
|
|
5818
|
-
}
|
|
5819
|
-
function readLogTail() {
|
|
5820
|
-
const TAIL_BYTES = 64 * 1024;
|
|
5821
|
-
let fd = null;
|
|
5822
|
-
try {
|
|
5823
|
-
const size = fs6.statSync(PATHS.logFile).size;
|
|
5824
|
-
if (size === 0) return [];
|
|
5825
|
-
const start = Math.max(0, size - TAIL_BYTES);
|
|
5826
|
-
const length = size - start;
|
|
5827
|
-
const buf = Buffer.alloc(length);
|
|
5828
|
-
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5829
|
-
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5830
|
-
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5831
|
-
} catch {
|
|
5832
|
-
return [];
|
|
5833
|
-
} finally {
|
|
5834
|
-
if (fd !== null) {
|
|
5835
|
-
try {
|
|
5836
|
-
fs6.closeSync(fd);
|
|
5837
|
-
} catch {
|
|
5838
|
-
}
|
|
5839
|
-
}
|
|
5840
|
-
}
|
|
5841
|
-
}
|
|
5842
|
-
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5843
|
-
function allocateArchivePath() {
|
|
5844
|
-
const timestamp = formatLocalTimestamp();
|
|
5845
|
-
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5846
|
-
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
5847
|
-
const archivePath = path5.join(DIRS.logs, name);
|
|
5848
|
-
let fd = null;
|
|
5849
|
-
try {
|
|
5850
|
-
fd = fs6.openSync(archivePath, "wx");
|
|
5851
|
-
} catch (e) {
|
|
5852
|
-
if (e.code === "EEXIST") continue;
|
|
5853
|
-
throw e;
|
|
5854
|
-
}
|
|
5855
|
-
try {
|
|
5856
|
-
fs6.closeSync(fd);
|
|
5857
|
-
} catch {
|
|
5858
|
-
}
|
|
5859
|
-
return archivePath;
|
|
5860
|
-
}
|
|
5861
|
-
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
5862
|
-
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
5863
|
-
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
5864
|
-
});
|
|
5865
|
-
}
|
|
5866
|
-
function rotateLog() {
|
|
5867
|
-
const logFile = PATHS.logFile;
|
|
5868
|
-
let stat;
|
|
5869
|
-
try {
|
|
5870
|
-
stat = fs6.statSync(logFile);
|
|
5871
|
-
} catch (e) {
|
|
5872
|
-
if (e.code === "ENOENT") return;
|
|
5873
|
-
throw e;
|
|
5874
|
-
}
|
|
5875
|
-
if (stat.size === 0) return;
|
|
5876
|
-
const rotatedPath = allocateArchivePath();
|
|
5877
|
-
try {
|
|
5878
|
-
fs6.renameSync(logFile, rotatedPath);
|
|
5879
|
-
} catch (e) {
|
|
5880
|
-
try {
|
|
5881
|
-
fs6.unlinkSync(rotatedPath);
|
|
5882
|
-
} catch {
|
|
5883
|
-
}
|
|
5884
|
-
if (e.code === "ENOENT") return;
|
|
5885
|
-
throw e;
|
|
5886
|
-
}
|
|
5887
|
-
}
|
|
5888
|
-
function cleanupOldLogs() {
|
|
5889
|
-
const logsDir = DIRS.logs;
|
|
5890
|
-
if (!fs6.existsSync(logsDir)) return;
|
|
5891
|
-
const files = fs6.readdirSync(logsDir);
|
|
5892
|
-
const now = Date.now();
|
|
5893
|
-
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5894
|
-
for (const file of files) {
|
|
5895
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
5896
|
-
try {
|
|
5897
|
-
const filePath = path5.join(logsDir, file);
|
|
5898
|
-
const stat = fs6.statSync(filePath);
|
|
5899
|
-
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5900
|
-
fs6.unlinkSync(filePath);
|
|
5901
|
-
}
|
|
5902
|
-
} catch {
|
|
5903
|
-
}
|
|
5904
|
-
}
|
|
5905
|
-
}
|
|
5906
|
-
function listLogs() {
|
|
5907
|
-
const logsDir = DIRS.logs;
|
|
5908
|
-
const result = { current: null, archives: [] };
|
|
5909
|
-
if (fs6.existsSync(PATHS.logFile)) {
|
|
5910
|
-
const stat = fs6.statSync(PATHS.logFile);
|
|
5911
|
-
result.current = {
|
|
5912
|
-
name: "mihomo.log (\u5F53\u524D)",
|
|
5913
|
-
path: PATHS.logFile,
|
|
5914
|
-
size: stat.size,
|
|
5915
|
-
mtime: stat.mtime,
|
|
5916
|
-
isCurrent: true
|
|
5917
|
-
};
|
|
5918
|
-
}
|
|
5919
|
-
if (!fs6.existsSync(logsDir)) return result;
|
|
5920
|
-
const files = fs6.readdirSync(logsDir);
|
|
5921
|
-
for (const file of files) {
|
|
5922
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
5923
|
-
try {
|
|
5924
|
-
const filePath = path5.join(logsDir, file);
|
|
5925
|
-
const stat = fs6.statSync(filePath);
|
|
5926
|
-
result.archives.push({
|
|
5927
|
-
name: file,
|
|
5928
|
-
path: filePath,
|
|
5929
|
-
size: stat.size,
|
|
5930
|
-
mtime: stat.mtime,
|
|
5931
|
-
isCurrent: false
|
|
5932
|
-
});
|
|
5933
|
-
} catch {
|
|
5934
|
-
}
|
|
5935
|
-
}
|
|
5936
|
-
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
5937
|
-
return result;
|
|
5938
|
-
}
|
|
5939
|
-
|
|
5940
6287
|
// src/process-probe.ts
|
|
5941
6288
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
5942
|
-
import
|
|
6289
|
+
import fs8 from "fs";
|
|
5943
6290
|
var PS_TIMEOUT_MS = 5e3;
|
|
5944
6291
|
var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
|
|
5945
6292
|
function probeProcess(pid) {
|
|
@@ -5962,9 +6309,9 @@ function isProbedMihomo(p) {
|
|
|
5962
6309
|
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
5963
6310
|
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
5964
6311
|
function getPid() {
|
|
5965
|
-
if (!
|
|
6312
|
+
if (!fs8.existsSync(PATHS.pidFile)) return null;
|
|
5966
6313
|
try {
|
|
5967
|
-
const pid = parseInt(
|
|
6314
|
+
const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
5968
6315
|
return pid > 0 ? pid : null;
|
|
5969
6316
|
} catch {
|
|
5970
6317
|
return null;
|
|
@@ -5998,9 +6345,9 @@ function parsePidList(stdout) {
|
|
|
5998
6345
|
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
5999
6346
|
}
|
|
6000
6347
|
function isPidFileOwnedByRoot() {
|
|
6001
|
-
if (!
|
|
6348
|
+
if (!fs8.existsSync(PATHS.pidFile)) return false;
|
|
6002
6349
|
try {
|
|
6003
|
-
const stat =
|
|
6350
|
+
const stat = fs8.statSync(PATHS.pidFile);
|
|
6004
6351
|
return stat.uid === 0;
|
|
6005
6352
|
} catch {
|
|
6006
6353
|
return false;
|
|
@@ -6019,15 +6366,15 @@ function getStatus() {
|
|
|
6019
6366
|
}
|
|
6020
6367
|
|
|
6021
6368
|
// src/process-start.ts
|
|
6022
|
-
import
|
|
6369
|
+
import fs14 from "fs";
|
|
6023
6370
|
|
|
6024
6371
|
// src/service.ts
|
|
6025
6372
|
import { spawnSync as spawnSync7 } from "child_process";
|
|
6026
|
-
import
|
|
6373
|
+
import fs13 from "fs";
|
|
6027
6374
|
import path7 from "path";
|
|
6028
6375
|
|
|
6029
6376
|
// src/hot-reload.ts
|
|
6030
|
-
import
|
|
6377
|
+
import fs9 from "fs";
|
|
6031
6378
|
|
|
6032
6379
|
// src/proxy-probe.ts
|
|
6033
6380
|
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
@@ -6062,7 +6409,7 @@ async function probeProxyConnectivity(port) {
|
|
|
6062
6409
|
try {
|
|
6063
6410
|
const { stdout } = await execFileAsync(
|
|
6064
6411
|
"curl",
|
|
6065
|
-
["-x", `http://127.0.0.1:${port}`, "-
|
|
6412
|
+
["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6066
6413
|
{
|
|
6067
6414
|
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6068
6415
|
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
@@ -6072,16 +6419,20 @@ async function probeProxyConnectivity(port) {
|
|
|
6072
6419
|
const code = Number.parseInt(stdout.trim(), 10);
|
|
6073
6420
|
const statusCode = Number.isFinite(code) ? code : null;
|
|
6074
6421
|
const ok = isProbeSuccessStatus(statusCode);
|
|
6422
|
+
const durationMs = Date.now() - start;
|
|
6423
|
+
recordDiagnosticEvent("proxy.probe", ok ? "success" : "failure", { port, httpStatus: statusCode, durationMs });
|
|
6075
6424
|
return {
|
|
6076
6425
|
ok,
|
|
6077
6426
|
statusCode,
|
|
6078
6427
|
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6079
|
-
durationMs
|
|
6428
|
+
durationMs
|
|
6080
6429
|
};
|
|
6081
6430
|
} catch (e) {
|
|
6082
6431
|
const err = e;
|
|
6083
6432
|
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6084
|
-
|
|
6433
|
+
const durationMs = Date.now() - start;
|
|
6434
|
+
recordDiagnosticEvent("proxy.probe", "failure", { port, httpStatus: null, durationMs, ...diagnosticErrorDetails(e) });
|
|
6435
|
+
return { ok: false, statusCode: null, error: detail, durationMs };
|
|
6085
6436
|
}
|
|
6086
6437
|
}
|
|
6087
6438
|
|
|
@@ -6090,51 +6441,65 @@ var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
|
6090
6441
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6091
6442
|
function logOversized() {
|
|
6092
6443
|
try {
|
|
6093
|
-
return
|
|
6444
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6094
6445
|
} catch {
|
|
6095
6446
|
return false;
|
|
6096
6447
|
}
|
|
6097
6448
|
}
|
|
6098
6449
|
async function tryHotReload(prefetched) {
|
|
6099
6450
|
const controller = new AbortController();
|
|
6451
|
+
let stage = "status";
|
|
6100
6452
|
try {
|
|
6101
6453
|
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6102
|
-
if (!status.running || status.pid === null) return false;
|
|
6454
|
+
if (!status.running || status.pid === null) return { ok: false, stage, reason: "service-not-running" };
|
|
6455
|
+
stage = "controller";
|
|
6103
6456
|
const endpoint = getControllerEndpoint();
|
|
6104
|
-
if (endpoint.port === null) return false;
|
|
6457
|
+
if (endpoint.port === null) return { ok: false, stage, reason: "controller-unavailable" };
|
|
6105
6458
|
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6106
6459
|
const headers = { "Content-Type": "application/json" };
|
|
6107
6460
|
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6108
6461
|
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6109
6462
|
try {
|
|
6463
|
+
stage = "version";
|
|
6110
6464
|
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6111
|
-
if (!probe.ok) return false;
|
|
6465
|
+
if (!probe.ok) return { ok: false, stage, reason: "http-status", httpStatus: probe.status };
|
|
6112
6466
|
const info = await probe.json();
|
|
6113
|
-
if (typeof info?.version !== "string") return false;
|
|
6467
|
+
if (typeof info?.version !== "string") return { ok: false, stage, reason: "invalid-response" };
|
|
6468
|
+
stage = "identity";
|
|
6114
6469
|
const listenerPids = lsofListenPids(endpoint.port);
|
|
6115
|
-
if (listenerPids === null
|
|
6470
|
+
if (listenerPids === null) return { ok: false, stage, reason: "listener-unknown" };
|
|
6471
|
+
if (listenerPids[0] !== status.pid) return { ok: false, stage, reason: "owner-mismatch" };
|
|
6472
|
+
stage = "put";
|
|
6116
6473
|
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6117
6474
|
method: "PUT",
|
|
6118
6475
|
headers,
|
|
6119
6476
|
body: "{}",
|
|
6120
6477
|
signal: controller.signal
|
|
6121
6478
|
});
|
|
6122
|
-
return res.
|
|
6479
|
+
if (!res.ok) return { ok: false, stage, reason: "http-status", httpStatus: res.status };
|
|
6480
|
+
return { ok: true };
|
|
6123
6481
|
} finally {
|
|
6124
6482
|
clearTimeout(timer);
|
|
6125
6483
|
}
|
|
6126
|
-
} catch {
|
|
6127
|
-
|
|
6484
|
+
} catch (e) {
|
|
6485
|
+
const aborted = controller.signal.aborted;
|
|
6486
|
+
return {
|
|
6487
|
+
ok: false,
|
|
6488
|
+
stage,
|
|
6489
|
+
reason: aborted ? "timeout" : "exception",
|
|
6490
|
+
errorType: e instanceof Error && e.name === "AbortError" ? "AbortError" : "Error",
|
|
6491
|
+
...aborted ? { aborted: true } : {}
|
|
6492
|
+
};
|
|
6128
6493
|
}
|
|
6129
6494
|
}
|
|
6130
6495
|
|
|
6131
6496
|
// src/process-stop.ts
|
|
6132
6497
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
6133
|
-
import
|
|
6498
|
+
import fs11 from "fs";
|
|
6134
6499
|
|
|
6135
6500
|
// src/sudo.ts
|
|
6136
6501
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6137
|
-
import
|
|
6502
|
+
import fs10 from "fs";
|
|
6138
6503
|
import path6 from "path";
|
|
6139
6504
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
6140
6505
|
var SudoAuthError = class extends Error {
|
|
@@ -6161,8 +6526,8 @@ function runSudoScript(scriptBody, opts) {
|
|
|
6161
6526
|
}
|
|
6162
6527
|
ensureDirs();
|
|
6163
6528
|
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
6164
|
-
|
|
6165
|
-
|
|
6529
|
+
fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
6530
|
+
fs10.chmodSync(scriptPath, 448);
|
|
6166
6531
|
try {
|
|
6167
6532
|
const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
6168
6533
|
if (result.error) {
|
|
@@ -6172,7 +6537,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
6172
6537
|
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
6173
6538
|
} finally {
|
|
6174
6539
|
try {
|
|
6175
|
-
|
|
6540
|
+
fs10.unlinkSync(scriptPath);
|
|
6176
6541
|
} catch {
|
|
6177
6542
|
}
|
|
6178
6543
|
}
|
|
@@ -6183,7 +6548,7 @@ var PROCESS_WAIT_ATTEMPTS = 50;
|
|
|
6183
6548
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
6184
6549
|
var BATCH_KILL_THRESHOLD = 3;
|
|
6185
6550
|
function clearRuntime() {
|
|
6186
|
-
if (
|
|
6551
|
+
if (fs11.existsSync(DIRS.runtime)) {
|
|
6187
6552
|
rmrf(DIRS.runtime);
|
|
6188
6553
|
}
|
|
6189
6554
|
ensureDirs();
|
|
@@ -6195,7 +6560,7 @@ function printResidueWarning(remaining) {
|
|
|
6195
6560
|
}
|
|
6196
6561
|
function clearPid() {
|
|
6197
6562
|
try {
|
|
6198
|
-
|
|
6563
|
+
fs11.unlinkSync(PATHS.pidFile);
|
|
6199
6564
|
return null;
|
|
6200
6565
|
} catch (e) {
|
|
6201
6566
|
if (e.code === "ENOENT") return null;
|
|
@@ -6310,10 +6675,10 @@ async function stop() {
|
|
|
6310
6675
|
}
|
|
6311
6676
|
|
|
6312
6677
|
// src/stop-epoch.ts
|
|
6313
|
-
import
|
|
6678
|
+
import fs12 from "fs";
|
|
6314
6679
|
function readStopEpoch() {
|
|
6315
6680
|
try {
|
|
6316
|
-
const n = Number.parseInt(
|
|
6681
|
+
const n = Number.parseInt(fs12.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
6317
6682
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
6318
6683
|
} catch {
|
|
6319
6684
|
return 0;
|
|
@@ -6426,14 +6791,14 @@ function tunBlockedByConcurrentStart() {
|
|
|
6426
6791
|
function ensureServiceSymlink() {
|
|
6427
6792
|
assertKernelInstalled();
|
|
6428
6793
|
try {
|
|
6429
|
-
const current =
|
|
6794
|
+
const current = fs13.readlinkSync(PATHS.serviceBinary);
|
|
6430
6795
|
if (current === "mihomo") return;
|
|
6431
|
-
|
|
6796
|
+
fs13.unlinkSync(PATHS.serviceBinary);
|
|
6432
6797
|
} catch (e) {
|
|
6433
6798
|
const code = e.code;
|
|
6434
6799
|
if (code === "EINVAL") {
|
|
6435
6800
|
try {
|
|
6436
|
-
|
|
6801
|
+
fs13.unlinkSync(PATHS.serviceBinary);
|
|
6437
6802
|
} catch {
|
|
6438
6803
|
}
|
|
6439
6804
|
} else if (code !== "ENOENT") {
|
|
@@ -6441,12 +6806,12 @@ function ensureServiceSymlink() {
|
|
|
6441
6806
|
}
|
|
6442
6807
|
}
|
|
6443
6808
|
try {
|
|
6444
|
-
|
|
6809
|
+
fs13.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
6445
6810
|
} catch (e) {
|
|
6446
6811
|
if (e.code !== "EEXIST") throw e;
|
|
6447
6812
|
let existing;
|
|
6448
6813
|
try {
|
|
6449
|
-
existing =
|
|
6814
|
+
existing = fs13.readlinkSync(PATHS.serviceBinary);
|
|
6450
6815
|
} catch {
|
|
6451
6816
|
throw e;
|
|
6452
6817
|
}
|
|
@@ -6455,8 +6820,8 @@ function ensureServiceSymlink() {
|
|
|
6455
6820
|
}
|
|
6456
6821
|
function bootstrapServiceIdempotentOrThrow(what) {
|
|
6457
6822
|
const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6458
|
-
if (result.status === 0) return;
|
|
6459
|
-
if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
|
|
6823
|
+
if (result.status === 0) return true;
|
|
6824
|
+
if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return false;
|
|
6460
6825
|
const detail = result.stderr.trim();
|
|
6461
6826
|
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
6462
6827
|
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
@@ -6486,8 +6851,8 @@ async function installService(wasRunning) {
|
|
|
6486
6851
|
}
|
|
6487
6852
|
bootoutService();
|
|
6488
6853
|
await waitUntilUnloaded();
|
|
6489
|
-
|
|
6490
|
-
atomicWriteFileSync(PATHS.userAgentPlist,
|
|
6854
|
+
fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
6855
|
+
atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
6491
6856
|
if (wasRunning) {
|
|
6492
6857
|
withFileLock(PATHS.serviceLock, () => {
|
|
6493
6858
|
if (startAbortedByConcurrentStop()) {
|
|
@@ -6500,7 +6865,7 @@ async function installService(wasRunning) {
|
|
|
6500
6865
|
}
|
|
6501
6866
|
} finally {
|
|
6502
6867
|
try {
|
|
6503
|
-
|
|
6868
|
+
fs13.unlinkSync(stagePath);
|
|
6504
6869
|
} catch {
|
|
6505
6870
|
}
|
|
6506
6871
|
}
|
|
@@ -6528,15 +6893,19 @@ async function startService() {
|
|
|
6528
6893
|
});
|
|
6529
6894
|
}
|
|
6530
6895
|
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
|
|
6896
|
+
const previousPid = getServiceStatus({ withDisabled: false }).pid;
|
|
6531
6897
|
bootoutService();
|
|
6532
|
-
await waitUntilUnloaded()
|
|
6533
|
-
|
|
6898
|
+
const unloadOutcome = await waitUntilUnloaded(serviceTarget(), {
|
|
6899
|
+
acceptReplacement: (pid) => pid !== previousPid && !isServiceDisabledInLaunchd()
|
|
6900
|
+
});
|
|
6901
|
+
if (unloadOutcome === "unloaded") rotateAndCleanupLogs();
|
|
6534
6902
|
let started = true;
|
|
6535
6903
|
withFileLock(PATHS.serviceLock, () => {
|
|
6536
6904
|
if (startAbortedByConcurrentStop()) {
|
|
6537
6905
|
started = false;
|
|
6538
6906
|
return;
|
|
6539
6907
|
}
|
|
6908
|
+
if (unloadOutcome === "replacement-running") return;
|
|
6540
6909
|
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6541
6910
|
bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
|
|
6542
6911
|
});
|
|
@@ -6568,13 +6937,13 @@ async function uninstallService() {
|
|
|
6568
6937
|
assertServiceLabelSafe();
|
|
6569
6938
|
await bootoutAndDisableInLock();
|
|
6570
6939
|
try {
|
|
6571
|
-
|
|
6940
|
+
fs13.rmSync(PATHS.userAgentPlist, { force: true });
|
|
6572
6941
|
} catch (e) {
|
|
6573
6942
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
6574
6943
|
}
|
|
6575
6944
|
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6576
6945
|
try {
|
|
6577
|
-
|
|
6946
|
+
fs13.rmSync(PATHS.serviceBinary, { force: true });
|
|
6578
6947
|
} catch {
|
|
6579
6948
|
}
|
|
6580
6949
|
return cleanup;
|
|
@@ -6585,29 +6954,52 @@ async function restartService(prefetched) {
|
|
|
6585
6954
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
6586
6955
|
}
|
|
6587
6956
|
const oversized = logOversized();
|
|
6588
|
-
|
|
6957
|
+
const hotReload = oversized ? null : await tryHotReload(prefetched);
|
|
6958
|
+
if (hotReload?.ok) {
|
|
6959
|
+
recordDiagnosticEvent("service.hot-reload", "success", { stage: "put" });
|
|
6589
6960
|
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6590
6961
|
}
|
|
6962
|
+
recordDiagnosticEvent("service.hot-reload", "fallback", {
|
|
6963
|
+
stage: hotReload?.stage ?? "log-rotation",
|
|
6964
|
+
reason: hotReload?.reason ?? "log-oversized",
|
|
6965
|
+
httpStatus: hotReload?.httpStatus,
|
|
6966
|
+
errorType: hotReload?.errorType,
|
|
6967
|
+
aborted: hotReload?.aborted
|
|
6968
|
+
});
|
|
6591
6969
|
if (oversized) {
|
|
6592
6970
|
const archiveFile = allocateArchivePath();
|
|
6593
6971
|
try {
|
|
6594
|
-
|
|
6595
|
-
|
|
6972
|
+
fs13.copyFileSync(PATHS.logFile, archiveFile);
|
|
6973
|
+
fs13.writeFileSync(PATHS.logFile, "");
|
|
6596
6974
|
} catch {
|
|
6597
6975
|
}
|
|
6598
6976
|
}
|
|
6599
6977
|
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
6600
|
-
|
|
6978
|
+
recordDiagnosticEvent("service.kickstart", kick.status === 0 ? "success" : "failure", { exitCode: kick.status });
|
|
6601
6979
|
if (kick.status !== 0) {
|
|
6602
|
-
|
|
6603
|
-
|
|
6604
|
-
|
|
6605
|
-
return;
|
|
6606
|
-
|
|
6607
|
-
|
|
6608
|
-
|
|
6609
|
-
})
|
|
6610
|
-
|
|
6980
|
+
let bootstrapped;
|
|
6981
|
+
try {
|
|
6982
|
+
bootstrapped = withFileLock(PATHS.serviceLock, () => {
|
|
6983
|
+
if (startAbortedByConcurrentStop()) return null;
|
|
6984
|
+
runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6985
|
+
return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
|
|
6986
|
+
});
|
|
6987
|
+
} catch (e) {
|
|
6988
|
+
recordDiagnosticEvent("service.bootstrap", "failure", diagnosticErrorDetails(e));
|
|
6989
|
+
throw e;
|
|
6990
|
+
}
|
|
6991
|
+
if (bootstrapped === null) {
|
|
6992
|
+
recordDiagnosticEvent("service.bootstrap", "cancelled", { reason: "concurrent-stop" });
|
|
6993
|
+
return { hotReloaded: false, started: false };
|
|
6994
|
+
}
|
|
6995
|
+
if (!bootstrapped) {
|
|
6996
|
+
recordDiagnosticEvent("service.bootstrap", "failure", { reason: "replacement-not-bootstrapped", exitCode: kick.status });
|
|
6997
|
+
const detail = kick.stderr.trim();
|
|
6998
|
+
throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
|
|
6999
|
+
hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
7000
|
+
});
|
|
7001
|
+
}
|
|
7002
|
+
recordDiagnosticEvent("service.bootstrap", "success");
|
|
6611
7003
|
}
|
|
6612
7004
|
cleanupOldLogs();
|
|
6613
7005
|
return { hotReloaded: false, started: true };
|
|
@@ -6688,12 +7080,12 @@ async function startTun(prefetched) {
|
|
|
6688
7080
|
}
|
|
6689
7081
|
rotateAndCleanupLogs();
|
|
6690
7082
|
const logFile = PATHS.logFile;
|
|
6691
|
-
if (
|
|
7083
|
+
if (fs14.existsSync(logFile)) {
|
|
6692
7084
|
try {
|
|
6693
|
-
|
|
7085
|
+
fs14.accessSync(logFile, fs14.constants.W_OK);
|
|
6694
7086
|
} catch {
|
|
6695
7087
|
try {
|
|
6696
|
-
|
|
7088
|
+
fs14.unlinkSync(logFile);
|
|
6697
7089
|
} catch {
|
|
6698
7090
|
}
|
|
6699
7091
|
}
|
|
@@ -6745,8 +7137,28 @@ function restartModeOnChange() {
|
|
|
6745
7137
|
return state.running ? restartModeFor(state, getRuntimeMode()) : null;
|
|
6746
7138
|
}
|
|
6747
7139
|
async function launchOrRestart(mode) {
|
|
7140
|
+
const startedAt = Date.now();
|
|
7141
|
+
try {
|
|
7142
|
+
const pid = await launchOrRestartImpl(mode);
|
|
7143
|
+
recordDiagnosticEvent("runtime.launch", "success", { mode, kernelPid: pid, durationMs: Date.now() - startedAt });
|
|
7144
|
+
return pid;
|
|
7145
|
+
} catch (e) {
|
|
7146
|
+
recordDiagnosticEvent("runtime.launch", "failure", { mode, durationMs: Date.now() - startedAt, ...diagnosticErrorDetails(e) });
|
|
7147
|
+
throw e;
|
|
7148
|
+
}
|
|
7149
|
+
}
|
|
7150
|
+
async function launchOrRestartImpl(mode) {
|
|
6748
7151
|
if (mode === "tun") {
|
|
6749
|
-
|
|
7152
|
+
const prefetched = assertTunStartNotRaced();
|
|
7153
|
+
let pid;
|
|
7154
|
+
try {
|
|
7155
|
+
pid = await startTun(prefetched);
|
|
7156
|
+
} catch (e) {
|
|
7157
|
+
await throwIfTunStartCancelled();
|
|
7158
|
+
throw e;
|
|
7159
|
+
}
|
|
7160
|
+
await throwIfTunStartCancelled();
|
|
7161
|
+
return pid;
|
|
6750
7162
|
}
|
|
6751
7163
|
const status = getServiceStatus();
|
|
6752
7164
|
let hotReloaded = false;
|
|
@@ -6771,6 +7183,20 @@ async function launchOrRestart(mode) {
|
|
|
6771
7183
|
throw e;
|
|
6772
7184
|
}
|
|
6773
7185
|
}
|
|
7186
|
+
async function stopTunAfterConcurrentStop() {
|
|
7187
|
+
const result = await stop();
|
|
7188
|
+
if (result.remaining && result.remaining.length > 0) {
|
|
7189
|
+
throw new CliError(`\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C\uFF0C\u4F46 TUN \u8FDB\u7A0B\u672A\u80FD\u7EC8\u6B62\uFF08PID ${result.remaining.join(", ")}\uFF09`, {
|
|
7190
|
+
label: "\u505C\u6B62\u5931\u8D25",
|
|
7191
|
+
hint: [MANUAL_PKILL_HINT]
|
|
7192
|
+
});
|
|
7193
|
+
}
|
|
7194
|
+
}
|
|
7195
|
+
async function throwIfTunStartCancelled() {
|
|
7196
|
+
if (!startAbortedByConcurrentStop()) return;
|
|
7197
|
+
await stopTunAfterConcurrentStop();
|
|
7198
|
+
throw cancelledByConcurrentStop();
|
|
7199
|
+
}
|
|
6774
7200
|
function cancelledByConcurrentStop() {
|
|
6775
7201
|
return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
|
|
6776
7202
|
label: "\u542F\u52A8\u5931\u8D25",
|
|
@@ -6791,7 +7217,15 @@ function startCommandForCurrentMode(state) {
|
|
|
6791
7217
|
return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
|
|
6792
7218
|
}
|
|
6793
7219
|
async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
7220
|
+
const startedAt = Date.now();
|
|
6794
7221
|
const health = await waitServiceHealthy();
|
|
7222
|
+
recordDiagnosticEvent("service.health", health.healthy ? "success" : "failure", {
|
|
7223
|
+
reason: health.healthy ? void 0 : health.crashed ? "crashed" : "not-running",
|
|
7224
|
+
kernelPid: health.pid,
|
|
7225
|
+
lastExitCode: health.exitCode,
|
|
7226
|
+
lastTerminatingSignal: health.terminatingSignal,
|
|
7227
|
+
durationMs: Date.now() - startedAt
|
|
7228
|
+
});
|
|
6795
7229
|
if (health.healthy) return health.pid;
|
|
6796
7230
|
const tail = readLogTail();
|
|
6797
7231
|
const cause = describeExitCause(health.exitCode, health.terminatingSignal);
|
|
@@ -7160,6 +7594,7 @@ async function cmdStart(args) {
|
|
|
7160
7594
|
const targetMode = resolveStartMode(args);
|
|
7161
7595
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
7162
7596
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
7597
|
+
recordDiagnosticEvent("start", "begin", { mode: targetMode, updateRequested: !skipUpdate, timeoutMs: updateTimeout });
|
|
7163
7598
|
let disabledAutoStartForTun = false;
|
|
7164
7599
|
assertKernelInstalled();
|
|
7165
7600
|
const serviceBefore = getServiceStatus();
|
|
@@ -7266,7 +7701,7 @@ function unknownSubcommandError(action, table, opts) {
|
|
|
7266
7701
|
}
|
|
7267
7702
|
async function confirmPrompt(question) {
|
|
7268
7703
|
if (!process.stdin.isTTY) return false;
|
|
7269
|
-
const rl = readline.createInterface({ input: process.stdin, output: process.
|
|
7704
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
7270
7705
|
const answer = await new Promise((resolve) => {
|
|
7271
7706
|
rl.question(`${question} (y/N) `, (a) => {
|
|
7272
7707
|
rl.close();
|
|
@@ -7344,11 +7779,11 @@ async function cmdDirectory(args) {
|
|
|
7344
7779
|
}
|
|
7345
7780
|
|
|
7346
7781
|
// src/commands/doctor.ts
|
|
7347
|
-
import
|
|
7782
|
+
import fs16 from "fs";
|
|
7348
7783
|
|
|
7349
7784
|
// src/kernel.ts
|
|
7350
|
-
import { execFile as execFile3, spawnSync as spawnSync9 } from "child_process";
|
|
7351
|
-
import
|
|
7785
|
+
import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync9 } from "child_process";
|
|
7786
|
+
import fs15 from "fs";
|
|
7352
7787
|
import path8 from "path";
|
|
7353
7788
|
import { promisify as promisify3 } from "util";
|
|
7354
7789
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7434,7 +7869,7 @@ function pickLatestRelease(releases) {
|
|
|
7434
7869
|
}
|
|
7435
7870
|
function buildReleaseApiCurlArgs(proxy, url) {
|
|
7436
7871
|
return [
|
|
7437
|
-
"-
|
|
7872
|
+
"-sS",
|
|
7438
7873
|
...proxy ? ["-x", proxy] : ["--noproxy", "*"],
|
|
7439
7874
|
"--proto",
|
|
7440
7875
|
"=https",
|
|
@@ -7608,6 +8043,74 @@ function buildGhDownloadEnv(proxy) {
|
|
|
7608
8043
|
}
|
|
7609
8044
|
return env;
|
|
7610
8045
|
}
|
|
8046
|
+
var CHILD_FORCE_KILL_GRACE_MS = 1e3;
|
|
8047
|
+
var GZIP_TIMEOUT_MS = 6e4;
|
|
8048
|
+
function scheduleChildForceKill(child, delayMs) {
|
|
8049
|
+
const timer = setTimeout(() => {
|
|
8050
|
+
try {
|
|
8051
|
+
child.kill("SIGKILL");
|
|
8052
|
+
} catch {
|
|
8053
|
+
}
|
|
8054
|
+
}, delayMs);
|
|
8055
|
+
timer.unref();
|
|
8056
|
+
return () => clearTimeout(timer);
|
|
8057
|
+
}
|
|
8058
|
+
function runInheritedChild(command, args, options) {
|
|
8059
|
+
return new Promise((resolve) => {
|
|
8060
|
+
const child = spawn2(command, args, { stdio: "inherit", env: options.env });
|
|
8061
|
+
const untrack = trackChildProcess(child);
|
|
8062
|
+
let childError = null;
|
|
8063
|
+
let timedOut = false;
|
|
8064
|
+
let settled = false;
|
|
8065
|
+
let timer;
|
|
8066
|
+
let cancelForceKill = () => {
|
|
8067
|
+
};
|
|
8068
|
+
const finish = (status) => {
|
|
8069
|
+
if (settled) return;
|
|
8070
|
+
settled = true;
|
|
8071
|
+
if (timer) clearTimeout(timer);
|
|
8072
|
+
cancelForceKill();
|
|
8073
|
+
untrack();
|
|
8074
|
+
if (timedOut && childError === null) {
|
|
8075
|
+
childError = Object.assign(new Error(`${command} timed out`), { code: "ETIMEDOUT" });
|
|
8076
|
+
}
|
|
8077
|
+
resolve({ error: childError, status });
|
|
8078
|
+
};
|
|
8079
|
+
child.on("error", (error) => {
|
|
8080
|
+
childError = error;
|
|
8081
|
+
if (child.pid === void 0) finish(null);
|
|
8082
|
+
});
|
|
8083
|
+
child.on("close", (status) => finish(status));
|
|
8084
|
+
if (options.timeout !== void 0) {
|
|
8085
|
+
timer = setTimeout(() => {
|
|
8086
|
+
timedOut = true;
|
|
8087
|
+
child.kill();
|
|
8088
|
+
cancelForceKill = scheduleChildForceKill(child, CHILD_FORCE_KILL_GRACE_MS);
|
|
8089
|
+
}, options.timeout);
|
|
8090
|
+
timer.unref();
|
|
8091
|
+
}
|
|
8092
|
+
});
|
|
8093
|
+
}
|
|
8094
|
+
async function decompressGzip(tempPath) {
|
|
8095
|
+
const execution = execFileAsync2("gzip", ["-dc", tempPath], {
|
|
8096
|
+
encoding: "buffer",
|
|
8097
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
8098
|
+
timeout: GZIP_TIMEOUT_MS
|
|
8099
|
+
});
|
|
8100
|
+
const untrack = trackChildProcess(execution.child);
|
|
8101
|
+
const cancelForceKill = scheduleChildForceKill(execution.child, GZIP_TIMEOUT_MS + CHILD_FORCE_KILL_GRACE_MS);
|
|
8102
|
+
try {
|
|
8103
|
+
const { stdout } = await execution;
|
|
8104
|
+
return stdout;
|
|
8105
|
+
} catch (error) {
|
|
8106
|
+
const code = error.code;
|
|
8107
|
+
if (typeof code === "number") throw new Error(`gzip \u9000\u51FA\u7801 ${code}`);
|
|
8108
|
+
throw error;
|
|
8109
|
+
} finally {
|
|
8110
|
+
cancelForceKill();
|
|
8111
|
+
untrack();
|
|
8112
|
+
}
|
|
8113
|
+
}
|
|
7611
8114
|
async function downloadKernel(progressCallback, channel, latest) {
|
|
7612
8115
|
ensureDirs();
|
|
7613
8116
|
const downloadProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
|
|
@@ -7628,7 +8131,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7628
8131
|
if (mirrorIneffective) {
|
|
7629
8132
|
console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
|
|
7630
8133
|
}
|
|
7631
|
-
const tempDir =
|
|
8134
|
+
const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
7632
8135
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
7633
8136
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7634
8137
|
try {
|
|
@@ -7642,8 +8145,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7642
8145
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path8.basename(asset.name)) {
|
|
7643
8146
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7644
8147
|
}
|
|
7645
|
-
const ghResult =
|
|
7646
|
-
stdio: "inherit",
|
|
8148
|
+
const ghResult = await runInheritedChild("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7647
8149
|
timeout: GH_DOWNLOAD_TIMEOUT,
|
|
7648
8150
|
// gh 回退候选带本机代理:per-spawn 注入(buildGhDownloadEnv 注释述其与 D9 的关系)
|
|
7649
8151
|
env: buildGhDownloadEnv(channel.proxy ?? null)
|
|
@@ -7662,7 +8164,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7662
8164
|
}
|
|
7663
8165
|
} else {
|
|
7664
8166
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7665
|
-
const curlResult =
|
|
8167
|
+
const curlResult = await runInheritedChild(
|
|
7666
8168
|
"curl",
|
|
7667
8169
|
buildKernelCurlArgs({
|
|
7668
8170
|
url: downloadUrl,
|
|
@@ -7671,7 +8173,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7671
8173
|
outputPath: tempPath
|
|
7672
8174
|
}),
|
|
7673
8175
|
// no_proxy 例外表会绕过显式 -x——统一出口置空,保 -x 权威(curl-spawn.ts)
|
|
7674
|
-
{
|
|
8176
|
+
{ env: buildCurlSpawnEnv() }
|
|
7675
8177
|
);
|
|
7676
8178
|
if (curlResult.error) {
|
|
7677
8179
|
if (curlResult.error.code === "ENOENT") {
|
|
@@ -7683,11 +8185,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7683
8185
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
|
|
7684
8186
|
}
|
|
7685
8187
|
}
|
|
7686
|
-
if (!
|
|
8188
|
+
if (!fs15.existsSync(tempPath)) {
|
|
7687
8189
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7688
8190
|
}
|
|
7689
8191
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7690
|
-
const actual =
|
|
8192
|
+
const actual = fs15.statSync(tempPath).size;
|
|
7691
8193
|
if (actual !== asset.size) {
|
|
7692
8194
|
throw new Error(
|
|
7693
8195
|
`\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
|
|
@@ -7698,18 +8200,13 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7698
8200
|
if (progressCallback) {
|
|
7699
8201
|
progressCallback("\u89E3\u538B\u5185\u6838...");
|
|
7700
8202
|
}
|
|
7701
|
-
if (!tempPath.endsWith(".gz")) {
|
|
7702
|
-
throw new Error(`\u4E0D\u652F\u6301\u7684\u5185\u6838\u8D44\u4EA7\u683C\u5F0F: ${asset.name}\uFF08\u671F\u671B\u5355\u6587\u4EF6 .gz\uFF09`);
|
|
7703
|
-
}
|
|
7704
8203
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
7705
|
-
const
|
|
7706
|
-
|
|
7707
|
-
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7708
|
-
fs14.writeFileSync(foundBinary, gzipResult.stdout, { mode: 493 });
|
|
8204
|
+
const gzipStdout = await decompressGzip(tempPath);
|
|
8205
|
+
fs15.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
|
|
7709
8206
|
if (progressCallback) {
|
|
7710
8207
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7711
8208
|
}
|
|
7712
|
-
|
|
8209
|
+
fs15.chmodSync(foundBinary, 493);
|
|
7713
8210
|
const probe = probeKernelVersion(foundBinary);
|
|
7714
8211
|
if (probe.spawnError || probe.status !== 0 || probe.version === null) {
|
|
7715
8212
|
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
|
|
@@ -7722,19 +8219,18 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7722
8219
|
throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
|
|
7723
8220
|
}
|
|
7724
8221
|
const targetPath = PATHS.mihomoBinary;
|
|
7725
|
-
|
|
7726
|
-
|
|
7727
|
-
return { version: latest.tag_name, path: targetPath };
|
|
8222
|
+
fs15.renameSync(foundBinary, targetPath);
|
|
8223
|
+
return { version: latest.tag_name };
|
|
7728
8224
|
} finally {
|
|
7729
8225
|
try {
|
|
7730
|
-
|
|
8226
|
+
fs15.rmSync(tempDir, { recursive: true, force: true });
|
|
7731
8227
|
} catch {
|
|
7732
8228
|
}
|
|
7733
8229
|
}
|
|
7734
8230
|
}
|
|
7735
8231
|
|
|
7736
8232
|
// src/commands/update.ts
|
|
7737
|
-
import { execFile as execFile4, spawn as
|
|
8233
|
+
import { execFile as execFile4, spawn as spawn3 } from "child_process";
|
|
7738
8234
|
import net from "net";
|
|
7739
8235
|
import { promisify as promisify4 } from "util";
|
|
7740
8236
|
var execFileAsync3 = promisify4(execFile4);
|
|
@@ -7815,7 +8311,7 @@ async function cmdUpdate(args = []) {
|
|
|
7815
8311
|
console.log("");
|
|
7816
8312
|
const installEnv = await buildNpmSpawnEnv();
|
|
7817
8313
|
await new Promise((resolve, reject) => {
|
|
7818
|
-
const npm =
|
|
8314
|
+
const npm = spawn3("npm", ["install", "-g", PKG_NAME], { stdio: "inherit", env: installEnv });
|
|
7819
8315
|
npm.on("close", (code) => {
|
|
7820
8316
|
if (code === 0) {
|
|
7821
8317
|
resolve();
|
|
@@ -7889,20 +8385,20 @@ async function collectChecks() {
|
|
|
7889
8385
|
} else {
|
|
7890
8386
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
7891
8387
|
}
|
|
7892
|
-
if (
|
|
8388
|
+
if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
|
|
7893
8389
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
|
|
7894
8390
|
}
|
|
7895
|
-
if (
|
|
8391
|
+
if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
|
|
7896
8392
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
|
|
7897
8393
|
}
|
|
7898
8394
|
try {
|
|
7899
|
-
|
|
8395
|
+
fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
|
|
7900
8396
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
7901
8397
|
} catch {
|
|
7902
8398
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
7903
8399
|
}
|
|
7904
|
-
if (
|
|
7905
|
-
if (isValidSettingsContent(
|
|
8400
|
+
if (fs16.existsSync(PATHS.settingsFile)) {
|
|
8401
|
+
if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
7906
8402
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
7907
8403
|
} else {
|
|
7908
8404
|
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");
|
|
@@ -7977,7 +8473,7 @@ async function collectChecks() {
|
|
|
7977
8473
|
if (active && hasKernel()) {
|
|
7978
8474
|
try {
|
|
7979
8475
|
const mode = deriveRuntimeMode(info);
|
|
7980
|
-
const prepared = await prepareConfigForStart(mode, active.name);
|
|
8476
|
+
const prepared = await prepareConfigForStart(mode, active.name, "doctor");
|
|
7981
8477
|
const warnings = prepared.buildResult.warnings;
|
|
7982
8478
|
if (warnings.length > 0) {
|
|
7983
8479
|
push(
|
|
@@ -8227,7 +8723,7 @@ function printChannelLine(channel, isExplicitProxy) {
|
|
|
8227
8723
|
console.log("");
|
|
8228
8724
|
}
|
|
8229
8725
|
function formatChannelSwitchLine(previousError) {
|
|
8230
|
-
const reason =
|
|
8726
|
+
const reason = firstLine(previousError.message);
|
|
8231
8727
|
return reason ? `\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF08${reason}\uFF09\uFF0C\u5207\u6362\u4E3A:` : "\u4E0A\u4E00\u901A\u9053\u5931\u8D25\uFF0C\u5207\u6362\u4E3A:";
|
|
8232
8728
|
}
|
|
8233
8729
|
function buildDownloadFailureError(attempts, isExplicitProxy) {
|
|
@@ -8334,7 +8830,7 @@ async function cmdKernel(args) {
|
|
|
8334
8830
|
const attempts = [];
|
|
8335
8831
|
for (let attempt = 0; attempt < channels.length; attempt++) {
|
|
8336
8832
|
if (attempt > 0) {
|
|
8337
|
-
console.log(formatChannelSwitchLine(attempts[attempt - 1]
|
|
8833
|
+
console.log(formatChannelSwitchLine(attempts[attempt - 1].error));
|
|
8338
8834
|
printChannelLine(channels[attempt], proxyInfo.proxy !== null);
|
|
8339
8835
|
}
|
|
8340
8836
|
try {
|
|
@@ -8359,22 +8855,35 @@ async function cmdKernel(args) {
|
|
|
8359
8855
|
}
|
|
8360
8856
|
|
|
8361
8857
|
// src/commands/log.ts
|
|
8858
|
+
import fs17 from "fs";
|
|
8362
8859
|
var INVALID_INDEX_HINT = "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs";
|
|
8363
8860
|
function cmdLogs(args) {
|
|
8364
|
-
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8365
|
-
assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8861
|
+
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open", "--diagnostic"], "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8862
|
+
assertPositionalCount(args, 1, 1, "mihomo-cli logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8366
8863
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
8367
8864
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
8368
8865
|
const follow = hasFlag(args, "-f", "--follow");
|
|
8369
8866
|
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
8370
8867
|
const positional = getNonFlagArg(args, 1);
|
|
8868
|
+
const diagnostic = hasFlag(args, "--diagnostic");
|
|
8869
|
+
if (diagnostic && positional !== null) {
|
|
8870
|
+
throw new CliError("--diagnostic \u4E0E\u5185\u6838\u65E5\u5FD7\u7F16\u53F7\u4E92\u65A5", {
|
|
8871
|
+
hint: ["\u67E5\u770B\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic", "\u67E5\u770B\u5185\u6838\u65E5\u5FD7: mihomo-cli logs <\u7F16\u53F7>"]
|
|
8872
|
+
});
|
|
8873
|
+
}
|
|
8371
8874
|
if (positional === "") {
|
|
8372
8875
|
throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: INVALID_INDEX_HINT });
|
|
8373
8876
|
}
|
|
8374
|
-
|
|
8877
|
+
if (diagnostic && !fs17.existsSync(PATHS.diagnosticEventsFile)) {
|
|
8878
|
+
console.log("\u6682\u65E0\u8BCA\u65AD\u4E8B\u4EF6");
|
|
8879
|
+
return;
|
|
8880
|
+
}
|
|
8881
|
+
const targetName = diagnostic ? "0" : positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
8375
8882
|
if (targetName) {
|
|
8376
8883
|
let logPath;
|
|
8377
|
-
if (
|
|
8884
|
+
if (diagnostic) {
|
|
8885
|
+
logPath = PATHS.diagnosticEventsFile;
|
|
8886
|
+
} else if (targetName === "0") {
|
|
8378
8887
|
logPath = PATHS.logFile;
|
|
8379
8888
|
} else {
|
|
8380
8889
|
const parsedIdx = parseInt(targetName, 10);
|
|
@@ -8390,7 +8899,7 @@ function cmdLogs(args) {
|
|
|
8390
8899
|
if (openInViewer) {
|
|
8391
8900
|
if (follow) {
|
|
8392
8901
|
throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
|
|
8393
|
-
hint:
|
|
8902
|
+
hint: `\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs ${diagnostic ? "--diagnostic" : "0"} -f`
|
|
8394
8903
|
});
|
|
8395
8904
|
}
|
|
8396
8905
|
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
|
|
@@ -8405,7 +8914,8 @@ function cmdLogs(args) {
|
|
|
8405
8914
|
if (logs.current) all.push(logs.current);
|
|
8406
8915
|
all.push(...logs.archives);
|
|
8407
8916
|
if (all.length === 0) {
|
|
8408
|
-
console.log("\u6682\u65E0\u65E5\u5FD7");
|
|
8917
|
+
console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
|
|
8918
|
+
console.log("\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic");
|
|
8409
8919
|
return;
|
|
8410
8920
|
}
|
|
8411
8921
|
console.log("");
|
|
@@ -8433,6 +8943,7 @@ function cmdLogs(args) {
|
|
|
8433
8943
|
console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
|
|
8434
8944
|
console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
|
|
8435
8945
|
console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
|
|
8946
|
+
console.log(" mihomo-cli logs --diagnostic # \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6 (JSONL)");
|
|
8436
8947
|
console.log("");
|
|
8437
8948
|
}
|
|
8438
8949
|
|
|
@@ -8523,7 +9034,7 @@ async function cmdOverwrite(args) {
|
|
|
8523
9034
|
}
|
|
8524
9035
|
|
|
8525
9036
|
// src/commands/reset.ts
|
|
8526
|
-
import
|
|
9037
|
+
import fs18 from "fs";
|
|
8527
9038
|
var RESET_TARGETS = [
|
|
8528
9039
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
8529
9040
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -8535,7 +9046,7 @@ var RESET_TARGETS = [
|
|
|
8535
9046
|
label: "\u8986\u5199",
|
|
8536
9047
|
needsStop: false,
|
|
8537
9048
|
preserveOnBare: true,
|
|
8538
|
-
paths: () =>
|
|
9049
|
+
paths: () => fs18.existsSync(USER_DATA_DIR) ? fs18.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
8539
9050
|
},
|
|
8540
9051
|
{
|
|
8541
9052
|
// 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
|
|
@@ -8576,8 +9087,13 @@ async function cmdReset(args) {
|
|
|
8576
9087
|
const ids = new Set(targets.map((t) => t.id));
|
|
8577
9088
|
const needsStop = targets.some((t) => t.needsStop);
|
|
8578
9089
|
const serviceTargeted = ids.has("service");
|
|
8579
|
-
const
|
|
8580
|
-
|
|
9090
|
+
const needsServiceState = needsStop || serviceTargeted;
|
|
9091
|
+
const readServiceActive = () => {
|
|
9092
|
+
if (!needsServiceState) return false;
|
|
9093
|
+
const service = getServiceStatus();
|
|
9094
|
+
return service.installed || service.loaded;
|
|
9095
|
+
};
|
|
9096
|
+
let serviceActive = readServiceActive();
|
|
8581
9097
|
if (targets.length === 1) {
|
|
8582
9098
|
if (serviceTargeted && !serviceActive) {
|
|
8583
9099
|
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
@@ -8603,8 +9119,7 @@ async function cmdReset(args) {
|
|
|
8603
9119
|
console.log("\u5DF2\u53D6\u6D88");
|
|
8604
9120
|
return;
|
|
8605
9121
|
}
|
|
8606
|
-
|
|
8607
|
-
serviceActive = current.installed || current.loaded;
|
|
9122
|
+
serviceActive = readServiceActive();
|
|
8608
9123
|
let cleanup = null;
|
|
8609
9124
|
if (serviceActive) {
|
|
8610
9125
|
if (serviceTargeted) cleanup = await uninstallService();
|
|
@@ -8631,7 +9146,7 @@ async function cmdReset(args) {
|
|
|
8631
9146
|
for (const target of targets) {
|
|
8632
9147
|
let hadContent = target.id === "service" && serviceActive;
|
|
8633
9148
|
for (const filePath of target.paths()) {
|
|
8634
|
-
if (!
|
|
9149
|
+
if (!fs18.existsSync(filePath)) continue;
|
|
8635
9150
|
try {
|
|
8636
9151
|
rmrf(filePath);
|
|
8637
9152
|
} catch (e) {
|
|
@@ -8669,7 +9184,7 @@ async function cmdReset(args) {
|
|
|
8669
9184
|
}
|
|
8670
9185
|
|
|
8671
9186
|
// src/commands/service.ts
|
|
8672
|
-
import
|
|
9187
|
+
import fs19 from "fs";
|
|
8673
9188
|
function printRestoreSkipped() {
|
|
8674
9189
|
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
8675
9190
|
console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
|
|
@@ -8706,7 +9221,7 @@ async function cmdInstall(args) {
|
|
|
8706
9221
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
8707
9222
|
} else {
|
|
8708
9223
|
console.log("\u542F\u52A8: mihomo-cli start");
|
|
8709
|
-
if (!
|
|
9224
|
+
if (!fs19.existsSync(PATHS.configFile)) {
|
|
8710
9225
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
8711
9226
|
}
|
|
8712
9227
|
}
|
|
@@ -8838,6 +9353,7 @@ function readUrlFromClipboard() {
|
|
|
8838
9353
|
}
|
|
8839
9354
|
}
|
|
8840
9355
|
async function subAdd(args) {
|
|
9356
|
+
setDiagnosticCommand("sub add");
|
|
8841
9357
|
assertPositionalCount(args, 2, 2, "mihomo-cli sub add <url> [name]");
|
|
8842
9358
|
let url = args[2]?.trim();
|
|
8843
9359
|
const name = args[3] === void 0 ? "default" : args[3];
|
|
@@ -8881,6 +9397,7 @@ async function subAdd(args) {
|
|
|
8881
9397
|
printSubscriptionList();
|
|
8882
9398
|
}
|
|
8883
9399
|
async function subUpdate(args) {
|
|
9400
|
+
setDiagnosticCommand("sub update");
|
|
8884
9401
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub update [name]");
|
|
8885
9402
|
const nameArg = getNonFlagArg(args, 2);
|
|
8886
9403
|
const subs = getSubscriptions();
|
|
@@ -8925,6 +9442,7 @@ async function subUpdate(args) {
|
|
|
8925
9442
|
printSubscriptionList();
|
|
8926
9443
|
}
|
|
8927
9444
|
async function subUse(args) {
|
|
9445
|
+
setDiagnosticCommand("sub use");
|
|
8928
9446
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub use <name>");
|
|
8929
9447
|
assertRestartOptionValues(args);
|
|
8930
9448
|
const name = getNonFlagArg(args, 2);
|
|
@@ -8956,6 +9474,7 @@ async function subUse(args) {
|
|
|
8956
9474
|
printSubscriptionList();
|
|
8957
9475
|
}
|
|
8958
9476
|
async function subRemove(args) {
|
|
9477
|
+
setDiagnosticCommand("sub remove");
|
|
8959
9478
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub remove <name>");
|
|
8960
9479
|
const name = getNonFlagArg(args, 2);
|
|
8961
9480
|
const subs = getSubscriptions();
|
|
@@ -9123,7 +9642,12 @@ var COMMANDS = [
|
|
|
9123
9642
|
aliases: [],
|
|
9124
9643
|
handler: cmdLogs,
|
|
9125
9644
|
group: "interface",
|
|
9126
|
-
usage: [
|
|
9645
|
+
usage: [
|
|
9646
|
+
{
|
|
9647
|
+
signature: "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]",
|
|
9648
|
+
description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7\uFF1B--diagnostic \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6"
|
|
9649
|
+
}
|
|
9650
|
+
]
|
|
9127
9651
|
},
|
|
9128
9652
|
// === 订阅 ===
|
|
9129
9653
|
{
|
|
@@ -9244,12 +9768,14 @@ function allCommandTokens() {
|
|
|
9244
9768
|
|
|
9245
9769
|
// src/index.ts
|
|
9246
9770
|
process.on("SIGINT", () => {
|
|
9771
|
+
terminateActiveChildren("SIGINT");
|
|
9247
9772
|
if (!isSilentSigint()) {
|
|
9248
9773
|
console.error("\n\u6B63\u5728\u9000\u51FA...");
|
|
9249
9774
|
}
|
|
9250
9775
|
process.exit(130);
|
|
9251
9776
|
});
|
|
9252
9777
|
process.on("SIGTERM", () => {
|
|
9778
|
+
terminateActiveChildren("SIGTERM");
|
|
9253
9779
|
process.exit(143);
|
|
9254
9780
|
});
|
|
9255
9781
|
process.on("uncaughtException", (e) => {
|
|
@@ -9268,7 +9794,7 @@ process.on("unhandledRejection", (reason) => {
|
|
|
9268
9794
|
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
9269
9795
|
function readSelfMixedPortEarly() {
|
|
9270
9796
|
try {
|
|
9271
|
-
const raw = JSON.parse(
|
|
9797
|
+
const raw = JSON.parse(fs20.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9272
9798
|
const mixed = raw?.ports?.mixed;
|
|
9273
9799
|
if (isValidPortNumber(mixed)) return mixed;
|
|
9274
9800
|
} catch {
|
|
@@ -9337,6 +9863,7 @@ async function main() {
|
|
|
9337
9863
|
assertNotRoot("status");
|
|
9338
9864
|
ensureDirs();
|
|
9339
9865
|
cleanupStaleTmpFiles();
|
|
9866
|
+
beginDiagnosticOperation("status");
|
|
9340
9867
|
await printStatus();
|
|
9341
9868
|
printShortHelp();
|
|
9342
9869
|
return;
|
|
@@ -9356,6 +9883,7 @@ async function main() {
|
|
|
9356
9883
|
ensureDirs();
|
|
9357
9884
|
cleanupStaleTmpFiles();
|
|
9358
9885
|
captureStopEpochBaseline();
|
|
9886
|
+
beginDiagnosticOperation(command.name);
|
|
9359
9887
|
}
|
|
9360
9888
|
if (command.group === "meta") {
|
|
9361
9889
|
assertKnownFlags(args.slice(1), [], command.name);
|