mihomo-cli 4.8.0 → 4.9.0
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 +77 -2
- package/README.md +53 -13
- package/dist/index.js +858 -522
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -56,19 +56,22 @@ var compareVersions = (v1, v2) => {
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
// src/colors.ts
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
};
|
|
59
|
+
function colorEnabled(noColor, isTTY) {
|
|
60
|
+
return !(noColor !== void 0 && noColor !== "") && isTTY === true;
|
|
61
|
+
}
|
|
62
|
+
function createColors(enabled) {
|
|
63
|
+
const colorize = (code, str) => enabled ? `${code + String(str)}\x1B[0m` : String(str);
|
|
64
|
+
return {
|
|
65
|
+
bold: (s) => colorize("\x1B[1m", s),
|
|
66
|
+
red: (s) => colorize("\x1B[31m", s),
|
|
67
|
+
green: (s) => colorize("\x1B[32m", s),
|
|
68
|
+
yellow: (s) => colorize("\x1B[33m", s),
|
|
69
|
+
cyan: (s) => colorize("\x1B[36m", s),
|
|
70
|
+
gray: (s) => colorize("\x1B[90m", s)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
var colors = createColors(colorEnabled(process.env.NO_COLOR, process.stdout.isTTY));
|
|
74
|
+
var stderrColors = createColors(colorEnabled(process.env.NO_COLOR, process.stderr.isTTY));
|
|
72
75
|
|
|
73
76
|
// src/config.ts
|
|
74
77
|
import { execFile, spawnSync } from "child_process";
|
|
@@ -3200,6 +3203,9 @@ var CliError = class extends Error {
|
|
|
3200
3203
|
this.exitCode = options.exitCode ?? 1;
|
|
3201
3204
|
}
|
|
3202
3205
|
};
|
|
3206
|
+
function errorMessage(e) {
|
|
3207
|
+
return e instanceof Error ? e.message : String(e);
|
|
3208
|
+
}
|
|
3203
3209
|
function withTimeout(promise, ms) {
|
|
3204
3210
|
return new Promise((resolve, reject) => {
|
|
3205
3211
|
const timer = setTimeout(() => reject(new TimeoutError()), ms);
|
|
@@ -3327,8 +3333,9 @@ function rmrf(dir) {
|
|
|
3327
3333
|
}
|
|
3328
3334
|
var LOCK_STALE_MS = 1e4;
|
|
3329
3335
|
var LOCK_RETRY_MS = 20;
|
|
3330
|
-
function withFileLock(lockPath, fn) {
|
|
3331
|
-
const
|
|
3336
|
+
function withFileLock(lockPath, fn, opts) {
|
|
3337
|
+
const staleMs = opts?.staleMs ?? LOCK_STALE_MS;
|
|
3338
|
+
const deadline = Date.now() + (opts?.deadlineMs ?? LOCK_STALE_MS);
|
|
3332
3339
|
const token = `${process.pid}-${process.hrtime.bigint()}`;
|
|
3333
3340
|
let fd = null;
|
|
3334
3341
|
while (fd === null) {
|
|
@@ -3351,7 +3358,7 @@ function withFileLock(lockPath, fn) {
|
|
|
3351
3358
|
if (e.code !== "EEXIST") throw e;
|
|
3352
3359
|
let stale = false;
|
|
3353
3360
|
try {
|
|
3354
|
-
stale = Date.now() - fs.statSync(lockPath).mtimeMs >
|
|
3361
|
+
stale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3355
3362
|
} catch {
|
|
3356
3363
|
}
|
|
3357
3364
|
if (stale) {
|
|
@@ -3362,11 +3369,18 @@ function withFileLock(lockPath, fn) {
|
|
|
3362
3369
|
continue;
|
|
3363
3370
|
}
|
|
3364
3371
|
if (Date.now() > deadline) {
|
|
3372
|
+
let deadlineStale = false;
|
|
3365
3373
|
try {
|
|
3366
|
-
fs.
|
|
3374
|
+
deadlineStale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3367
3375
|
} catch {
|
|
3368
3376
|
}
|
|
3369
|
-
|
|
3377
|
+
if (deadlineStale) {
|
|
3378
|
+
try {
|
|
3379
|
+
fs.rmSync(lockPath, { force: true });
|
|
3380
|
+
} catch {
|
|
3381
|
+
}
|
|
3382
|
+
continue;
|
|
3383
|
+
}
|
|
3370
3384
|
}
|
|
3371
3385
|
sleepSyncMs(LOCK_RETRY_MS);
|
|
3372
3386
|
}
|
|
@@ -3449,15 +3463,19 @@ function getPorts(settings = readSettings()) {
|
|
|
3449
3463
|
if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
|
|
3450
3464
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3451
3465
|
}
|
|
3452
|
-
const
|
|
3453
|
-
const
|
|
3454
|
-
|
|
3455
|
-
|
|
3466
|
+
const configuredMixed = validatePort(ports.mixed, "ports.mixed");
|
|
3467
|
+
const configuredController = validatePort(ports.controller, "ports.controller");
|
|
3468
|
+
const mixed = configuredMixed ?? DEFAULT_MIXED_PORT;
|
|
3469
|
+
const controller = configuredController ?? CONTROLLER_PORT;
|
|
3470
|
+
if (mixed === controller) {
|
|
3471
|
+
const defaultedKey = configuredMixed === void 0 ? "ports.mixed" : configuredController === void 0 ? "ports.controller" : null;
|
|
3472
|
+
const source = defaultedKey ? `\uFF1A${defaultedKey} \u672A\u914D\u7F6E\uFF0C\u53D6\u9ED8\u8BA4 ${mixed}` : "";
|
|
3473
|
+
throw new CliError(`ports.mixed \u4E0E ports.controller \u4E0D\u80FD\u76F8\u540C\uFF08\u5F53\u524D\u5747\u4E3A ${mixed}${source}\uFF09`, {
|
|
3456
3474
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3457
3475
|
hint: ["\u6DF7\u5408\u7AEF\u53E3\u4E0E\u63A7\u5236\u5668\u7AEF\u53E3\u5404\u9700\u72EC\u7ACB\u7AEF\u53E3\uFF0C\u76F8\u540C\u4F1A\u5BFC\u81F4\u5185\u6838\u542F\u52A8\u5931\u8D25"]
|
|
3458
3476
|
});
|
|
3459
3477
|
}
|
|
3460
|
-
return { mixed
|
|
3478
|
+
return { mixed, controller };
|
|
3461
3479
|
}
|
|
3462
3480
|
function maskSingleUrl(url) {
|
|
3463
3481
|
try {
|
|
@@ -3641,6 +3659,7 @@ function parseOverrideKey(key) {
|
|
|
3641
3659
|
let arrayPrepend = false;
|
|
3642
3660
|
let arrayAppend = false;
|
|
3643
3661
|
let arrayMergeByName = false;
|
|
3662
|
+
let arrayMergeOnly = false;
|
|
3644
3663
|
const lastChar = key[key.length - 1];
|
|
3645
3664
|
const openAngleCount = (key.match(/</g) || []).length;
|
|
3646
3665
|
const closeAngleCount = (key.match(/>/g) || []).length;
|
|
@@ -3664,6 +3683,13 @@ function parseOverrideKey(key) {
|
|
|
3664
3683
|
} else if (actualKey.startsWith("~")) {
|
|
3665
3684
|
arrayMergeByName = true;
|
|
3666
3685
|
actualKey = actualKey.slice(1);
|
|
3686
|
+
if (actualKey.startsWith("?")) {
|
|
3687
|
+
arrayMergeOnly = true;
|
|
3688
|
+
actualKey = actualKey.slice(1);
|
|
3689
|
+
}
|
|
3690
|
+
if (/^<[^>]+>$/.test(actualKey)) {
|
|
3691
|
+
actualKey = actualKey.slice(1, -1);
|
|
3692
|
+
}
|
|
3667
3693
|
} else {
|
|
3668
3694
|
if (actualKey.startsWith("+")) {
|
|
3669
3695
|
arrayPrepend = true;
|
|
@@ -3674,9 +3700,9 @@ function parseOverrideKey(key) {
|
|
|
3674
3700
|
actualKey = actualKey.slice(0, -1);
|
|
3675
3701
|
}
|
|
3676
3702
|
}
|
|
3677
|
-
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName };
|
|
3703
|
+
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly };
|
|
3678
3704
|
}
|
|
3679
|
-
function
|
|
3705
|
+
function mergeConfigLevel(target, override, collectors, parseOperators) {
|
|
3680
3706
|
let t = target;
|
|
3681
3707
|
if (t === null || t === void 0) {
|
|
3682
3708
|
t = Array.isArray(override) ? [] : {};
|
|
@@ -3692,7 +3718,17 @@ function deepMergeWithOverrides(target, override) {
|
|
|
3692
3718
|
}
|
|
3693
3719
|
const result = { ...t };
|
|
3694
3720
|
for (const [rawKey, value] of Object.entries(override)) {
|
|
3695
|
-
|
|
3721
|
+
let key = rawKey;
|
|
3722
|
+
let forceOverwrite = false;
|
|
3723
|
+
let arrayPrepend = false;
|
|
3724
|
+
let arrayAppend = false;
|
|
3725
|
+
let arrayMergeByName = false;
|
|
3726
|
+
let arrayMergeOnly = false;
|
|
3727
|
+
if (parseOperators) {
|
|
3728
|
+
({ key, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly } = parseOverrideKey(rawKey));
|
|
3729
|
+
} else if (isOperatorShapedNestedKey(rawKey)) {
|
|
3730
|
+
noteOperatorShapedKey(collectors, rawKey);
|
|
3731
|
+
}
|
|
3696
3732
|
const existingValue = result[key];
|
|
3697
3733
|
if (arrayMergeByName) {
|
|
3698
3734
|
if (existingValue !== void 0 && !Array.isArray(existingValue)) {
|
|
@@ -3714,7 +3750,9 @@ function deepMergeWithOverrides(target, override) {
|
|
|
3714
3750
|
const name = item && typeof item === "object" && !Array.isArray(item) ? item.name : void 0;
|
|
3715
3751
|
const idx = name != null ? merged.findIndex((e) => e && typeof e === "object" && e.name === name) : -1;
|
|
3716
3752
|
if (idx >= 0) {
|
|
3717
|
-
merged[idx] =
|
|
3753
|
+
merged[idx] = mergeConfigLevel(merged[idx], item, collectors, false);
|
|
3754
|
+
} else if (arrayMergeOnly) {
|
|
3755
|
+
collectors.skipped.push({ key, name: name == null ? "(\u65E0 name)" : String(name) });
|
|
3718
3756
|
} else {
|
|
3719
3757
|
merged.push(item);
|
|
3720
3758
|
}
|
|
@@ -3746,13 +3784,21 @@ function deepMergeWithOverrides(target, override) {
|
|
|
3746
3784
|
continue;
|
|
3747
3785
|
}
|
|
3748
3786
|
if (value !== null && typeof value === "object" && !Array.isArray(value) && existingValue !== null && typeof existingValue === "object" && !Array.isArray(existingValue)) {
|
|
3749
|
-
result[key] =
|
|
3787
|
+
result[key] = mergeConfigLevel(existingValue, value, collectors, false);
|
|
3750
3788
|
continue;
|
|
3751
3789
|
}
|
|
3752
3790
|
result[key] = value;
|
|
3753
3791
|
}
|
|
3754
3792
|
return result;
|
|
3755
3793
|
}
|
|
3794
|
+
function isOperatorShapedNestedKey(key) {
|
|
3795
|
+
if (key.startsWith("+.")) return false;
|
|
3796
|
+
return key.startsWith("~") || key.startsWith("+") || key.endsWith("!") || key.endsWith("+") || /^<[^>]+>$/.test(key);
|
|
3797
|
+
}
|
|
3798
|
+
function noteOperatorShapedKey(collectors, key) {
|
|
3799
|
+
if (collectors.operatorShapedKeys.some((note) => note.key === key)) return;
|
|
3800
|
+
collectors.operatorShapedKeys.push({ key });
|
|
3801
|
+
}
|
|
3756
3802
|
function isOverwriteEnabled() {
|
|
3757
3803
|
const settings = readSettings();
|
|
3758
3804
|
return settings.overwrite_enabled !== false;
|
|
@@ -3763,6 +3809,11 @@ function setOverwriteEnabled(enabled) {
|
|
|
3763
3809
|
function isOverwriteFilename(filename) {
|
|
3764
3810
|
return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
|
|
3765
3811
|
}
|
|
3812
|
+
function isOverwriteFilenameTypo(filename) {
|
|
3813
|
+
if (isOverwriteFilename(filename)) return false;
|
|
3814
|
+
const lower = filename.toLowerCase();
|
|
3815
|
+
return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower);
|
|
3816
|
+
}
|
|
3766
3817
|
var MATCH_KEYS = /* @__PURE__ */ new Set(["subscription", "url-domain"]);
|
|
3767
3818
|
function normalizeMatch(raw, fileName) {
|
|
3768
3819
|
if (raw == null) return void 0;
|
|
@@ -3810,6 +3861,9 @@ function summarizeMatch(match) {
|
|
|
3810
3861
|
}
|
|
3811
3862
|
return parts.length > 0 ? parts.join(", ") : void 0;
|
|
3812
3863
|
}
|
|
3864
|
+
function describeOverwriteScope(file) {
|
|
3865
|
+
return `${file.name} (${summarizeMatch(file.match) ?? "\u5168\u5C40"})`;
|
|
3866
|
+
}
|
|
3813
3867
|
function hostMatchesDomain(host, domain) {
|
|
3814
3868
|
const h = host.toLowerCase();
|
|
3815
3869
|
const d = domain.toLowerCase();
|
|
@@ -3842,11 +3896,17 @@ function filterOverwriteFilesByScope(files, scope) {
|
|
|
3842
3896
|
function loadOverwriteFile() {
|
|
3843
3897
|
const dir = USER_DATA_DIR;
|
|
3844
3898
|
if (!fs3.existsSync(dir)) return [];
|
|
3845
|
-
const
|
|
3899
|
+
const entries = fs3.readdirSync(dir);
|
|
3900
|
+
const files = entries.filter(isOverwriteFilename).sort((a, b) => {
|
|
3846
3901
|
if (a === "overwrite.yaml") return -1;
|
|
3847
3902
|
if (b === "overwrite.yaml") return 1;
|
|
3848
3903
|
return a.localeCompare(b);
|
|
3849
3904
|
});
|
|
3905
|
+
for (const typo of entries.filter((e) => isOverwriteFilenameTypo(e))) {
|
|
3906
|
+
console.warn(
|
|
3907
|
+
`\u8B66\u544A: "${typo}" \u4E0D\u4F1A\u88AB\u5F53\u4F5C\u8986\u5199\u6587\u4EF6\u52A0\u8F7D\uFF08\u5408\u6CD5\u6587\u4EF6\u540D: overwrite.yaml \u4E3B\u6587\u4EF6\u3001overwrite.*.yaml / overwrite.*.yml \u6269\u5C55\u6587\u4EF6\uFF1B\u4E3B\u6587\u4EF6\u4E0D\u652F\u6301 .yml\uFF09\uFF1B\u82E5\u662F\u7B14\u8BEF\u8BF7\u6539\u540D`
|
|
3908
|
+
);
|
|
3909
|
+
}
|
|
3850
3910
|
const results = [];
|
|
3851
3911
|
for (const file of files) {
|
|
3852
3912
|
const filePath = path3.join(dir, file);
|
|
@@ -3868,8 +3928,15 @@ function loadOverwriteFile() {
|
|
|
3868
3928
|
}
|
|
3869
3929
|
function applyOverwrite(baseConfig, files) {
|
|
3870
3930
|
let result = { ...baseConfig };
|
|
3871
|
-
|
|
3872
|
-
|
|
3931
|
+
const skipped = [];
|
|
3932
|
+
const operatorShapedKeys = [];
|
|
3933
|
+
for (const file of files) {
|
|
3934
|
+
const collectors = { skipped: [], operatorShapedKeys: [] };
|
|
3935
|
+
result = mergeConfigLevel(result, file.config, collectors, true);
|
|
3936
|
+
for (const s of collectors.skipped) skipped.push({ ...s, file: file.name });
|
|
3937
|
+
for (const k of collectors.operatorShapedKeys) operatorShapedKeys.push({ ...k, file: file.name });
|
|
3938
|
+
}
|
|
3939
|
+
return { config: result, skipped, operatorShapedKeys };
|
|
3873
3940
|
}
|
|
3874
3941
|
function listOverwriteFile() {
|
|
3875
3942
|
const files = loadOverwriteFile();
|
|
@@ -3902,6 +3969,26 @@ var FLAGS = [
|
|
|
3902
3969
|
];
|
|
3903
3970
|
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
3904
3971
|
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
3972
|
+
function matchValueFlagToken(token) {
|
|
3973
|
+
const byForm = (form) => FLAGS.find((f) => f.takesValue && f.forms.includes(form));
|
|
3974
|
+
const exact = byForm(token);
|
|
3975
|
+
if (exact) return { spec: exact, baseForm: token, form: "exact", inlineValue: null };
|
|
3976
|
+
if (token.startsWith("--")) {
|
|
3977
|
+
const eqIdx = token.indexOf("=");
|
|
3978
|
+
if (eqIdx > 2) {
|
|
3979
|
+
const base = token.slice(0, eqIdx);
|
|
3980
|
+
const spec = byForm(base);
|
|
3981
|
+
if (spec) return { spec, baseForm: base, form: "long-eq", inlineValue: token.slice(eqIdx + 1) };
|
|
3982
|
+
}
|
|
3983
|
+
return null;
|
|
3984
|
+
}
|
|
3985
|
+
if (token.length > 2 && token.startsWith("-")) {
|
|
3986
|
+
const base = token.slice(0, 2);
|
|
3987
|
+
const spec = byForm(base);
|
|
3988
|
+
if (spec) return { spec, baseForm: base, form: "attached-short", inlineValue: token.slice(2) };
|
|
3989
|
+
}
|
|
3990
|
+
return null;
|
|
3991
|
+
}
|
|
3905
3992
|
|
|
3906
3993
|
// src/utils.ts
|
|
3907
3994
|
function sleep(ms) {
|
|
@@ -4017,15 +4104,33 @@ function assertKnownFlags(args, known, command) {
|
|
|
4017
4104
|
for (const a of args) {
|
|
4018
4105
|
if (!a.startsWith("-") || a === "-") continue;
|
|
4019
4106
|
if (knownSet.has(a)) continue;
|
|
4020
|
-
const
|
|
4021
|
-
if (
|
|
4022
|
-
if (a.
|
|
4107
|
+
const match = matchValueFlagToken(a);
|
|
4108
|
+
if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
|
|
4109
|
+
if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
|
|
4023
4110
|
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
4024
4111
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4025
4112
|
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
4026
4113
|
});
|
|
4027
4114
|
}
|
|
4028
4115
|
}
|
|
4116
|
+
function assertPositionalCount(args, max, startIdx, usage, valueFlags = VALUE_FLAGS) {
|
|
4117
|
+
if (!args) return;
|
|
4118
|
+
let count = 0;
|
|
4119
|
+
for (let i = startIdx; i < args.length; i++) {
|
|
4120
|
+
const a = args[i];
|
|
4121
|
+
if (a.startsWith("-")) {
|
|
4122
|
+
if (valueFlags.has(a)) i++;
|
|
4123
|
+
continue;
|
|
4124
|
+
}
|
|
4125
|
+
count++;
|
|
4126
|
+
if (count > max) {
|
|
4127
|
+
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
|
|
4128
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4129
|
+
hint: [`\u7528\u6CD5: ${usage}`]
|
|
4130
|
+
});
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4029
4134
|
function parseIntArg(args, short, long, defaultValue) {
|
|
4030
4135
|
if (!args) return defaultValue;
|
|
4031
4136
|
const parse = (raw, flag) => {
|
|
@@ -4045,11 +4150,9 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
4045
4150
|
}
|
|
4046
4151
|
throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
|
|
4047
4152
|
}
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
|
|
4052
|
-
return parse(args[i].slice(short.length), short);
|
|
4153
|
+
const match = matchValueFlagToken(args[i]);
|
|
4154
|
+
if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
|
|
4155
|
+
return parse(match.inlineValue ?? "", match.baseForm);
|
|
4053
4156
|
}
|
|
4054
4157
|
}
|
|
4055
4158
|
return defaultValue;
|
|
@@ -4058,12 +4161,16 @@ function extractStartOptions(args) {
|
|
|
4058
4161
|
if (!args) return [];
|
|
4059
4162
|
const out = [];
|
|
4060
4163
|
for (let i = 0; i < args.length; i++) {
|
|
4061
|
-
const
|
|
4062
|
-
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
|
|
4164
|
+
const token = args[i];
|
|
4165
|
+
if (START_RESTART_FLAGS.some((f) => !f.takesValue && f.forms.includes(token))) {
|
|
4166
|
+
out.push(token);
|
|
4167
|
+
continue;
|
|
4168
|
+
}
|
|
4169
|
+
const match = matchValueFlagToken(token);
|
|
4170
|
+
if (!match?.spec.passthroughToRestart) continue;
|
|
4171
|
+
out.push(token);
|
|
4172
|
+
if (match.form === "exact" && i + 1 < args.length) {
|
|
4173
|
+
out.push(args[++i]);
|
|
4067
4174
|
}
|
|
4068
4175
|
}
|
|
4069
4176
|
return out;
|
|
@@ -4255,9 +4362,18 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4255
4362
|
const settings = readSettings();
|
|
4256
4363
|
const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
|
|
4257
4364
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4258
|
-
const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4365
|
+
const { config: withOverwrites, skipped: skippedMerges, operatorShapedKeys } = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4366
|
+
const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
|
|
4259
4367
|
const systemConfig = {};
|
|
4260
4368
|
const lockedWarnings = [];
|
|
4369
|
+
for (const s of skippedMerges) {
|
|
4370
|
+
lockedWarnings.push(`\u8986\u5199 ~?${s.key} \u7684\u8865\u4E01 "${s.name}" \u672A\u5339\u914D\u5230\u5F53\u524D\u8BA2\u9605\u4E2D\u7684\u540C\u540D\u5143\u7D20\uFF0C\u5DF2\u8DF3\u8FC7${s.file ? `\uFF08${s.file}\uFF09` : ""}`);
|
|
4371
|
+
}
|
|
4372
|
+
for (const n of operatorShapedKeys) {
|
|
4373
|
+
lockedWarnings.push(
|
|
4374
|
+
`\u8986\u5199${n.file ? `\u6587\u4EF6 ${n.file} \u7684` : ""}\u5D4C\u5957\u952E "${n.key}" \u5F62\u4F3C\u64CD\u4F5C\u7B26\uFF0C\u5DF2\u6309\u5B57\u9762\u952E\u540D\u4FDD\u7559\uFF1B\u64CD\u4F5C\u7B26\u53EA\u5728\u8986\u5199\u6587\u4EF6\u9876\u5C42\u751F\u6548\uFF0C\u82E5\u8FD9\u662F mihomo \u539F\u751F\u952E\u53EF\u5FFD\u7565\u672C\u63D0\u793A`
|
|
4375
|
+
);
|
|
4376
|
+
}
|
|
4261
4377
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4262
4378
|
if (!(key in withOverwrites)) {
|
|
4263
4379
|
systemConfig[key] = value;
|
|
@@ -4269,6 +4385,8 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4269
4385
|
delete withOverwrites["mixed-port"];
|
|
4270
4386
|
delete withOverwrites.port;
|
|
4271
4387
|
delete withOverwrites["socks-port"];
|
|
4388
|
+
delete withOverwrites["redir-port"];
|
|
4389
|
+
delete withOverwrites["tproxy-port"];
|
|
4272
4390
|
delete withOverwrites["external-ui"];
|
|
4273
4391
|
delete withOverwrites["external-ui-name"];
|
|
4274
4392
|
delete withOverwrites["external-ui-url"];
|
|
@@ -4310,14 +4428,25 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4310
4428
|
};
|
|
4311
4429
|
}
|
|
4312
4430
|
assertConfigShape(merged);
|
|
4313
|
-
return { config: merged, warnings: lockedWarnings };
|
|
4431
|
+
return { config: merged, warnings: lockedWarnings, overwriteSummaries };
|
|
4314
4432
|
}
|
|
4315
4433
|
function writeMihomoConfig(configObj) {
|
|
4316
4434
|
ensureDirs();
|
|
4317
4435
|
const content = dumpYaml(configObj);
|
|
4318
4436
|
atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
|
|
4319
4437
|
}
|
|
4320
|
-
|
|
4438
|
+
var HINT_INDENT = " ";
|
|
4439
|
+
function buildKernelRejectHint(detail, overwriteSummaries) {
|
|
4440
|
+
const hint = ["", ...detail.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
|
|
4441
|
+
if (overwriteSummaries.length > 0) {
|
|
4442
|
+
hint.push("", `${HINT_INDENT}\u5F53\u524D\u751F\u6548\u7684\u8986\u5199\u6587\u4EF6:`);
|
|
4443
|
+
for (const summary of overwriteSummaries) hint.push(sanitizeTerminal(`${HINT_INDENT.repeat(2)}${summary}`));
|
|
4444
|
+
hint.push(`${HINT_INDENT}\u82E5\u62A5\u9519\u7684\u5143\u7D20\u6765\u81EA\u8986\u5199\u8FFD\u52A0\uFF08~key \u672A\u5339\u914D\u5230\u540C\u540D\u5143\u7D20\u65F6\u4F1A\u65B0\u589E\uFF09\uFF0C\u6539\u7528 ~?key \u53EF\u5728\u7F3A\u5C11\u8BE5\u5143\u7D20\u7684\u8BA2\u9605\u4E0A\u8DF3\u8FC7\u3002`);
|
|
4445
|
+
}
|
|
4446
|
+
hint.push("", `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
|
|
4447
|
+
return hint;
|
|
4448
|
+
}
|
|
4449
|
+
async function validateConfigWithKernel(config, overwriteSummaries) {
|
|
4321
4450
|
if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4322
4451
|
ensureDirs();
|
|
4323
4452
|
const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
|
|
@@ -4334,9 +4463,15 @@ async function validateConfigWithKernel(config) {
|
|
|
4334
4463
|
const error = e;
|
|
4335
4464
|
const detail = sanitizeTerminal(`${error.stdout || ""}
|
|
4336
4465
|
${error.stderr || ""}`).trim();
|
|
4337
|
-
|
|
4466
|
+
if (error.killed) {
|
|
4467
|
+
throw new CliError("\u5185\u6838\u914D\u7F6E\u6821\u9A8C\u8D85\u65F6", {
|
|
4468
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4469
|
+
hint: buildKernelRejectHint(detail || error.message, [])
|
|
4470
|
+
});
|
|
4471
|
+
}
|
|
4472
|
+
throw new CliError("\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
|
|
4338
4473
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4339
|
-
hint:
|
|
4474
|
+
hint: buildKernelRejectHint(detail || error.message, overwriteSummaries)
|
|
4340
4475
|
});
|
|
4341
4476
|
}
|
|
4342
4477
|
} finally {
|
|
@@ -4440,23 +4575,51 @@ function readLogTail(maxLines = 15) {
|
|
|
4440
4575
|
}
|
|
4441
4576
|
}
|
|
4442
4577
|
}
|
|
4578
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
4443
4579
|
function allocateArchivePath() {
|
|
4444
4580
|
const timestamp = formatLocalTimestamp();
|
|
4445
|
-
let
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4581
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
4582
|
+
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
4583
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
4584
|
+
let fd = null;
|
|
4585
|
+
try {
|
|
4586
|
+
fd = fs5.openSync(archivePath, "wx");
|
|
4587
|
+
} catch (e) {
|
|
4588
|
+
if (e.code === "EEXIST") continue;
|
|
4589
|
+
throw e;
|
|
4590
|
+
}
|
|
4591
|
+
try {
|
|
4592
|
+
fs5.closeSync(fd);
|
|
4593
|
+
} catch {
|
|
4594
|
+
}
|
|
4595
|
+
return archivePath;
|
|
4450
4596
|
}
|
|
4451
|
-
|
|
4597
|
+
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`, {
|
|
4598
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
4599
|
+
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`]
|
|
4600
|
+
});
|
|
4452
4601
|
}
|
|
4453
4602
|
function rotateLog() {
|
|
4454
4603
|
const logFile = PATHS.logFile;
|
|
4455
|
-
|
|
4456
|
-
|
|
4604
|
+
let stat;
|
|
4605
|
+
try {
|
|
4606
|
+
stat = fs5.statSync(logFile);
|
|
4607
|
+
} catch (e) {
|
|
4608
|
+
if (e.code === "ENOENT") return null;
|
|
4609
|
+
throw e;
|
|
4610
|
+
}
|
|
4457
4611
|
if (stat.size === 0) return null;
|
|
4458
4612
|
const rotatedPath = allocateArchivePath();
|
|
4459
|
-
|
|
4613
|
+
try {
|
|
4614
|
+
fs5.renameSync(logFile, rotatedPath);
|
|
4615
|
+
} catch (e) {
|
|
4616
|
+
try {
|
|
4617
|
+
fs5.unlinkSync(rotatedPath);
|
|
4618
|
+
} catch {
|
|
4619
|
+
}
|
|
4620
|
+
if (e.code === "ENOENT") return null;
|
|
4621
|
+
throw e;
|
|
4622
|
+
}
|
|
4460
4623
|
return rotatedPath;
|
|
4461
4624
|
}
|
|
4462
4625
|
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
@@ -4631,6 +4794,18 @@ import { spawnSync as spawnSync3 } from "child_process";
|
|
|
4631
4794
|
import fs7 from "fs";
|
|
4632
4795
|
import path6 from "path";
|
|
4633
4796
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
4797
|
+
var SudoAuthError = class extends Error {
|
|
4798
|
+
constructor() {
|
|
4799
|
+
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4800
|
+
this.name = "SudoAuthError";
|
|
4801
|
+
}
|
|
4802
|
+
};
|
|
4803
|
+
function sudoExitToError(action, status, codeMessages) {
|
|
4804
|
+
if (status === 1) return new SudoAuthError();
|
|
4805
|
+
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4806
|
+
const custom = codeMessages?.[status];
|
|
4807
|
+
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
4808
|
+
}
|
|
4634
4809
|
function runSudoScript(scriptBody, opts) {
|
|
4635
4810
|
if (!process.stdin.isTTY) {
|
|
4636
4811
|
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
@@ -4642,16 +4817,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
4642
4817
|
try {
|
|
4643
4818
|
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
4644
4819
|
if (result.error) throw result.error;
|
|
4645
|
-
if (result.status !== 0)
|
|
4646
|
-
if (result.status === 1) {
|
|
4647
|
-
throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4648
|
-
}
|
|
4649
|
-
if (result.status == null) {
|
|
4650
|
-
throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4651
|
-
}
|
|
4652
|
-
const custom = opts.codeMessages?.[result.status];
|
|
4653
|
-
throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
|
|
4654
|
-
}
|
|
4820
|
+
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
4655
4821
|
} finally {
|
|
4656
4822
|
try {
|
|
4657
4823
|
fs7.unlinkSync(scriptPath);
|
|
@@ -4675,6 +4841,7 @@ var SERVICE_OBSERVE_MS = 1200;
|
|
|
4675
4841
|
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
4676
4842
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4677
4843
|
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
4844
|
+
var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
|
|
4678
4845
|
function serviceTarget() {
|
|
4679
4846
|
return `${bootstrapDomain()}/${SERVICE_LABEL}`;
|
|
4680
4847
|
}
|
|
@@ -4723,8 +4890,8 @@ function assertLaunchctlQueryOk(status, what) {
|
|
|
4723
4890
|
hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
|
|
4724
4891
|
});
|
|
4725
4892
|
}
|
|
4726
|
-
function isServiceDisabledInLaunchd() {
|
|
4727
|
-
const out = runLaunchctl(["print-disabled", bootstrapDomain()]);
|
|
4893
|
+
function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
4894
|
+
const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
|
|
4728
4895
|
assertLaunchctlQueryOk(out.status, "print-disabled");
|
|
4729
4896
|
return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
|
|
4730
4897
|
}
|
|
@@ -4831,16 +4998,16 @@ function ensureServiceSymlink() {
|
|
|
4831
4998
|
}
|
|
4832
4999
|
fs8.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
4833
5000
|
}
|
|
4834
|
-
function runLaunchctlOrThrow(args, what) {
|
|
4835
|
-
const result = runLaunchctl(args);
|
|
5001
|
+
function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5002
|
+
const result = runLaunchctl(args, timeoutMs);
|
|
4836
5003
|
if (result.status === 0) return;
|
|
4837
5004
|
const detail = result.stderr.trim();
|
|
4838
5005
|
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4839
5006
|
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
|
|
4840
5007
|
});
|
|
4841
5008
|
}
|
|
4842
|
-
function bootoutService() {
|
|
4843
|
-
const result = runLaunchctl(["bootout", serviceTarget()]);
|
|
5009
|
+
function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5010
|
+
const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
|
|
4844
5011
|
if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
4845
5012
|
const detail = result.stderr.trim();
|
|
4846
5013
|
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
@@ -4880,7 +5047,36 @@ function cleanupRootResidue() {
|
|
|
4880
5047
|
].join("\n");
|
|
4881
5048
|
runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh", codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" } });
|
|
4882
5049
|
}
|
|
4883
|
-
function
|
|
5050
|
+
function buildRootResidueCleanupError(e, ctx, rootPids) {
|
|
5051
|
+
const cancelled = e instanceof SudoAuthError;
|
|
5052
|
+
const hasKernelResidue = rootPids.length > 0;
|
|
5053
|
+
const hint = [
|
|
5054
|
+
ctx.mainOutcome,
|
|
5055
|
+
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u88AB\u6E05\u7406: ${PATHS.pidFile}`,
|
|
5056
|
+
`\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`
|
|
5057
|
+
];
|
|
5058
|
+
hint.push(hasKernelResidue ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5059
|
+
if (cancelled) {
|
|
5060
|
+
return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
|
|
5061
|
+
}
|
|
5062
|
+
return new CliError(e.message, { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5063
|
+
}
|
|
5064
|
+
function currentRootResiduePids() {
|
|
5065
|
+
try {
|
|
5066
|
+
return getMihomoPids().filter(isProcessRoot);
|
|
5067
|
+
} catch {
|
|
5068
|
+
return [];
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
function cleanupRootResidueOrThrow(ctx) {
|
|
5072
|
+
try {
|
|
5073
|
+
cleanupRootResidue();
|
|
5074
|
+
} catch (e) {
|
|
5075
|
+
if (e instanceof CliError) throw e;
|
|
5076
|
+
throw buildRootResidueCleanupError(e, ctx, currentRootResiduePids());
|
|
5077
|
+
}
|
|
5078
|
+
}
|
|
5079
|
+
function killResidualKernels(ctx) {
|
|
4884
5080
|
const pids = getMihomoPids();
|
|
4885
5081
|
if (pids.length === 0) return;
|
|
4886
5082
|
const rootPids = pids.filter(isProcessRoot);
|
|
@@ -4891,7 +5087,7 @@ function killResidualKernels() {
|
|
|
4891
5087
|
} catch {
|
|
4892
5088
|
}
|
|
4893
5089
|
}
|
|
4894
|
-
if (rootPids.length > 0)
|
|
5090
|
+
if (rootPids.length > 0) cleanupRootResidueOrThrow(ctx);
|
|
4895
5091
|
}
|
|
4896
5092
|
async function installService(wasRunning, stopEpochBefore) {
|
|
4897
5093
|
assertServiceLabelSafe();
|
|
@@ -4974,7 +5170,7 @@ async function startService(stopEpochBefore) {
|
|
|
4974
5170
|
]
|
|
4975
5171
|
});
|
|
4976
5172
|
}
|
|
4977
|
-
|
|
5173
|
+
cleanupRootResidueOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
|
|
4978
5174
|
bootoutService();
|
|
4979
5175
|
await waitUntilUnloaded();
|
|
4980
5176
|
rotateAndCleanupLogs();
|
|
@@ -4989,10 +5185,10 @@ async function startService(stopEpochBefore) {
|
|
|
4989
5185
|
});
|
|
4990
5186
|
return { started };
|
|
4991
5187
|
}
|
|
4992
|
-
function disableServiceAutoStart() {
|
|
5188
|
+
function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
4993
5189
|
assertServiceLabelSafe();
|
|
4994
|
-
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F");
|
|
4995
|
-
if (!isServiceDisabledInLaunchd()) {
|
|
5190
|
+
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
|
|
5191
|
+
if (!isServiceDisabledInLaunchd(timeoutMs)) {
|
|
4996
5192
|
throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
|
|
4997
5193
|
hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
|
|
4998
5194
|
});
|
|
@@ -5002,17 +5198,17 @@ function disableServiceAutoStart() {
|
|
|
5002
5198
|
async function stopService() {
|
|
5003
5199
|
assertServiceLabelSafe();
|
|
5004
5200
|
withFileLock(PATHS.serviceLock, () => {
|
|
5005
|
-
bootoutService();
|
|
5006
|
-
disableServiceAutoStart();
|
|
5201
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5202
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5007
5203
|
});
|
|
5008
5204
|
await waitUntilUnloaded();
|
|
5009
|
-
killResidualKernels();
|
|
5205
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
|
|
5010
5206
|
}
|
|
5011
5207
|
async function uninstallService() {
|
|
5012
5208
|
assertServiceLabelSafe();
|
|
5013
5209
|
withFileLock(PATHS.serviceLock, () => {
|
|
5014
|
-
bootoutService();
|
|
5015
|
-
disableServiceAutoStart();
|
|
5210
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5211
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5016
5212
|
});
|
|
5017
5213
|
await waitUntilUnloaded();
|
|
5018
5214
|
try {
|
|
@@ -5021,15 +5217,14 @@ async function uninstallService() {
|
|
|
5021
5217
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5022
5218
|
}
|
|
5023
5219
|
disableServiceAutoStart();
|
|
5024
|
-
killResidualKernels();
|
|
5220
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5025
5221
|
try {
|
|
5026
5222
|
fs8.rmSync(PATHS.serviceBinary, { force: true });
|
|
5027
5223
|
} catch {
|
|
5028
5224
|
}
|
|
5029
5225
|
}
|
|
5030
|
-
function
|
|
5031
|
-
|
|
5032
|
-
const script = [
|
|
5226
|
+
function buildLegacyCleanupScript() {
|
|
5227
|
+
return [
|
|
5033
5228
|
"#!/bin/bash",
|
|
5034
5229
|
// bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
|
|
5035
5230
|
// 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
|
|
@@ -5037,7 +5232,7 @@ function cleanupLegacySystemInstall() {
|
|
|
5037
5232
|
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
|
|
5038
5233
|
`if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
|
|
5039
5234
|
` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
|
|
5040
|
-
` exit
|
|
5235
|
+
` exit 3`,
|
|
5041
5236
|
`fi`,
|
|
5042
5237
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5043
5238
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
@@ -5046,7 +5241,16 @@ function cleanupLegacySystemInstall() {
|
|
|
5046
5241
|
"exit 0",
|
|
5047
5242
|
""
|
|
5048
5243
|
].join("\n");
|
|
5049
|
-
|
|
5244
|
+
}
|
|
5245
|
+
function cleanupLegacySystemInstall() {
|
|
5246
|
+
assertServiceLabelSafe();
|
|
5247
|
+
runSudoScript(buildLegacyCleanupScript(), {
|
|
5248
|
+
action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
|
|
5249
|
+
file: "legacy-cleanup.sh",
|
|
5250
|
+
// 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
|
|
5251
|
+
// 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
|
|
5252
|
+
codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
|
|
5253
|
+
});
|
|
5050
5254
|
}
|
|
5051
5255
|
function cleanupLegacyInstallOrThrow() {
|
|
5052
5256
|
try {
|
|
@@ -5098,11 +5302,16 @@ async function tryHotReload() {
|
|
|
5098
5302
|
clearTimeout(timer);
|
|
5099
5303
|
}
|
|
5100
5304
|
}
|
|
5305
|
+
function concludeHotReload(stopEpochBefore, stopEpochNow) {
|
|
5306
|
+
return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
|
|
5307
|
+
}
|
|
5101
5308
|
async function restartService(stopEpochBefore) {
|
|
5102
5309
|
if (!isServiceInstalled()) {
|
|
5103
5310
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5104
5311
|
}
|
|
5105
|
-
if (!logOversized() && await tryHotReload())
|
|
5312
|
+
if (!logOversized() && await tryHotReload()) {
|
|
5313
|
+
return concludeHotReload(stopEpochBefore, readStopEpoch());
|
|
5314
|
+
}
|
|
5106
5315
|
if (logOversized()) {
|
|
5107
5316
|
const archiveFile = allocateArchivePath();
|
|
5108
5317
|
try {
|
|
@@ -5212,7 +5421,7 @@ function printVersion() {
|
|
|
5212
5421
|
}
|
|
5213
5422
|
|
|
5214
5423
|
// src/commands/completion.ts
|
|
5215
|
-
import
|
|
5424
|
+
import fs12 from "fs";
|
|
5216
5425
|
import os3 from "os";
|
|
5217
5426
|
import path9 from "path";
|
|
5218
5427
|
|
|
@@ -5259,7 +5468,7 @@ function viewLogWithTail(logPath, options) {
|
|
|
5259
5468
|
tailArgs.push(logPath);
|
|
5260
5469
|
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5261
5470
|
if (follow) setSilentSigint(true);
|
|
5262
|
-
tail.on("close", (code
|
|
5471
|
+
tail.on("close", (code) => process.exit(code ?? 0));
|
|
5263
5472
|
tail.on("error", (e) => {
|
|
5264
5473
|
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5265
5474
|
process.exit(1);
|
|
@@ -5396,8 +5605,12 @@ function getRunningState(serviceStatus) {
|
|
|
5396
5605
|
}
|
|
5397
5606
|
return { running: false, pid: null, kind: null, processInfo: null };
|
|
5398
5607
|
}
|
|
5399
|
-
function
|
|
5400
|
-
return
|
|
5608
|
+
function restartModeFor(state, fallbackMode) {
|
|
5609
|
+
return state.kind === "tun" ? "tun" : fallbackMode;
|
|
5610
|
+
}
|
|
5611
|
+
function restartModeOnChange() {
|
|
5612
|
+
const state = getRunningState();
|
|
5613
|
+
return state.running ? restartModeFor(state, getRuntimeMode()) : null;
|
|
5401
5614
|
}
|
|
5402
5615
|
async function launchOrRestart(mode, stopEpochBefore) {
|
|
5403
5616
|
if (mode === "tun") {
|
|
@@ -5451,6 +5664,22 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
5451
5664
|
// src/http.ts
|
|
5452
5665
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5453
5666
|
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5667
|
+
function isHttpsUrl(url) {
|
|
5668
|
+
try {
|
|
5669
|
+
return new URL(url).protocol === "https:";
|
|
5670
|
+
} catch {
|
|
5671
|
+
return false;
|
|
5672
|
+
}
|
|
5673
|
+
}
|
|
5674
|
+
function createHttpError(status, bodyText) {
|
|
5675
|
+
const error = new Error(`HTTP ${status}`);
|
|
5676
|
+
error.response = { status };
|
|
5677
|
+
try {
|
|
5678
|
+
error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
|
|
5679
|
+
} catch {
|
|
5680
|
+
}
|
|
5681
|
+
return error;
|
|
5682
|
+
}
|
|
5454
5683
|
function createHttpClient(options = {}) {
|
|
5455
5684
|
const { timeout = 6e4 } = options;
|
|
5456
5685
|
return {
|
|
@@ -5463,18 +5692,16 @@ function createHttpClient(options = {}) {
|
|
|
5463
5692
|
signal,
|
|
5464
5693
|
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5465
5694
|
});
|
|
5466
|
-
if (url
|
|
5695
|
+
if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
|
|
5467
5696
|
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5468
5697
|
}
|
|
5469
5698
|
if (!response.ok) {
|
|
5470
|
-
|
|
5471
|
-
error.response = { status: response.status };
|
|
5699
|
+
let text2 = "";
|
|
5472
5700
|
try {
|
|
5473
|
-
|
|
5474
|
-
error.response.data = JSON.parse(text2);
|
|
5701
|
+
text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
|
|
5475
5702
|
} catch {
|
|
5476
5703
|
}
|
|
5477
|
-
throw
|
|
5704
|
+
throw createHttpError(response.status, text2);
|
|
5478
5705
|
}
|
|
5479
5706
|
const declaredLen = Number(response.headers.get("content-length"));
|
|
5480
5707
|
if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
|
|
@@ -5726,7 +5953,7 @@ async function prepareConfigForStart(mode, subName = "default") {
|
|
|
5726
5953
|
}
|
|
5727
5954
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5728
5955
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5729
|
-
await validateConfigWithKernel(buildResult.config);
|
|
5956
|
+
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
5730
5957
|
const proxies = buildResult.config.proxies;
|
|
5731
5958
|
const proxyGroups = buildResult.config["proxy-groups"];
|
|
5732
5959
|
return {
|
|
@@ -5919,6 +6146,7 @@ function buildStatusJson(args) {
|
|
|
5919
6146
|
}
|
|
5920
6147
|
async function printStatus(args = []) {
|
|
5921
6148
|
assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
|
|
6149
|
+
assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
|
|
5922
6150
|
const asJson = hasFlag(args, "-j", "--json");
|
|
5923
6151
|
const skipProbe = hasFlag(args, "--no-probe");
|
|
5924
6152
|
const service = getServiceStatus();
|
|
@@ -6067,6 +6295,7 @@ function resolveStartMode(args) {
|
|
|
6067
6295
|
}
|
|
6068
6296
|
async function cmdStart(args) {
|
|
6069
6297
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
6298
|
+
assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
|
|
6070
6299
|
const targetMode = resolveStartMode(args);
|
|
6071
6300
|
if (!hasKernel()) {
|
|
6072
6301
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
@@ -6134,7 +6363,23 @@ async function cmdStart(args) {
|
|
|
6134
6363
|
}
|
|
6135
6364
|
|
|
6136
6365
|
// src/commands/shared.ts
|
|
6366
|
+
var validatedTables = /* @__PURE__ */ new WeakSet();
|
|
6367
|
+
function assertUniqueTokens(table) {
|
|
6368
|
+
if (validatedTables.has(table)) return;
|
|
6369
|
+
const owner = /* @__PURE__ */ new Map();
|
|
6370
|
+
for (const cmd of table) {
|
|
6371
|
+
for (const token of [cmd.name, ...cmd.aliases ?? []]) {
|
|
6372
|
+
const prev = owner.get(token);
|
|
6373
|
+
if (prev !== void 0) {
|
|
6374
|
+
throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
|
|
6375
|
+
}
|
|
6376
|
+
owner.set(token, cmd.name);
|
|
6377
|
+
}
|
|
6378
|
+
}
|
|
6379
|
+
validatedTables.add(table);
|
|
6380
|
+
}
|
|
6137
6381
|
async function dispatchSubcommand(args, table, options) {
|
|
6382
|
+
assertUniqueTokens(table);
|
|
6138
6383
|
const action = args[1];
|
|
6139
6384
|
if (action) {
|
|
6140
6385
|
const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
|
|
@@ -6161,8 +6406,8 @@ async function confirmOrThrow(question, opts) {
|
|
|
6161
6406
|
return confirmPrompt(question);
|
|
6162
6407
|
}
|
|
6163
6408
|
async function restartToApply(args) {
|
|
6164
|
-
|
|
6165
|
-
|
|
6409
|
+
const currentMode = restartModeOnChange();
|
|
6410
|
+
if (!currentMode) return false;
|
|
6166
6411
|
console.log("");
|
|
6167
6412
|
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
6168
6413
|
return true;
|
|
@@ -6170,6 +6415,7 @@ async function restartToApply(args) {
|
|
|
6170
6415
|
|
|
6171
6416
|
// src/commands/directory.ts
|
|
6172
6417
|
function openDirectory(args) {
|
|
6418
|
+
assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
|
|
6173
6419
|
const target = args[2];
|
|
6174
6420
|
if (!target || target === "root") {
|
|
6175
6421
|
console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
|
|
@@ -6256,6 +6502,7 @@ function printOverwriteList() {
|
|
|
6256
6502
|
console.log("");
|
|
6257
6503
|
}
|
|
6258
6504
|
async function setOverwrite(enabled, args) {
|
|
6505
|
+
assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
|
|
6259
6506
|
if (isOverwriteEnabled() === enabled) {
|
|
6260
6507
|
console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
|
|
6261
6508
|
console.log("");
|
|
@@ -6290,94 +6537,331 @@ async function cmdOverwrite(args) {
|
|
|
6290
6537
|
});
|
|
6291
6538
|
}
|
|
6292
6539
|
|
|
6293
|
-
// src/commands/
|
|
6540
|
+
// src/commands/reset.ts
|
|
6541
|
+
import fs11 from "fs";
|
|
6542
|
+
|
|
6543
|
+
// src/process-stop.ts
|
|
6294
6544
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6545
|
+
import fs10 from "fs";
|
|
6546
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6547
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
6548
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
6549
|
+
function clearRuntime() {
|
|
6550
|
+
if (fs10.existsSync(DIRS.runtime)) {
|
|
6551
|
+
rmrf(DIRS.runtime);
|
|
6299
6552
|
}
|
|
6553
|
+
ensureDirs();
|
|
6300
6554
|
}
|
|
6301
|
-
function
|
|
6302
|
-
|
|
6303
|
-
if (
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
console.log("");
|
|
6308
|
-
return;
|
|
6309
|
-
}
|
|
6310
|
-
const activeSub = getActiveSubscription();
|
|
6311
|
-
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6312
|
-
subs.forEach((s, i) => {
|
|
6313
|
-
const rel = formatRelativeTime(s.updated_at);
|
|
6314
|
-
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6315
|
-
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6316
|
-
const interval = resolveUpdateInterval(s.update_interval);
|
|
6317
|
-
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6318
|
-
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6319
|
-
if (s.username) {
|
|
6320
|
-
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6321
|
-
}
|
|
6322
|
-
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6323
|
-
if (traffic) {
|
|
6324
|
-
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6325
|
-
}
|
|
6326
|
-
if (s.expire !== void 0) {
|
|
6327
|
-
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6555
|
+
function clearPid() {
|
|
6556
|
+
if (!fs10.existsSync(PATHS.pidFile)) return;
|
|
6557
|
+
if (isPidFileOwnedByRoot()) {
|
|
6558
|
+
try {
|
|
6559
|
+
spawnSync5("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
6560
|
+
} catch {
|
|
6328
6561
|
}
|
|
6329
|
-
|
|
6330
|
-
|
|
6562
|
+
} else {
|
|
6563
|
+
try {
|
|
6564
|
+
fs10.unlinkSync(PATHS.pidFile);
|
|
6565
|
+
} catch {
|
|
6331
6566
|
}
|
|
6332
|
-
}
|
|
6333
|
-
console.log("");
|
|
6334
|
-
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6335
|
-
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6336
|
-
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6337
|
-
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6338
|
-
console.log("");
|
|
6567
|
+
}
|
|
6339
6568
|
}
|
|
6340
|
-
function
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
|
|
6569
|
+
function killProcess(pid) {
|
|
6570
|
+
try {
|
|
6571
|
+
process.kill(pid, "SIGKILL");
|
|
6572
|
+
return true;
|
|
6573
|
+
} catch {
|
|
6574
|
+
return false;
|
|
6346
6575
|
}
|
|
6347
6576
|
}
|
|
6348
|
-
function
|
|
6349
|
-
|
|
6577
|
+
function killAllMihomo(forceSudo = false) {
|
|
6578
|
+
const pattern = MAIN_INSTANCE_PATTERN;
|
|
6579
|
+
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
6580
|
+
const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
|
|
6350
6581
|
try {
|
|
6351
|
-
const
|
|
6352
|
-
if (
|
|
6353
|
-
|
|
6354
|
-
return isValidHttpUrl(text) ? text : null;
|
|
6582
|
+
const result = spawnSync5(argv[0], argv[1], options);
|
|
6583
|
+
if (result.error) return false;
|
|
6584
|
+
return result.status === 0 || result.status === 1;
|
|
6355
6585
|
} catch {
|
|
6356
|
-
return
|
|
6586
|
+
return false;
|
|
6357
6587
|
}
|
|
6358
6588
|
}
|
|
6359
|
-
async function
|
|
6360
|
-
|
|
6361
|
-
|
|
6362
|
-
|
|
6363
|
-
|
|
6364
|
-
|
|
6365
|
-
|
|
6366
|
-
|
|
6367
|
-
|
|
6368
|
-
|
|
6369
|
-
|
|
6589
|
+
async function cleanupAll(forceSudo = false) {
|
|
6590
|
+
const pids = getMihomoPids();
|
|
6591
|
+
if (pids.length === 0) {
|
|
6592
|
+
clearPid();
|
|
6593
|
+
return { killed: 0, failed: 0, remaining: [] };
|
|
6594
|
+
}
|
|
6595
|
+
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
6596
|
+
const needsSudo = forceSudo || hasRootProcess;
|
|
6597
|
+
let killedCount = 0;
|
|
6598
|
+
const failedPids = [];
|
|
6599
|
+
if (needsSudo) {
|
|
6600
|
+
const success = killAllMihomo(true);
|
|
6601
|
+
if (success) {
|
|
6602
|
+
killedCount = pids.length;
|
|
6603
|
+
} else {
|
|
6604
|
+
failedPids.push(...pids);
|
|
6605
|
+
}
|
|
6606
|
+
} else {
|
|
6607
|
+
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
6608
|
+
if (killAllMihomo(false)) {
|
|
6609
|
+
killedCount = pids.length;
|
|
6610
|
+
} else {
|
|
6611
|
+
failedPids.push(...pids);
|
|
6370
6612
|
}
|
|
6371
|
-
url = clipped;
|
|
6372
|
-
} else if (process.stdin.isTTY) {
|
|
6373
|
-
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6374
|
-
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6375
|
-
});
|
|
6376
6613
|
} else {
|
|
6377
|
-
|
|
6614
|
+
for (const pid of pids) {
|
|
6615
|
+
if (killProcess(pid)) {
|
|
6616
|
+
killedCount++;
|
|
6617
|
+
} else {
|
|
6618
|
+
failedPids.push(pid);
|
|
6619
|
+
}
|
|
6620
|
+
}
|
|
6378
6621
|
}
|
|
6379
6622
|
}
|
|
6380
|
-
|
|
6623
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6624
|
+
if (getMihomoPids().length === 0) break;
|
|
6625
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
6626
|
+
}
|
|
6627
|
+
clearPid();
|
|
6628
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
6629
|
+
}
|
|
6630
|
+
async function stop(forceSudo = false) {
|
|
6631
|
+
const allPids = getMihomoPids();
|
|
6632
|
+
if (allPids.length === 0) {
|
|
6633
|
+
clearPid();
|
|
6634
|
+
clearRuntime();
|
|
6635
|
+
return { success: true, notRunning: true };
|
|
6636
|
+
}
|
|
6637
|
+
const result = await cleanupAll(forceSudo);
|
|
6638
|
+
const remaining = getMihomoPids();
|
|
6639
|
+
if (remaining.length > 0) {
|
|
6640
|
+
console.log("");
|
|
6641
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
6642
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
6643
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
6644
|
+
console.log("");
|
|
6645
|
+
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
6646
|
+
}
|
|
6647
|
+
clearRuntime();
|
|
6648
|
+
return { success: true, killed: result.killed };
|
|
6649
|
+
}
|
|
6650
|
+
|
|
6651
|
+
// src/commands/reset.ts
|
|
6652
|
+
var RESET_TARGETS = [
|
|
6653
|
+
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
6654
|
+
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
6655
|
+
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
6656
|
+
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
6657
|
+
{
|
|
6658
|
+
id: "overwrites",
|
|
6659
|
+
aliases: ["overwrite", "overwrites", "ow"],
|
|
6660
|
+
label: "\u8986\u5199",
|
|
6661
|
+
needsStop: false,
|
|
6662
|
+
preserveOnBare: true,
|
|
6663
|
+
paths: () => fs11.existsSync(USER_DATA_DIR) ? fs11.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
6664
|
+
},
|
|
6665
|
+
{
|
|
6666
|
+
id: "settings",
|
|
6667
|
+
aliases: ["setting", "settings", "config"],
|
|
6668
|
+
label: "\u8BBE\u7F6E",
|
|
6669
|
+
needsStop: false,
|
|
6670
|
+
preserveOnBare: true,
|
|
6671
|
+
// 损坏备份也包含订阅凭据,需要一起删除
|
|
6672
|
+
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
6673
|
+
},
|
|
6674
|
+
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
6675
|
+
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
6676
|
+
];
|
|
6677
|
+
function resolveResetTargets(names) {
|
|
6678
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6679
|
+
for (const name of names) {
|
|
6680
|
+
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
6681
|
+
if (!target) {
|
|
6682
|
+
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
6683
|
+
}
|
|
6684
|
+
matched.add(target);
|
|
6685
|
+
}
|
|
6686
|
+
return [...matched];
|
|
6687
|
+
}
|
|
6688
|
+
async function cmdReset(args) {
|
|
6689
|
+
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
6690
|
+
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
6691
|
+
const namedTargets = resolveResetTargets(names);
|
|
6692
|
+
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
6693
|
+
const ids = new Set(targets.map((t) => t.id));
|
|
6694
|
+
const needsStop = targets.some((t) => t.needsStop);
|
|
6695
|
+
const serviceTargeted = ids.has("service");
|
|
6696
|
+
const service = getServiceStatus();
|
|
6697
|
+
const serviceActive = service.installed || service.loaded;
|
|
6698
|
+
const legacy = detectLegacySystemInstall();
|
|
6699
|
+
if (targets.length === 1) {
|
|
6700
|
+
if (serviceTargeted && !serviceActive && !legacy) {
|
|
6701
|
+
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
6702
|
+
return;
|
|
6703
|
+
}
|
|
6704
|
+
}
|
|
6705
|
+
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
6706
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
|
|
6707
|
+
}
|
|
6708
|
+
if (serviceTargeted && serviceActive) {
|
|
6709
|
+
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
6710
|
+
} else if (needsStop && serviceActive) {
|
|
6711
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
6712
|
+
}
|
|
6713
|
+
if ((needsStop || serviceTargeted) && legacy) {
|
|
6714
|
+
console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
6715
|
+
}
|
|
6716
|
+
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
6717
|
+
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
6718
|
+
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
6719
|
+
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
6720
|
+
})) {
|
|
6721
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6722
|
+
return;
|
|
6723
|
+
}
|
|
6724
|
+
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
6725
|
+
if (serviceActive) {
|
|
6726
|
+
if (serviceTargeted) await uninstallService();
|
|
6727
|
+
else if (needsStop) await stopService();
|
|
6728
|
+
}
|
|
6729
|
+
if (needsStop) {
|
|
6730
|
+
const cleanup = await cleanupAll();
|
|
6731
|
+
if (cleanup.remaining.length > 0) {
|
|
6732
|
+
throw new CliError(cleanup.remaining.join(", "), {
|
|
6733
|
+
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
6734
|
+
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
6735
|
+
});
|
|
6736
|
+
}
|
|
6737
|
+
recordServiceStopped();
|
|
6738
|
+
}
|
|
6739
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
6740
|
+
for (const target of targets) {
|
|
6741
|
+
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
6742
|
+
for (const filePath of target.paths()) {
|
|
6743
|
+
if (!fs11.existsSync(filePath)) continue;
|
|
6744
|
+
try {
|
|
6745
|
+
rmrf(filePath);
|
|
6746
|
+
} catch (e) {
|
|
6747
|
+
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
6748
|
+
}
|
|
6749
|
+
hadContent = true;
|
|
6750
|
+
}
|
|
6751
|
+
if (hadContent) deleted.add(target.id);
|
|
6752
|
+
}
|
|
6753
|
+
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
6754
|
+
updateSettings((settings) => {
|
|
6755
|
+
const patch = {};
|
|
6756
|
+
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
6757
|
+
patch.subscriptions = void 0;
|
|
6758
|
+
patch.active_subscription = void 0;
|
|
6759
|
+
deleted.add("subs");
|
|
6760
|
+
}
|
|
6761
|
+
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
6762
|
+
patch.overwrite_enabled = void 0;
|
|
6763
|
+
deleted.add("overwrites");
|
|
6764
|
+
}
|
|
6765
|
+
return patch;
|
|
6766
|
+
});
|
|
6767
|
+
}
|
|
6768
|
+
if (ids.has("kernel")) clearKernelVersionCache();
|
|
6769
|
+
ensureDirs();
|
|
6770
|
+
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
6771
|
+
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
6772
|
+
}
|
|
6773
|
+
|
|
6774
|
+
// src/commands/subscription.ts
|
|
6775
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6776
|
+
function printRestartHintIfRunning() {
|
|
6777
|
+
const state = getRunningState();
|
|
6778
|
+
if (state.running) {
|
|
6779
|
+
const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
|
|
6780
|
+
console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`));
|
|
6781
|
+
console.log("");
|
|
6782
|
+
}
|
|
6783
|
+
}
|
|
6784
|
+
function printSubscriptionList() {
|
|
6785
|
+
const subs = getSubscriptionsWithCache();
|
|
6786
|
+
if (subs.length === 0) {
|
|
6787
|
+
console.log("\u6CA1\u6709\u8BA2\u9605");
|
|
6788
|
+
console.log("");
|
|
6789
|
+
console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6790
|
+
console.log("");
|
|
6791
|
+
return;
|
|
6792
|
+
}
|
|
6793
|
+
const activeSub = getActiveSubscription();
|
|
6794
|
+
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6795
|
+
subs.forEach((s, i) => {
|
|
6796
|
+
const rel = formatRelativeTime(s.updated_at);
|
|
6797
|
+
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6798
|
+
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6799
|
+
const interval = resolveUpdateInterval(s.update_interval);
|
|
6800
|
+
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6801
|
+
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6802
|
+
if (s.username) {
|
|
6803
|
+
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6804
|
+
}
|
|
6805
|
+
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6806
|
+
if (traffic) {
|
|
6807
|
+
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6808
|
+
}
|
|
6809
|
+
if (s.expire !== void 0) {
|
|
6810
|
+
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6811
|
+
}
|
|
6812
|
+
if (s.web_page_url) {
|
|
6813
|
+
console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
|
|
6814
|
+
}
|
|
6815
|
+
});
|
|
6816
|
+
console.log("");
|
|
6817
|
+
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6818
|
+
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6819
|
+
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6820
|
+
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6821
|
+
console.log("");
|
|
6822
|
+
}
|
|
6823
|
+
function assertNotFlagLike(name, usage) {
|
|
6824
|
+
if (name.startsWith("-")) {
|
|
6825
|
+
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
6826
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6827
|
+
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
6828
|
+
});
|
|
6829
|
+
}
|
|
6830
|
+
}
|
|
6831
|
+
function readUrlFromClipboard() {
|
|
6832
|
+
if (!process.stdin.isTTY) return null;
|
|
6833
|
+
try {
|
|
6834
|
+
const r = spawnSync6("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
6835
|
+
if (r.status !== 0) return null;
|
|
6836
|
+
const text = (r.stdout || "").trim();
|
|
6837
|
+
return isValidHttpUrl(text) ? text : null;
|
|
6838
|
+
} catch {
|
|
6839
|
+
return null;
|
|
6840
|
+
}
|
|
6841
|
+
}
|
|
6842
|
+
async function subAdd(args) {
|
|
6843
|
+
assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
|
|
6844
|
+
let url = args[2]?.trim();
|
|
6845
|
+
const name = args[3] || "default";
|
|
6846
|
+
if (!url) {
|
|
6847
|
+
const clipped = readUrlFromClipboard();
|
|
6848
|
+
if (clipped) {
|
|
6849
|
+
console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
|
|
6850
|
+
console.log(` ${maskUrl(clipped)}`);
|
|
6851
|
+
if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
|
|
6852
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6853
|
+
return;
|
|
6854
|
+
}
|
|
6855
|
+
url = clipped;
|
|
6856
|
+
} else if (process.stdin.isTTY) {
|
|
6857
|
+
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6858
|
+
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6859
|
+
});
|
|
6860
|
+
} else {
|
|
6861
|
+
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
|
|
6862
|
+
}
|
|
6863
|
+
}
|
|
6864
|
+
if (!isValidHttpUrl(url)) {
|
|
6381
6865
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
6382
6866
|
}
|
|
6383
6867
|
assertNotFlagLike(name, "mihomo sub add <url> [name]");
|
|
@@ -6397,6 +6881,7 @@ async function subAdd(args) {
|
|
|
6397
6881
|
printSubscriptionList();
|
|
6398
6882
|
}
|
|
6399
6883
|
async function subUpdate(args) {
|
|
6884
|
+
assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
|
|
6400
6885
|
const name = getNonFlagArg(args, 2);
|
|
6401
6886
|
const subs = getSubscriptions();
|
|
6402
6887
|
if (subs.length === 0) {
|
|
@@ -6428,6 +6913,7 @@ async function subUpdate(args) {
|
|
|
6428
6913
|
printSubscriptionList();
|
|
6429
6914
|
}
|
|
6430
6915
|
async function subUse(args) {
|
|
6916
|
+
assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
|
|
6431
6917
|
const name = getNonFlagArg(args, 2);
|
|
6432
6918
|
const subs = getSubscriptions();
|
|
6433
6919
|
if (subs.length === 0) {
|
|
@@ -6457,6 +6943,7 @@ async function subUse(args) {
|
|
|
6457
6943
|
printSubscriptionList();
|
|
6458
6944
|
}
|
|
6459
6945
|
async function subRemove(args) {
|
|
6946
|
+
assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
|
|
6460
6947
|
const name = getNonFlagArg(args, 2);
|
|
6461
6948
|
const subs = getSubscriptions();
|
|
6462
6949
|
if (!name) {
|
|
@@ -6485,18 +6972,31 @@ async function subRemove(args) {
|
|
|
6485
6972
|
console.log("");
|
|
6486
6973
|
printSubscriptionList();
|
|
6487
6974
|
}
|
|
6975
|
+
var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
|
|
6976
|
+
var REMOVE_FLAGS = ["-y", "--yes"];
|
|
6977
|
+
function withKnownFlags(usage, known, handler) {
|
|
6978
|
+
return async (args) => {
|
|
6979
|
+
assertKnownFlags(args, known, usage);
|
|
6980
|
+
await handler(args);
|
|
6981
|
+
};
|
|
6982
|
+
}
|
|
6488
6983
|
var SUBCOMMANDS3 = [
|
|
6489
|
-
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: subAdd },
|
|
6490
|
-
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: subUpdate },
|
|
6491
|
-
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: subUse },
|
|
6492
|
-
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
|
|
6984
|
+
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
|
|
6985
|
+
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: withKnownFlags("sub update [name]", [], subUpdate) },
|
|
6986
|
+
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
|
|
6987
|
+
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
|
|
6493
6988
|
];
|
|
6494
6989
|
async function cmdSubscription(args) {
|
|
6495
|
-
assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
|
|
6496
6990
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6497
6991
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6498
6992
|
fallback: printSubscriptionList,
|
|
6499
6993
|
onUnknown: (action) => {
|
|
6994
|
+
if (action.startsWith("-")) {
|
|
6995
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
|
|
6996
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6997
|
+
hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
6998
|
+
});
|
|
6999
|
+
}
|
|
6500
7000
|
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6501
7001
|
const suggestion = suggestSimilar(action, names);
|
|
6502
7002
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
@@ -6523,8 +7023,10 @@ function subGroups(commands) {
|
|
|
6523
7023
|
};
|
|
6524
7024
|
return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
|
|
6525
7025
|
}
|
|
6526
|
-
var DIR_TARGETS =
|
|
6527
|
-
var UI_NAMES =
|
|
7026
|
+
var DIR_TARGETS = Object.keys(DIRECTORY_TARGETS);
|
|
7027
|
+
var UI_NAMES = Object.keys(UI_URLS);
|
|
7028
|
+
var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
|
|
7029
|
+
var RESET_TARGET_NAMES = RESET_TARGETS.map((t) => t.id);
|
|
6528
7030
|
var SHELLS = ["zsh", "bash", "fish"];
|
|
6529
7031
|
function buildZsh(commands, groups) {
|
|
6530
7032
|
const lines = [
|
|
@@ -6578,10 +7080,10 @@ function buildZsh(commands, groups) {
|
|
|
6578
7080
|
` _values 'ui' ${UI_NAMES.join(" ")}`,
|
|
6579
7081
|
" ;;",
|
|
6580
7082
|
" kernel)",
|
|
6581
|
-
|
|
7083
|
+
` _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(${MIRROR_NAMES.join(" ")})'`,
|
|
6582
7084
|
" ;;",
|
|
6583
7085
|
" reset)",
|
|
6584
|
-
` _values 'target'
|
|
7086
|
+
` _values 'target' ${RESET_TARGET_NAMES.join(" ")}`,
|
|
6585
7087
|
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
6586
7088
|
" ;;",
|
|
6587
7089
|
" completion)",
|
|
@@ -6645,10 +7147,14 @@ ${subCase}
|
|
|
6645
7147
|
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
6646
7148
|
;;
|
|
6647
7149
|
kernel)
|
|
6648
|
-
|
|
7150
|
+
if [[ "\${prev}" == "--mirror" ]]; then
|
|
7151
|
+
COMPREPLY=( $(compgen -W "${MIRROR_NAMES.join(" ")}" -- "\${cur}") )
|
|
7152
|
+
else
|
|
7153
|
+
COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
|
|
7154
|
+
fi
|
|
6649
7155
|
;;
|
|
6650
7156
|
reset)
|
|
6651
|
-
COMPREPLY=( $(compgen -W "
|
|
7157
|
+
COMPREPLY=( $(compgen -W "${RESET_TARGET_NAMES.join(" ")} --full -y" -- "\${cur}") )
|
|
6652
7158
|
;;
|
|
6653
7159
|
completion)
|
|
6654
7160
|
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
@@ -6673,15 +7179,20 @@ function buildFish(commands, groups) {
|
|
|
6673
7179
|
}
|
|
6674
7180
|
for (const group of groups) {
|
|
6675
7181
|
const seen = group.tokens.join(" ");
|
|
7182
|
+
const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
|
|
6676
7183
|
for (const s of group.words) {
|
|
6677
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${
|
|
7184
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
|
|
6678
7185
|
}
|
|
6679
7186
|
}
|
|
6680
|
-
lines.push(
|
|
6681
|
-
|
|
7187
|
+
lines.push(
|
|
7188
|
+
` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
|
|
7189
|
+
);
|
|
7190
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
|
|
6682
7191
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
|
|
6683
7192
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
|
|
6684
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -
|
|
7193
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -l mirror -d '\u8D70\u955C\u50CF\u4E0B\u8F7D' -a '${MIRROR_NAMES.join(" ")}'`);
|
|
7194
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -a '${RESET_TARGET_NAMES.join(" ")}'`);
|
|
7195
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -s y -l full -d '\u8DF3\u8FC7\u786E\u8BA4 / \u5220\u5168\u90E8'`);
|
|
6685
7196
|
lines.push("end");
|
|
6686
7197
|
return lines.join("\n");
|
|
6687
7198
|
}
|
|
@@ -6730,21 +7241,21 @@ function installCompletion(shell, commands) {
|
|
|
6730
7241
|
console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
|
|
6731
7242
|
try {
|
|
6732
7243
|
if (shell === "bash") {
|
|
6733
|
-
const existing =
|
|
7244
|
+
const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
|
|
6734
7245
|
if (existing.includes(BASH_MARKER)) {
|
|
6735
7246
|
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6736
7247
|
return;
|
|
6737
7248
|
}
|
|
6738
|
-
|
|
6739
|
-
|
|
7249
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7250
|
+
fs12.appendFileSync(target, `
|
|
6740
7251
|
${BASH_MARKER}
|
|
6741
7252
|
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
6742
7253
|
`);
|
|
6743
7254
|
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6744
7255
|
return;
|
|
6745
7256
|
}
|
|
6746
|
-
|
|
6747
|
-
|
|
7257
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7258
|
+
fs12.writeFileSync(target, script, { mode: 420 });
|
|
6748
7259
|
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6749
7260
|
} catch (e) {
|
|
6750
7261
|
throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
|
|
@@ -6765,14 +7276,14 @@ function uninstallCompletion(shell, commands) {
|
|
|
6765
7276
|
buildCompletionScript(shell, commands);
|
|
6766
7277
|
return;
|
|
6767
7278
|
}
|
|
6768
|
-
if (!
|
|
7279
|
+
if (!fs12.existsSync(target)) {
|
|
6769
7280
|
console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
|
|
6770
7281
|
return;
|
|
6771
7282
|
}
|
|
6772
7283
|
console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
|
|
6773
7284
|
try {
|
|
6774
7285
|
if (shell === "bash") {
|
|
6775
|
-
const existing2 =
|
|
7286
|
+
const existing2 = fs12.readFileSync(target, "utf8");
|
|
6776
7287
|
const endMarker = BASH_MARKER.replace(">>>", "<<<");
|
|
6777
7288
|
const start = existing2.indexOf(BASH_MARKER);
|
|
6778
7289
|
const end = existing2.indexOf(endMarker);
|
|
@@ -6785,15 +7296,15 @@ function uninstallCompletion(shell, commands) {
|
|
|
6785
7296
|
const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
|
|
6786
7297
|
const rest = `${before}${after}`;
|
|
6787
7298
|
if (rest.trim() === "") {
|
|
6788
|
-
|
|
7299
|
+
fs12.rmSync(target);
|
|
6789
7300
|
console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6790
7301
|
return;
|
|
6791
7302
|
}
|
|
6792
|
-
|
|
7303
|
+
fs12.writeFileSync(target, rest);
|
|
6793
7304
|
console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6794
7305
|
return;
|
|
6795
7306
|
}
|
|
6796
|
-
const existing =
|
|
7307
|
+
const existing = fs12.readFileSync(target, "utf8");
|
|
6797
7308
|
const fingerprint = shell === "zsh" ? "#compdef mihomo" : "for cmd in mihomo";
|
|
6798
7309
|
if (!existing.includes(fingerprint)) {
|
|
6799
7310
|
throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
|
|
@@ -6801,7 +7312,7 @@ function uninstallCompletion(shell, commands) {
|
|
|
6801
7312
|
hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
|
|
6802
7313
|
});
|
|
6803
7314
|
}
|
|
6804
|
-
|
|
7315
|
+
fs12.rmSync(target);
|
|
6805
7316
|
console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6806
7317
|
} catch (e) {
|
|
6807
7318
|
if (e instanceof CliError) throw e;
|
|
@@ -6814,13 +7325,16 @@ function uninstallCompletion(shell, commands) {
|
|
|
6814
7325
|
function cmdCompletion(args, commands) {
|
|
6815
7326
|
assertKnownFlags(args.slice(1), [], "completion");
|
|
6816
7327
|
if (args[1] === "install") {
|
|
7328
|
+
assertPositionalCount(args, 1, 2, `mihomo completion install <${SHELLS.join("|")}>`);
|
|
6817
7329
|
installCompletion(args[2], commands);
|
|
6818
7330
|
return;
|
|
6819
7331
|
}
|
|
6820
7332
|
if (args[1] === "uninstall") {
|
|
7333
|
+
assertPositionalCount(args, 1, 2, `mihomo completion uninstall <${SHELLS.join("|")}>`);
|
|
6821
7334
|
uninstallCompletion(args[2], commands);
|
|
6822
7335
|
return;
|
|
6823
7336
|
}
|
|
7337
|
+
assertPositionalCount(args, 1, 1, `mihomo completion <${SHELLS.join("|")}>`);
|
|
6824
7338
|
const shell = args[1];
|
|
6825
7339
|
if (!shell) {
|
|
6826
7340
|
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
@@ -6838,6 +7352,7 @@ function cmdCompletion(args, commands) {
|
|
|
6838
7352
|
// src/commands/config.ts
|
|
6839
7353
|
function cmdConfig(args = []) {
|
|
6840
7354
|
assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
|
|
7355
|
+
assertPositionalCount(args, 0, 1, "mihomo config [--json]");
|
|
6841
7356
|
const asJson = hasFlag(args, "-j", "--json");
|
|
6842
7357
|
const active = getActiveSubscription();
|
|
6843
7358
|
if (!active) {
|
|
@@ -6852,7 +7367,7 @@ function cmdConfig(args = []) {
|
|
|
6852
7367
|
const shown = { ...config };
|
|
6853
7368
|
if (typeof shown.secret === "string" && shown.secret) shown.secret = "***";
|
|
6854
7369
|
if (asJson) {
|
|
6855
|
-
console.log(JSON.stringify(shown, null, 2));
|
|
7370
|
+
console.log(JSON.stringify({ ...shown, warnings }, null, 2));
|
|
6856
7371
|
return;
|
|
6857
7372
|
}
|
|
6858
7373
|
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
@@ -6869,8 +7384,8 @@ function cmdConfig(args = []) {
|
|
|
6869
7384
|
}
|
|
6870
7385
|
|
|
6871
7386
|
// src/commands/doctor.ts
|
|
6872
|
-
import { spawnSync as
|
|
6873
|
-
import
|
|
7387
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7388
|
+
import fs13 from "fs";
|
|
6874
7389
|
|
|
6875
7390
|
// src/commands/update.ts
|
|
6876
7391
|
import { execFile as execFile3, spawn as spawn2 } from "child_process";
|
|
@@ -6888,6 +7403,7 @@ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
|
6888
7403
|
}
|
|
6889
7404
|
async function cmdUpdate(args = []) {
|
|
6890
7405
|
assertKnownFlags(args.slice(1), [], "update");
|
|
7406
|
+
assertPositionalCount(args, 0, 1, "mihomo update");
|
|
6891
7407
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6892
7408
|
console.log("");
|
|
6893
7409
|
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
@@ -6945,7 +7461,7 @@ async function cmdUpdate(args = []) {
|
|
|
6945
7461
|
// src/commands/doctor.ts
|
|
6946
7462
|
function isPortListening(port) {
|
|
6947
7463
|
try {
|
|
6948
|
-
const r =
|
|
7464
|
+
const r = spawnSync7("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
6949
7465
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
6950
7466
|
} catch {
|
|
6951
7467
|
return false;
|
|
@@ -6953,14 +7469,14 @@ function isPortListening(port) {
|
|
|
6953
7469
|
}
|
|
6954
7470
|
async function collectChecks() {
|
|
6955
7471
|
const checks = [];
|
|
6956
|
-
const push = (name, status, detail, fix) => {
|
|
6957
|
-
checks.push({ name, status, detail, fix });
|
|
7472
|
+
const push = (name, status, detail, fix, notes) => {
|
|
7473
|
+
checks.push({ name, status, detail, fix, notes });
|
|
6958
7474
|
};
|
|
6959
7475
|
if (!hasKernel()) {
|
|
6960
7476
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
6961
7477
|
} else {
|
|
6962
7478
|
const v = getKernelVersion();
|
|
6963
|
-
const r =
|
|
7479
|
+
const r = spawnSync7(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6964
7480
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
6965
7481
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
6966
7482
|
} else if (r.error) {
|
|
@@ -6970,13 +7486,13 @@ async function collectChecks() {
|
|
|
6970
7486
|
}
|
|
6971
7487
|
}
|
|
6972
7488
|
try {
|
|
6973
|
-
|
|
7489
|
+
fs13.accessSync(USER_DATA_DIR, fs13.constants.W_OK);
|
|
6974
7490
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
6975
7491
|
} catch {
|
|
6976
7492
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
6977
7493
|
}
|
|
6978
|
-
if (
|
|
6979
|
-
if (isValidSettingsContent(
|
|
7494
|
+
if (fs13.existsSync(PATHS.settingsFile)) {
|
|
7495
|
+
if (isValidSettingsContent(fs13.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
6980
7496
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
6981
7497
|
} else {
|
|
6982
7498
|
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");
|
|
@@ -7053,10 +7569,22 @@ async function collectChecks() {
|
|
|
7053
7569
|
if (active && hasKernel()) {
|
|
7054
7570
|
try {
|
|
7055
7571
|
const mode = info?.tun ? "tun" : "mixed";
|
|
7056
|
-
await prepareConfigForStart(mode, active.name);
|
|
7057
|
-
|
|
7572
|
+
const prepared = await prepareConfigForStart(mode, active.name);
|
|
7573
|
+
const warnings = prepared.buildResult.warnings;
|
|
7574
|
+
if (warnings.length > 0) {
|
|
7575
|
+
push(
|
|
7576
|
+
"\u914D\u7F6E\u6784\u5EFA",
|
|
7577
|
+
"warn",
|
|
7578
|
+
`\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
|
|
7579
|
+
void 0,
|
|
7580
|
+
warnings.map((w) => ` ${w}`)
|
|
7581
|
+
);
|
|
7582
|
+
} else {
|
|
7583
|
+
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
|
|
7584
|
+
}
|
|
7058
7585
|
} catch (e) {
|
|
7059
|
-
|
|
7586
|
+
const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
|
|
7587
|
+
push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
|
|
7060
7588
|
}
|
|
7061
7589
|
} else {
|
|
7062
7590
|
push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
|
|
@@ -7083,13 +7611,15 @@ async function collectChecks() {
|
|
|
7083
7611
|
}
|
|
7084
7612
|
async function cmdDoctor(args = []) {
|
|
7085
7613
|
assertKnownFlags(args.slice(1), [], "doctor");
|
|
7614
|
+
assertPositionalCount(args, 0, 1, "mihomo doctor");
|
|
7086
7615
|
const checks = await collectChecks();
|
|
7087
7616
|
console.log("");
|
|
7088
7617
|
for (const c of checks) {
|
|
7089
7618
|
const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
|
|
7090
7619
|
console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
|
|
7091
|
-
if (c.status !== "ok" && c.status !== "skip"
|
|
7092
|
-
console.log(colors.gray(
|
|
7620
|
+
if (c.status !== "ok" && c.status !== "skip") {
|
|
7621
|
+
for (const line of c.notes ?? []) console.log(colors.gray(line));
|
|
7622
|
+
if (c.fix) console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
|
|
7093
7623
|
}
|
|
7094
7624
|
}
|
|
7095
7625
|
const ok = checks.filter((c) => c.status === "ok").length;
|
|
@@ -7108,13 +7638,15 @@ async function cmdDoctor(args = []) {
|
|
|
7108
7638
|
}
|
|
7109
7639
|
|
|
7110
7640
|
// src/kernel.ts
|
|
7111
|
-
import { spawnSync as
|
|
7112
|
-
import
|
|
7641
|
+
import { execFile as execFile4, spawnSync as spawnSync8 } from "child_process";
|
|
7642
|
+
import fs14 from "fs";
|
|
7113
7643
|
import path10 from "path";
|
|
7644
|
+
import { promisify as promisify4 } from "util";
|
|
7114
7645
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
7115
7646
|
var KERNEL_HTTP_TIMEOUT = 12e4;
|
|
7116
7647
|
var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
|
|
7117
7648
|
var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
|
|
7649
|
+
var execFileAsync3 = promisify4(execFile4);
|
|
7118
7650
|
function withMirror(url, mirror) {
|
|
7119
7651
|
if (mirror && url.startsWith("https://github.com/")) {
|
|
7120
7652
|
return mirror + url;
|
|
@@ -7146,7 +7678,7 @@ function resolveDownloadChannel(input) {
|
|
|
7146
7678
|
return { kind: "direct" };
|
|
7147
7679
|
}
|
|
7148
7680
|
function hasGh() {
|
|
7149
|
-
const result =
|
|
7681
|
+
const result = spawnSync8("gh", ["--version"], { stdio: "ignore" });
|
|
7150
7682
|
return !result.error && result.status === 0;
|
|
7151
7683
|
}
|
|
7152
7684
|
function getArch() {
|
|
@@ -7169,51 +7701,81 @@ function pickLatestRelease(releases) {
|
|
|
7169
7701
|
if (!Array.isArray(releases) || releases.length === 0) {
|
|
7170
7702
|
throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
|
|
7171
7703
|
}
|
|
7172
|
-
const stableReleases = releases.filter(
|
|
7173
|
-
(r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
|
|
7174
|
-
);
|
|
7175
|
-
if (stableReleases.length === 0) {
|
|
7176
|
-
throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
|
|
7704
|
+
const stableReleases = releases.filter(
|
|
7705
|
+
(r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
|
|
7706
|
+
);
|
|
7707
|
+
if (stableReleases.length === 0) {
|
|
7708
|
+
throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
|
|
7709
|
+
}
|
|
7710
|
+
return stableReleases[0];
|
|
7711
|
+
}
|
|
7712
|
+
function buildReleaseApiCurlArgs(proxyPort, url) {
|
|
7713
|
+
return [
|
|
7714
|
+
"-s",
|
|
7715
|
+
"-x",
|
|
7716
|
+
`http://127.0.0.1:${proxyPort}`,
|
|
7717
|
+
"--proto",
|
|
7718
|
+
"=https",
|
|
7719
|
+
"--proto-redir",
|
|
7720
|
+
"=https",
|
|
7721
|
+
"--fail-with-body",
|
|
7722
|
+
"-w",
|
|
7723
|
+
"\n%{http_code}",
|
|
7724
|
+
"--connect-timeout",
|
|
7725
|
+
"10",
|
|
7726
|
+
"--max-time",
|
|
7727
|
+
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7728
|
+
"-H",
|
|
7729
|
+
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7730
|
+
url
|
|
7731
|
+
];
|
|
7732
|
+
}
|
|
7733
|
+
function parseCurlStatusOutput(stdout) {
|
|
7734
|
+
const newlineIdx = stdout.lastIndexOf("\n");
|
|
7735
|
+
if (newlineIdx === -1) return { body: stdout, statusCode: null };
|
|
7736
|
+
const code = Number.parseInt(stdout.slice(newlineIdx + 1).trim(), 10);
|
|
7737
|
+
return { body: stdout.slice(0, newlineIdx), statusCode: Number.isFinite(code) && code > 0 ? code : null };
|
|
7738
|
+
}
|
|
7739
|
+
function translateReleaseApiCurlError(e) {
|
|
7740
|
+
const err = e;
|
|
7741
|
+
if (typeof err.code === "string") {
|
|
7742
|
+
if (err.code === "ENOENT") {
|
|
7743
|
+
return new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7744
|
+
}
|
|
7745
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${err.message ?? err.code}`);
|
|
7746
|
+
}
|
|
7747
|
+
const { body, statusCode } = parseCurlStatusOutput(typeof err.stdout === "string" ? err.stdout : "");
|
|
7748
|
+
if (statusCode !== null && statusCode >= 400) {
|
|
7749
|
+
return createHttpError(statusCode, body);
|
|
7177
7750
|
}
|
|
7178
|
-
|
|
7751
|
+
if (err.killed) {
|
|
7752
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: curl ${Math.floor((KERNEL_HTTP_TIMEOUT + 1e4) / 1e3)}s \u672A\u5B8C\u6210\uFF0C\u5DF2\u7EC8\u6B62${err.signal ? `\uFF08${err.signal}\uFF09` : ""}`);
|
|
7753
|
+
}
|
|
7754
|
+
const stderr = (err.stderr || "").trim();
|
|
7755
|
+
const lastLine = stderr ? stderr.split("\n").pop()?.replace(/^curl: \(\d+\)\s*/, "") : void 0;
|
|
7756
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7179
7757
|
}
|
|
7180
7758
|
async function getLatestRelease(repo, proxyPort) {
|
|
7181
7759
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7182
7760
|
if (proxyPort) {
|
|
7183
|
-
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
"
|
|
7187
|
-
|
|
7188
|
-
|
|
7189
|
-
|
|
7190
|
-
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
"--connect-timeout",
|
|
7194
|
-
"10",
|
|
7195
|
-
"--max-time",
|
|
7196
|
-
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7197
|
-
"-H",
|
|
7198
|
-
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7199
|
-
url
|
|
7200
|
-
],
|
|
7201
|
-
{ encoding: "utf8", maxBuffer: 50 * 1024 * 1024, timeout: KERNEL_HTTP_TIMEOUT + 1e4 }
|
|
7202
|
-
);
|
|
7203
|
-
if (result.error) {
|
|
7204
|
-
if (result.error.code === "ENOENT") {
|
|
7205
|
-
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7206
|
-
}
|
|
7207
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${result.error.message}`);
|
|
7761
|
+
let stdout;
|
|
7762
|
+
try {
|
|
7763
|
+
const result = await execFileAsync3("curl", buildReleaseApiCurlArgs(proxyPort, url), {
|
|
7764
|
+
encoding: "utf8",
|
|
7765
|
+
maxBuffer: 50 * 1024 * 1024,
|
|
7766
|
+
timeout: KERNEL_HTTP_TIMEOUT + 1e4
|
|
7767
|
+
});
|
|
7768
|
+
stdout = result.stdout;
|
|
7769
|
+
} catch (e) {
|
|
7770
|
+
throw translateReleaseApiCurlError(e);
|
|
7208
7771
|
}
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
|
|
7212
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${result.status}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7772
|
+
const { body, statusCode } = parseCurlStatusOutput(stdout);
|
|
7773
|
+
if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
|
|
7774
|
+
throw createHttpError(statusCode, body);
|
|
7213
7775
|
}
|
|
7214
7776
|
let releases;
|
|
7215
7777
|
try {
|
|
7216
|
-
releases = JSON.parse(
|
|
7778
|
+
releases = JSON.parse(body);
|
|
7217
7779
|
} catch {
|
|
7218
7780
|
throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
|
|
7219
7781
|
}
|
|
@@ -7247,10 +7809,10 @@ async function checkUpdate(proxyPort) {
|
|
|
7247
7809
|
}
|
|
7248
7810
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
7249
7811
|
if (maxDepth <= 0) return null;
|
|
7250
|
-
const files =
|
|
7812
|
+
const files = fs14.readdirSync(dir);
|
|
7251
7813
|
for (const f of files) {
|
|
7252
7814
|
const fullPath = path10.join(dir, f);
|
|
7253
|
-
const stat =
|
|
7815
|
+
const stat = fs14.lstatSync(fullPath);
|
|
7254
7816
|
if (stat.isDirectory()) {
|
|
7255
7817
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
7256
7818
|
if (found) return found;
|
|
@@ -7302,7 +7864,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7302
7864
|
}
|
|
7303
7865
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7304
7866
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7305
|
-
const tempDir =
|
|
7867
|
+
const tempDir = fs14.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
|
|
7306
7868
|
const tempPath = path10.join(tempDir, path10.basename(asset.name));
|
|
7307
7869
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7308
7870
|
try {
|
|
@@ -7316,7 +7878,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7316
7878
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
|
|
7317
7879
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7318
7880
|
}
|
|
7319
|
-
const ghResult =
|
|
7881
|
+
const ghResult = spawnSync8("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7320
7882
|
stdio: "inherit",
|
|
7321
7883
|
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7322
7884
|
});
|
|
@@ -7334,7 +7896,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7334
7896
|
}
|
|
7335
7897
|
} else {
|
|
7336
7898
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7337
|
-
const curlResult =
|
|
7899
|
+
const curlResult = spawnSync8(
|
|
7338
7900
|
"curl",
|
|
7339
7901
|
buildKernelCurlArgs({
|
|
7340
7902
|
url: downloadUrl,
|
|
@@ -7354,11 +7916,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7354
7916
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7355
7917
|
}
|
|
7356
7918
|
}
|
|
7357
|
-
if (!
|
|
7919
|
+
if (!fs14.existsSync(tempPath)) {
|
|
7358
7920
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7359
7921
|
}
|
|
7360
7922
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7361
|
-
const actual =
|
|
7923
|
+
const actual = fs14.statSync(tempPath).size;
|
|
7362
7924
|
if (actual !== asset.size) {
|
|
7363
7925
|
throw new Error(
|
|
7364
7926
|
`\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
|
|
@@ -7371,7 +7933,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7371
7933
|
}
|
|
7372
7934
|
let extractedBinary = null;
|
|
7373
7935
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
7374
|
-
const listResult =
|
|
7936
|
+
const listResult = spawnSync8("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7375
7937
|
if (listResult.error) throw listResult.error;
|
|
7376
7938
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
7377
7939
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -7379,7 +7941,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7379
7941
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
7380
7942
|
}
|
|
7381
7943
|
}
|
|
7382
|
-
const typeResult =
|
|
7944
|
+
const typeResult = spawnSync8("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7383
7945
|
if (typeResult.error) throw typeResult.error;
|
|
7384
7946
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
7385
7947
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -7388,7 +7950,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7388
7950
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
7389
7951
|
}
|
|
7390
7952
|
}
|
|
7391
|
-
const tarResult =
|
|
7953
|
+
const tarResult = spawnSync8("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
|
|
7392
7954
|
stdio: ["ignore", "ignore", "inherit"],
|
|
7393
7955
|
timeout: 6e4
|
|
7394
7956
|
});
|
|
@@ -7397,10 +7959,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7397
7959
|
} else if (tempPath.endsWith(".gz")) {
|
|
7398
7960
|
const baseName = path10.basename(tempPath, ".gz");
|
|
7399
7961
|
const outputPath = path10.join(tempDir, baseName);
|
|
7400
|
-
const gzipResult =
|
|
7962
|
+
const gzipResult = spawnSync8("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7401
7963
|
if (gzipResult.error) throw gzipResult.error;
|
|
7402
7964
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7403
|
-
|
|
7965
|
+
fs14.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7404
7966
|
extractedBinary = outputPath;
|
|
7405
7967
|
}
|
|
7406
7968
|
const foundBinary = extractedBinary || findBinaryInDir(tempDir);
|
|
@@ -7410,8 +7972,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7410
7972
|
if (progressCallback) {
|
|
7411
7973
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7412
7974
|
}
|
|
7413
|
-
|
|
7414
|
-
const check =
|
|
7975
|
+
fs14.chmodSync(foundBinary, 493);
|
|
7976
|
+
const check = spawnSync8(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7415
7977
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7416
7978
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7417
7979
|
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
|
|
@@ -7427,21 +7989,23 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7427
7989
|
}
|
|
7428
7990
|
}
|
|
7429
7991
|
const targetPath = PATHS.mihomoBinary;
|
|
7430
|
-
|
|
7431
|
-
|
|
7992
|
+
fs14.renameSync(foundBinary, targetPath);
|
|
7993
|
+
fs14.chmodSync(targetPath, 493);
|
|
7432
7994
|
clearKernelVersionCache();
|
|
7433
7995
|
return { version: latest.tag_name, path: targetPath };
|
|
7434
7996
|
} finally {
|
|
7435
7997
|
try {
|
|
7436
|
-
|
|
7998
|
+
fs14.rmSync(tempDir, { recursive: true, force: true });
|
|
7437
7999
|
} catch {
|
|
7438
8000
|
}
|
|
7439
8001
|
}
|
|
7440
8002
|
}
|
|
7441
8003
|
|
|
7442
8004
|
// src/commands/kernel.ts
|
|
8005
|
+
var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
|
|
7443
8006
|
async function cmdKernel(args) {
|
|
7444
8007
|
const mirrorInfo = parseMirrorArg(args);
|
|
8008
|
+
assertPositionalCount(args, 0, 1, "mihomo kernel [--mirror [\u955C\u50CF]]", KERNEL_VALUE_FLAGS);
|
|
7445
8009
|
const effectiveMirror = mirrorInfo.mirror;
|
|
7446
8010
|
const proxyRunning = getRunningState().running;
|
|
7447
8011
|
const proxyPort = proxyRunning ? getPorts().mixed : null;
|
|
@@ -7524,12 +8088,11 @@ async function cmdKernel(args) {
|
|
|
7524
8088
|
// src/commands/log.ts
|
|
7525
8089
|
function cmdLogs(args) {
|
|
7526
8090
|
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8091
|
+
assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
|
|
7527
8092
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
7528
8093
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
7529
8094
|
const follow = hasFlag(args, "-f", "--follow");
|
|
7530
|
-
const hasLinesFlag = args.some(
|
|
7531
|
-
(a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
|
|
7532
|
-
);
|
|
8095
|
+
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
7533
8096
|
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
7534
8097
|
if (targetName) {
|
|
7535
8098
|
let logPath;
|
|
@@ -7592,240 +8155,6 @@ function cmdLogs(args) {
|
|
|
7592
8155
|
console.log("");
|
|
7593
8156
|
}
|
|
7594
8157
|
|
|
7595
|
-
// src/commands/reset.ts
|
|
7596
|
-
import fs14 from "fs";
|
|
7597
|
-
|
|
7598
|
-
// src/process-stop.ts
|
|
7599
|
-
import { spawnSync as spawnSync8 } from "child_process";
|
|
7600
|
-
import fs13 from "fs";
|
|
7601
|
-
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
7602
|
-
var PROCESS_WAIT_INTERVAL = 100;
|
|
7603
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
7604
|
-
function clearRuntime() {
|
|
7605
|
-
if (fs13.existsSync(DIRS.runtime)) {
|
|
7606
|
-
rmrf(DIRS.runtime);
|
|
7607
|
-
}
|
|
7608
|
-
ensureDirs();
|
|
7609
|
-
}
|
|
7610
|
-
function clearPid() {
|
|
7611
|
-
if (!fs13.existsSync(PATHS.pidFile)) return;
|
|
7612
|
-
if (isPidFileOwnedByRoot()) {
|
|
7613
|
-
try {
|
|
7614
|
-
spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
7615
|
-
} catch {
|
|
7616
|
-
}
|
|
7617
|
-
} else {
|
|
7618
|
-
try {
|
|
7619
|
-
fs13.unlinkSync(PATHS.pidFile);
|
|
7620
|
-
} catch {
|
|
7621
|
-
}
|
|
7622
|
-
}
|
|
7623
|
-
}
|
|
7624
|
-
function killProcess(pid) {
|
|
7625
|
-
try {
|
|
7626
|
-
process.kill(pid, "SIGKILL");
|
|
7627
|
-
return true;
|
|
7628
|
-
} catch {
|
|
7629
|
-
return false;
|
|
7630
|
-
}
|
|
7631
|
-
}
|
|
7632
|
-
function killAllMihomo(forceSudo = false) {
|
|
7633
|
-
const pattern = MAIN_INSTANCE_PATTERN;
|
|
7634
|
-
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
7635
|
-
const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
|
|
7636
|
-
try {
|
|
7637
|
-
const result = spawnSync8(argv[0], argv[1], options);
|
|
7638
|
-
if (result.error) return false;
|
|
7639
|
-
return result.status === 0 || result.status === 1;
|
|
7640
|
-
} catch {
|
|
7641
|
-
return false;
|
|
7642
|
-
}
|
|
7643
|
-
}
|
|
7644
|
-
async function cleanupAll(forceSudo = false) {
|
|
7645
|
-
const pids = getMihomoPids();
|
|
7646
|
-
if (pids.length === 0) {
|
|
7647
|
-
clearPid();
|
|
7648
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
7649
|
-
}
|
|
7650
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
7651
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
7652
|
-
let killedCount = 0;
|
|
7653
|
-
const failedPids = [];
|
|
7654
|
-
if (needsSudo) {
|
|
7655
|
-
const success = killAllMihomo(true);
|
|
7656
|
-
if (success) {
|
|
7657
|
-
killedCount = pids.length;
|
|
7658
|
-
} else {
|
|
7659
|
-
failedPids.push(...pids);
|
|
7660
|
-
}
|
|
7661
|
-
} else {
|
|
7662
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
7663
|
-
if (killAllMihomo(false)) {
|
|
7664
|
-
killedCount = pids.length;
|
|
7665
|
-
} else {
|
|
7666
|
-
failedPids.push(...pids);
|
|
7667
|
-
}
|
|
7668
|
-
} else {
|
|
7669
|
-
for (const pid of pids) {
|
|
7670
|
-
if (killProcess(pid)) {
|
|
7671
|
-
killedCount++;
|
|
7672
|
-
} else {
|
|
7673
|
-
failedPids.push(pid);
|
|
7674
|
-
}
|
|
7675
|
-
}
|
|
7676
|
-
}
|
|
7677
|
-
}
|
|
7678
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
7679
|
-
if (getMihomoPids().length === 0) break;
|
|
7680
|
-
await sleep(PROCESS_WAIT_INTERVAL);
|
|
7681
|
-
}
|
|
7682
|
-
clearPid();
|
|
7683
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
7684
|
-
}
|
|
7685
|
-
async function stop(forceSudo = false) {
|
|
7686
|
-
const allPids = getMihomoPids();
|
|
7687
|
-
if (allPids.length === 0) {
|
|
7688
|
-
clearPid();
|
|
7689
|
-
clearRuntime();
|
|
7690
|
-
return { success: true, notRunning: true };
|
|
7691
|
-
}
|
|
7692
|
-
const result = await cleanupAll(forceSudo);
|
|
7693
|
-
const remaining = getMihomoPids();
|
|
7694
|
-
if (remaining.length > 0) {
|
|
7695
|
-
console.log("");
|
|
7696
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
7697
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
7698
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
7699
|
-
console.log("");
|
|
7700
|
-
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
7701
|
-
}
|
|
7702
|
-
clearRuntime();
|
|
7703
|
-
return { success: true, killed: result.killed };
|
|
7704
|
-
}
|
|
7705
|
-
|
|
7706
|
-
// src/commands/reset.ts
|
|
7707
|
-
var RESET_TARGETS = [
|
|
7708
|
-
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
7709
|
-
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
7710
|
-
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
7711
|
-
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
7712
|
-
{
|
|
7713
|
-
id: "overwrites",
|
|
7714
|
-
aliases: ["overwrite", "overwrites", "ow"],
|
|
7715
|
-
label: "\u8986\u5199",
|
|
7716
|
-
needsStop: false,
|
|
7717
|
-
preserveOnBare: true,
|
|
7718
|
-
paths: () => fs14.existsSync(USER_DATA_DIR) ? fs14.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
7719
|
-
},
|
|
7720
|
-
{
|
|
7721
|
-
id: "settings",
|
|
7722
|
-
aliases: ["setting", "settings", "config"],
|
|
7723
|
-
label: "\u8BBE\u7F6E",
|
|
7724
|
-
needsStop: false,
|
|
7725
|
-
preserveOnBare: true,
|
|
7726
|
-
// 损坏备份也包含订阅凭据,需要一起删除
|
|
7727
|
-
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
7728
|
-
},
|
|
7729
|
-
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
7730
|
-
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
7731
|
-
];
|
|
7732
|
-
function resolveResetTargets(names) {
|
|
7733
|
-
const matched = /* @__PURE__ */ new Set();
|
|
7734
|
-
for (const name of names) {
|
|
7735
|
-
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
7736
|
-
if (!target) {
|
|
7737
|
-
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
7738
|
-
}
|
|
7739
|
-
matched.add(target);
|
|
7740
|
-
}
|
|
7741
|
-
return [...matched];
|
|
7742
|
-
}
|
|
7743
|
-
async function cmdReset(args) {
|
|
7744
|
-
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
7745
|
-
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
7746
|
-
const namedTargets = resolveResetTargets(names);
|
|
7747
|
-
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
7748
|
-
const ids = new Set(targets.map((t) => t.id));
|
|
7749
|
-
const needsStop = targets.some((t) => t.needsStop);
|
|
7750
|
-
const serviceTargeted = ids.has("service");
|
|
7751
|
-
const service = getServiceStatus();
|
|
7752
|
-
const serviceActive = service.installed || service.loaded;
|
|
7753
|
-
const legacy = detectLegacySystemInstall();
|
|
7754
|
-
if (targets.length === 1) {
|
|
7755
|
-
if (serviceTargeted && !serviceActive && !legacy) {
|
|
7756
|
-
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
7757
|
-
return;
|
|
7758
|
-
}
|
|
7759
|
-
}
|
|
7760
|
-
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
7761
|
-
console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
|
|
7762
|
-
}
|
|
7763
|
-
if (serviceTargeted && serviceActive) {
|
|
7764
|
-
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
7765
|
-
} else if (needsStop && serviceActive) {
|
|
7766
|
-
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
7767
|
-
}
|
|
7768
|
-
if ((needsStop || serviceTargeted) && legacy) {
|
|
7769
|
-
console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
7770
|
-
}
|
|
7771
|
-
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
7772
|
-
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
7773
|
-
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
7774
|
-
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
7775
|
-
})) {
|
|
7776
|
-
console.log("\u5DF2\u53D6\u6D88");
|
|
7777
|
-
return;
|
|
7778
|
-
}
|
|
7779
|
-
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
7780
|
-
if (serviceActive) {
|
|
7781
|
-
if (serviceTargeted) await uninstallService();
|
|
7782
|
-
else if (needsStop) await stopService();
|
|
7783
|
-
}
|
|
7784
|
-
if (needsStop) {
|
|
7785
|
-
const cleanup = await cleanupAll();
|
|
7786
|
-
if (cleanup.remaining.length > 0) {
|
|
7787
|
-
throw new CliError(cleanup.remaining.join(", "), {
|
|
7788
|
-
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
7789
|
-
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
7790
|
-
});
|
|
7791
|
-
}
|
|
7792
|
-
recordServiceStopped();
|
|
7793
|
-
}
|
|
7794
|
-
const deleted = /* @__PURE__ */ new Set();
|
|
7795
|
-
for (const target of targets) {
|
|
7796
|
-
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
7797
|
-
for (const filePath of target.paths()) {
|
|
7798
|
-
if (!fs14.existsSync(filePath)) continue;
|
|
7799
|
-
try {
|
|
7800
|
-
rmrf(filePath);
|
|
7801
|
-
} catch (e) {
|
|
7802
|
-
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
7803
|
-
}
|
|
7804
|
-
hadContent = true;
|
|
7805
|
-
}
|
|
7806
|
-
if (hadContent) deleted.add(target.id);
|
|
7807
|
-
}
|
|
7808
|
-
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
7809
|
-
updateSettings((settings) => {
|
|
7810
|
-
const patch = {};
|
|
7811
|
-
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
7812
|
-
patch.subscriptions = void 0;
|
|
7813
|
-
patch.active_subscription = void 0;
|
|
7814
|
-
deleted.add("subs");
|
|
7815
|
-
}
|
|
7816
|
-
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
7817
|
-
patch.overwrite_enabled = void 0;
|
|
7818
|
-
deleted.add("overwrites");
|
|
7819
|
-
}
|
|
7820
|
-
return patch;
|
|
7821
|
-
});
|
|
7822
|
-
}
|
|
7823
|
-
if (ids.has("kernel")) clearKernelVersionCache();
|
|
7824
|
-
ensureDirs();
|
|
7825
|
-
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
7826
|
-
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
7827
|
-
}
|
|
7828
|
-
|
|
7829
8158
|
// src/commands/service.ts
|
|
7830
8159
|
import fs15 from "fs";
|
|
7831
8160
|
async function handleLegacyInstall() {
|
|
@@ -7846,6 +8175,7 @@ function printRestoreSkipped() {
|
|
|
7846
8175
|
}
|
|
7847
8176
|
async function cmdInstall(args) {
|
|
7848
8177
|
assertKnownFlags(args.slice(1), [], "install");
|
|
8178
|
+
assertPositionalCount(args, 0, 1, "mihomo install");
|
|
7849
8179
|
if (!hasKernel()) {
|
|
7850
8180
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
7851
8181
|
}
|
|
@@ -7886,6 +8216,7 @@ async function cmdInstall(args) {
|
|
|
7886
8216
|
}
|
|
7887
8217
|
async function cmdUninstall(args) {
|
|
7888
8218
|
assertKnownFlags(args.slice(1), [], "uninstall");
|
|
8219
|
+
assertPositionalCount(args, 0, 1, "mihomo uninstall");
|
|
7889
8220
|
const status = getServiceStatus();
|
|
7890
8221
|
const legacy = detectLegacySystemInstall();
|
|
7891
8222
|
const residue = getMihomoPids();
|
|
@@ -7927,6 +8258,7 @@ function handleStopResult(result) {
|
|
|
7927
8258
|
}
|
|
7928
8259
|
async function cmdStop(args) {
|
|
7929
8260
|
assertKnownFlags(args.slice(1), [], "stop");
|
|
8261
|
+
assertPositionalCount(args, 0, 1, "mihomo stop");
|
|
7930
8262
|
if (detectLegacySystemInstall()) {
|
|
7931
8263
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
|
|
7932
8264
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
@@ -7971,6 +8303,7 @@ function copyToClipboard(text) {
|
|
|
7971
8303
|
}
|
|
7972
8304
|
function cmdUI(args) {
|
|
7973
8305
|
assertKnownFlags(args.slice(1), [], "ui");
|
|
8306
|
+
assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd]");
|
|
7974
8307
|
const uiName = args[1] || "zash";
|
|
7975
8308
|
if (!Object.hasOwn(UI_URLS, uiName)) {
|
|
7976
8309
|
throw new CliError(`\u672A\u77E5\u7684 UI "${uiName}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
|
|
@@ -8190,16 +8523,15 @@ process.on("SIGTERM", () => {
|
|
|
8190
8523
|
});
|
|
8191
8524
|
process.on("uncaughtException", (e) => {
|
|
8192
8525
|
console.error(`
|
|
8193
|
-
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${e
|
|
8194
|
-
if (e.stack) {
|
|
8526
|
+
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${errorMessage(e)}`);
|
|
8527
|
+
if (e instanceof Error && e.stack) {
|
|
8195
8528
|
console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8196
8529
|
}
|
|
8197
8530
|
process.exit(1);
|
|
8198
8531
|
});
|
|
8199
8532
|
process.on("unhandledRejection", (reason) => {
|
|
8200
|
-
const msg = reason instanceof Error ? reason.message : String(reason);
|
|
8201
8533
|
console.error(`
|
|
8202
|
-
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${
|
|
8534
|
+
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
|
|
8203
8535
|
process.exit(1);
|
|
8204
8536
|
});
|
|
8205
8537
|
function clearProxyEnv() {
|
|
@@ -8274,19 +8606,23 @@ async function main() {
|
|
|
8274
8606
|
assertSupportedNodeVersion(command.name);
|
|
8275
8607
|
assertSupportedPlatform(command.name);
|
|
8276
8608
|
assertNotRoot(command.name);
|
|
8277
|
-
|
|
8278
|
-
|
|
8609
|
+
if (!GUARD_EXEMPT_COMMANDS.has(command.name)) {
|
|
8610
|
+
ensureDirs();
|
|
8611
|
+
}
|
|
8612
|
+
if (command.group === "meta") {
|
|
8613
|
+
assertKnownFlags(args.slice(1), [], command.name);
|
|
8614
|
+
assertPositionalCount(args, 0, 1, `mihomo ${command.name}`);
|
|
8615
|
+
}
|
|
8279
8616
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8280
8617
|
}
|
|
8281
8618
|
main().catch((e) => {
|
|
8282
8619
|
if (e instanceof CliError) {
|
|
8283
|
-
console.error(`${
|
|
8620
|
+
console.error(`${stderrColors.red(`${e.label}:`)} ${e.message}`);
|
|
8284
8621
|
for (const line of e.hint) console.error(line);
|
|
8285
8622
|
process.exit(e.exitCode);
|
|
8286
8623
|
}
|
|
8287
|
-
|
|
8288
|
-
console.error(
|
|
8289
|
-
if (err.stack) console.error(err.stack.split("\n").slice(1).join("\n"));
|
|
8624
|
+
console.error(`${stderrColors.red("\u9519\u8BEF:")} ${errorMessage(e)}`);
|
|
8625
|
+
if (e instanceof Error && e.stack) console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8290
8626
|
process.exit(1);
|
|
8291
8627
|
});
|
|
8292
8628
|
/*! Bundled license information:
|