mihomo-cli 4.2.3 → 4.3.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 +46 -0
- package/README.md +40 -7
- package/dist/index.js +1180 -555
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3773,6 +3773,20 @@ function listOverwriteFile() {
|
|
|
3773
3773
|
};
|
|
3774
3774
|
}
|
|
3775
3775
|
|
|
3776
|
+
// src/flags.ts
|
|
3777
|
+
var FLAGS = [
|
|
3778
|
+
// === start 的选项(重启透传) ===
|
|
3779
|
+
{ forms: ["-s", "--no-update"], takesValue: false, passthroughToRestart: true },
|
|
3780
|
+
{ forms: ["-u", "--update-timeout"], takesValue: true, passthroughToRestart: true },
|
|
3781
|
+
// === logs 的选项 ===
|
|
3782
|
+
{ forms: ["-n", "--lines"], takesValue: true }
|
|
3783
|
+
// 注意:`--mirror`(kernel)是可选值选项——`--mirror`、`--mirror=url`、`--mirror url`
|
|
3784
|
+
// 三种形式都合法,只走 parseMirrorArg。故意不在此登记:登记了 getNonFlagArg 反而会
|
|
3785
|
+
// 把它的值吞掉。它的移除/校验由 parseMirrorArg 自己负责。
|
|
3786
|
+
];
|
|
3787
|
+
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
3788
|
+
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
3789
|
+
|
|
3776
3790
|
// src/utils.ts
|
|
3777
3791
|
function sleep(ms) {
|
|
3778
3792
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -3844,6 +3858,35 @@ function formatDate(dateOrIso) {
|
|
|
3844
3858
|
return "\u672A\u77E5";
|
|
3845
3859
|
}
|
|
3846
3860
|
}
|
|
3861
|
+
function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
3862
|
+
if (dateOrIso === void 0 || dateOrIso === null) return null;
|
|
3863
|
+
let t;
|
|
3864
|
+
try {
|
|
3865
|
+
const d = dateOrIso instanceof Date ? dateOrIso : new Date(dateOrIso);
|
|
3866
|
+
t = d.getTime();
|
|
3867
|
+
} catch {
|
|
3868
|
+
return null;
|
|
3869
|
+
}
|
|
3870
|
+
if (Number.isNaN(t) || t > nowMs) return null;
|
|
3871
|
+
const sec = Math.floor((nowMs - t) / 1e3);
|
|
3872
|
+
if (sec < 60) return "\u521A\u521A";
|
|
3873
|
+
const min = Math.floor(sec / 60);
|
|
3874
|
+
if (min < 60) return `${min} \u5206\u949F\u524D`;
|
|
3875
|
+
const hour = Math.floor(min / 60);
|
|
3876
|
+
if (hour < 24) return `${hour} \u5C0F\u65F6\u524D`;
|
|
3877
|
+
const day = Math.floor(hour / 24);
|
|
3878
|
+
if (day < 30) return `${day} \u5929\u524D`;
|
|
3879
|
+
const month = Math.floor(day / 30);
|
|
3880
|
+
if (month < 12) return `${month} \u4E2A\u6708\u524D`;
|
|
3881
|
+
return `${Math.floor(month / 12)} \u5E74\u524D`;
|
|
3882
|
+
}
|
|
3883
|
+
function subscriptionUrgency(entry, nowMs = Date.now()) {
|
|
3884
|
+
if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 < nowMs) return "expired";
|
|
3885
|
+
const used = (entry.upload || 0) + (entry.download || 0);
|
|
3886
|
+
if (entry.total !== void 0 && entry.total > 0 && used >= entry.total) return "traffic-exhausted";
|
|
3887
|
+
if (entry.expire !== void 0 && entry.expire > 0 && entry.expire * 1e3 - nowMs < 7 * 864e5) return "expiring";
|
|
3888
|
+
return null;
|
|
3889
|
+
}
|
|
3847
3890
|
function hasFlag(args, short, long) {
|
|
3848
3891
|
return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
|
|
3849
3892
|
}
|
|
@@ -3883,18 +3926,16 @@ function assertNoRemovedSshFlag(args) {
|
|
|
3883
3926
|
]
|
|
3884
3927
|
});
|
|
3885
3928
|
}
|
|
3886
|
-
var VALUE_FLAGS = /* @__PURE__ */ new Set(["-n", "--lines", "-u", "--update-timeout"]);
|
|
3887
3929
|
function extractStartOptions(args) {
|
|
3888
3930
|
if (!args) return [];
|
|
3889
|
-
const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update"]);
|
|
3890
3931
|
const out = [];
|
|
3891
3932
|
for (let i = 0; i < args.length; i++) {
|
|
3892
3933
|
const a = args[i];
|
|
3893
|
-
|
|
3894
|
-
|
|
3934
|
+
const spec = START_RESTART_FLAGS.find((f) => f.forms.includes(a) || f.forms.some((form) => form.startsWith("--") && a.startsWith(`${form}=`)));
|
|
3935
|
+
if (!spec) continue;
|
|
3936
|
+
out.push(a);
|
|
3937
|
+
if (spec.takesValue && !a.includes("=")) {
|
|
3895
3938
|
if (i + 1 < args.length) out.push(args[++i]);
|
|
3896
|
-
} else if (BOOL_FLAGS.has(a) || /^--update-timeout=/.test(a)) {
|
|
3897
|
-
out.push(a);
|
|
3898
3939
|
}
|
|
3899
3940
|
}
|
|
3900
3941
|
return out;
|
|
@@ -3963,9 +4004,9 @@ function normalizeMirrorUrl(val) {
|
|
|
3963
4004
|
const url = parsed.toString();
|
|
3964
4005
|
return url.endsWith("/") ? url : `${url}/`;
|
|
3965
4006
|
}
|
|
3966
|
-
function parseMirrorArg(args) {
|
|
4007
|
+
function parseMirrorArg(args, savedMirror) {
|
|
3967
4008
|
if (!args || args.length < 2) {
|
|
3968
|
-
return { mirror: null, isOverride: false };
|
|
4009
|
+
return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
|
|
3969
4010
|
}
|
|
3970
4011
|
if (args.some((a) => a === "--mirror-all" || a.startsWith("--mirror-all="))) {
|
|
3971
4012
|
throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
|
|
@@ -3979,7 +4020,7 @@ function parseMirrorArg(args) {
|
|
|
3979
4020
|
});
|
|
3980
4021
|
}
|
|
3981
4022
|
if (args.includes("--no-mirror") || args.includes("--direct")) {
|
|
3982
|
-
return { mirror: null, isOverride: true };
|
|
4023
|
+
return { mirror: null, isOverride: true, clearSaved: true };
|
|
3983
4024
|
}
|
|
3984
4025
|
const mirrorEq = args.find((a) => a.startsWith("--mirror="));
|
|
3985
4026
|
const mirrorIdx = args.indexOf("--mirror");
|
|
@@ -3987,11 +4028,12 @@ function parseMirrorArg(args) {
|
|
|
3987
4028
|
const inline = mirrorEq?.slice("--mirror=".length);
|
|
3988
4029
|
const nextArg = inline ?? args[mirrorIdx + 1];
|
|
3989
4030
|
if (!nextArg || nextArg.startsWith("-")) {
|
|
3990
|
-
return { mirror: DEFAULT_MIRROR, isOverride: true };
|
|
4031
|
+
return { mirror: DEFAULT_MIRROR, isOverride: true, remember: true };
|
|
3991
4032
|
}
|
|
3992
|
-
|
|
4033
|
+
const normalized = normalizeMirrorUrl(nextArg);
|
|
4034
|
+
return normalized ? { mirror: normalized, isOverride: true, remember: true } : { mirror: null, isOverride: true, clearSaved: true };
|
|
3993
4035
|
}
|
|
3994
|
-
return { mirror: null, isOverride: false };
|
|
4036
|
+
return savedMirror ? { mirror: savedMirror, isOverride: false } : { mirror: null, isOverride: false };
|
|
3995
4037
|
}
|
|
3996
4038
|
|
|
3997
4039
|
// src/config.ts
|
|
@@ -4357,132 +4399,10 @@ function clearKernelVersionCache() {
|
|
|
4357
4399
|
kernelVersionCached = false;
|
|
4358
4400
|
}
|
|
4359
4401
|
|
|
4360
|
-
// src/
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
`);
|
|
4365
|
-
console.log(
|
|
4366
|
-
`\u5E38\u7528\u547D\u4EE4:
|
|
4367
|
-
${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
|
|
4368
|
-
${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
|
|
4369
|
-
${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
|
|
4370
|
-
${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
|
|
4371
|
-
`
|
|
4372
|
-
);
|
|
4373
|
-
}
|
|
4374
|
-
var GROUP_TITLES = [
|
|
4375
|
-
["control", "\u63A7\u5236:"],
|
|
4376
|
-
["interface", "\u754C\u9762:"],
|
|
4377
|
-
["subscription", "\u8BA2\u9605:"],
|
|
4378
|
-
["config", "\u914D\u7F6E:"],
|
|
4379
|
-
["system", "\u7CFB\u7EDF:"]
|
|
4380
|
-
];
|
|
4381
|
-
function printHelp(commands) {
|
|
4382
|
-
const lines = [`
|
|
4383
|
-
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
|
|
4384
|
-
const allUsage = commands.flatMap((c) => c.usage);
|
|
4385
|
-
const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
|
|
4386
|
-
const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
|
|
4387
|
-
for (const [group, title] of GROUP_TITLES) {
|
|
4388
|
-
const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
|
|
4389
|
-
if (usageLines.length === 0) continue;
|
|
4390
|
-
lines.push("", colors.cyan(title));
|
|
4391
|
-
for (const u of usageLines) lines.push(formatUsage(u));
|
|
4392
|
-
}
|
|
4393
|
-
const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
|
|
4394
|
-
if (meta.length > 0) {
|
|
4395
|
-
lines.push("", colors.cyan("\u5143:"));
|
|
4396
|
-
for (const u of meta) lines.push(formatUsage(u));
|
|
4397
|
-
}
|
|
4398
|
-
lines.push(
|
|
4399
|
-
"",
|
|
4400
|
-
`${colors.cyan("\u793A\u4F8B:")}`,
|
|
4401
|
-
" mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
|
|
4402
|
-
" mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
|
|
4403
|
-
" mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
|
|
4404
|
-
" mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
|
|
4405
|
-
" mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
4406
|
-
" mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
4407
|
-
" mihomo ui # \u6253\u5F00 Web UI",
|
|
4408
|
-
"",
|
|
4409
|
-
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
4410
|
-
" tun = start tun",
|
|
4411
|
-
"",
|
|
4412
|
-
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
4413
|
-
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
|
|
4414
|
-
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
|
|
4415
|
-
"",
|
|
4416
|
-
`${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
|
|
4417
|
-
" \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
|
|
4418
|
-
` \u9ED8\u8BA4: ${USER_DATA_DIR}`
|
|
4419
|
-
);
|
|
4420
|
-
console.log(lines.join("\n"));
|
|
4421
|
-
}
|
|
4422
|
-
function printVersion() {
|
|
4423
|
-
const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
|
|
4424
|
-
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
4425
|
-
console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
|
|
4426
|
-
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
4427
|
-
}
|
|
4428
|
-
|
|
4429
|
-
// src/open.ts
|
|
4430
|
-
import { spawn } from "child_process";
|
|
4431
|
-
|
|
4432
|
-
// src/lifecycle.ts
|
|
4433
|
-
var silentSigint = false;
|
|
4434
|
-
function setSilentSigint(value) {
|
|
4435
|
-
silentSigint = value;
|
|
4436
|
-
}
|
|
4437
|
-
function isSilentSigint() {
|
|
4438
|
-
return silentSigint;
|
|
4439
|
-
}
|
|
4440
|
-
|
|
4441
|
-
// src/open.ts
|
|
4442
|
-
function openUrl(url) {
|
|
4443
|
-
try {
|
|
4444
|
-
const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
|
|
4445
|
-
child.unref();
|
|
4446
|
-
child.on("error", () => {
|
|
4447
|
-
});
|
|
4448
|
-
return true;
|
|
4449
|
-
} catch {
|
|
4450
|
-
return false;
|
|
4451
|
-
}
|
|
4452
|
-
}
|
|
4453
|
-
function openLogFile(logPath, label) {
|
|
4454
|
-
const displayLabel = label || logPath;
|
|
4455
|
-
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
|
|
4456
|
-
const success = openUrl(logPath);
|
|
4457
|
-
if (!success) {
|
|
4458
|
-
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
4459
|
-
}
|
|
4460
|
-
}
|
|
4461
|
-
function viewLogWithTail(logPath, options) {
|
|
4462
|
-
const follow = options?.follow;
|
|
4463
|
-
const lines = options?.lines || 100;
|
|
4464
|
-
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
4465
|
-
if (follow) {
|
|
4466
|
-
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
4467
|
-
} else {
|
|
4468
|
-
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
4469
|
-
`);
|
|
4470
|
-
}
|
|
4471
|
-
const tailArgs = [];
|
|
4472
|
-
if (follow) tailArgs.push("-f");
|
|
4473
|
-
tailArgs.push("-n", lines.toString());
|
|
4474
|
-
tailArgs.push(logPath);
|
|
4475
|
-
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
4476
|
-
if (follow) setSilentSigint(true);
|
|
4477
|
-
tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
|
|
4478
|
-
tail.on("error", (e) => {
|
|
4479
|
-
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
4480
|
-
process.exit(1);
|
|
4481
|
-
});
|
|
4482
|
-
}
|
|
4483
|
-
|
|
4484
|
-
// src/commands/shared.ts
|
|
4485
|
-
import readline from "readline";
|
|
4402
|
+
// src/service.ts
|
|
4403
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
4404
|
+
import fs8 from "fs";
|
|
4405
|
+
import path6 from "path";
|
|
4486
4406
|
|
|
4487
4407
|
// src/log-files.ts
|
|
4488
4408
|
import fs5 from "fs";
|
|
@@ -4672,14 +4592,15 @@ function checkStaleState() {
|
|
|
4672
4592
|
}
|
|
4673
4593
|
function getProcessInfo(pid) {
|
|
4674
4594
|
try {
|
|
4675
|
-
const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
|
|
4595
|
+
const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
|
|
4676
4596
|
const psOutput = (result.stdout || "").trim();
|
|
4677
4597
|
if (!psOutput) return null;
|
|
4678
|
-
const
|
|
4598
|
+
const [rssRaw, uidRaw] = psOutput.split(/\s+/);
|
|
4599
|
+
const rss = parseInt(rssRaw, 10);
|
|
4679
4600
|
return {
|
|
4680
4601
|
pid,
|
|
4681
4602
|
memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
4682
|
-
isRoot:
|
|
4603
|
+
isRoot: uidRaw === "0"
|
|
4683
4604
|
};
|
|
4684
4605
|
} catch {
|
|
4685
4606
|
return { pid, memory: "\u672A\u77E5", isRoot: false };
|
|
@@ -4698,9 +4619,6 @@ function getStatus() {
|
|
|
4698
4619
|
};
|
|
4699
4620
|
}
|
|
4700
4621
|
|
|
4701
|
-
// src/process-start.ts
|
|
4702
|
-
import fs8 from "fs";
|
|
4703
|
-
|
|
4704
4622
|
// src/sudo.ts
|
|
4705
4623
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
4706
4624
|
import fs7 from "fs";
|
|
@@ -4735,116 +4653,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
4735
4653
|
}
|
|
4736
4654
|
}
|
|
4737
4655
|
|
|
4738
|
-
// src/process-start.ts
|
|
4739
|
-
var TUN_MODE_POST_WAIT_MS = 500;
|
|
4740
|
-
function buildTunLaunchScript() {
|
|
4741
|
-
const binary = shellQuote(PATHS.mihomoBinary);
|
|
4742
|
-
const configFile = shellQuote(PATHS.configFile);
|
|
4743
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
4744
|
-
const pidFile = shellQuote(PATHS.pidFile);
|
|
4745
|
-
const dataDir = shellQuote(DIRS.data);
|
|
4746
|
-
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
4747
|
-
return `#!/bin/bash
|
|
4748
|
-
BINARY=${binary}
|
|
4749
|
-
CONFIG_FILE=${configFile}
|
|
4750
|
-
LOG_FILE=${logFile}
|
|
4751
|
-
PID_FILE=${pidFile}
|
|
4752
|
-
DATA_DIR=${dataDir}
|
|
4753
|
-
KILL_PATTERN=${killPattern}
|
|
4754
|
-
|
|
4755
|
-
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
4756
|
-
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
4757
|
-
sleep 0.2
|
|
4758
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4759
|
-
|
|
4760
|
-
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
4761
|
-
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
4762
|
-
|
|
4763
|
-
# \u542F\u52A8
|
|
4764
|
-
cd /tmp
|
|
4765
|
-
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
4766
|
-
NEW_PID=$!
|
|
4767
|
-
echo \${NEW_PID} > "\${PID_FILE}"
|
|
4768
|
-
|
|
4769
|
-
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
4770
|
-
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
4771
|
-
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
4772
|
-
is_alive() {
|
|
4773
|
-
local stat
|
|
4774
|
-
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
4775
|
-
case "\${stat}" in
|
|
4776
|
-
Z*|'') return 1 ;;
|
|
4777
|
-
*) return 0 ;;
|
|
4778
|
-
esac
|
|
4779
|
-
}
|
|
4780
|
-
|
|
4781
|
-
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
4782
|
-
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
4783
|
-
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
4784
|
-
i=0
|
|
4785
|
-
while [ $i -lt 12 ]; do
|
|
4786
|
-
sleep 0.1
|
|
4787
|
-
is_alive \${NEW_PID} || break
|
|
4788
|
-
i=$((i+1))
|
|
4789
|
-
done
|
|
4790
|
-
if is_alive \${NEW_PID}; then
|
|
4791
|
-
exit 0
|
|
4792
|
-
fi
|
|
4793
|
-
|
|
4794
|
-
# \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
|
|
4795
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4796
|
-
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
4797
|
-
echo ""
|
|
4798
|
-
echo "--- \u65E5\u5FD7 ---"
|
|
4799
|
-
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
4800
|
-
exit 2
|
|
4801
|
-
`;
|
|
4802
|
-
}
|
|
4803
|
-
async function startTun() {
|
|
4804
|
-
ensureDirs();
|
|
4805
|
-
rotateAndCleanupLogs();
|
|
4806
|
-
if (!fs8.existsSync(PATHS.mihomoBinary)) {
|
|
4807
|
-
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4808
|
-
}
|
|
4809
|
-
if (!fs8.existsSync(PATHS.configFile)) {
|
|
4810
|
-
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
4811
|
-
}
|
|
4812
|
-
const logFile = PATHS.logFile;
|
|
4813
|
-
if (fs8.existsSync(logFile)) {
|
|
4814
|
-
try {
|
|
4815
|
-
fs8.accessSync(logFile, fs8.constants.W_OK);
|
|
4816
|
-
} catch {
|
|
4817
|
-
try {
|
|
4818
|
-
fs8.unlinkSync(logFile);
|
|
4819
|
-
} catch {
|
|
4820
|
-
}
|
|
4821
|
-
}
|
|
4822
|
-
}
|
|
4823
|
-
const staleState = checkStaleState();
|
|
4824
|
-
if (staleState.needsCleanup) {
|
|
4825
|
-
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
4826
|
-
}
|
|
4827
|
-
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
4828
|
-
runSudoScript(buildTunLaunchScript(), {
|
|
4829
|
-
action: "TUN \u542F\u52A8",
|
|
4830
|
-
file: "launch-tun.sh",
|
|
4831
|
-
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
4832
|
-
});
|
|
4833
|
-
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
4834
|
-
const finalPid = getPid();
|
|
4835
|
-
if (!finalPid || !isRunning()) {
|
|
4836
|
-
const tail = readLogTail();
|
|
4837
|
-
throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
|
|
4838
|
-
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
|
|
4839
|
-
});
|
|
4840
|
-
}
|
|
4841
|
-
return { success: true, pid: finalPid, mode: "tun" };
|
|
4842
|
-
}
|
|
4843
|
-
|
|
4844
4656
|
// src/service.ts
|
|
4845
|
-
import { spawnSync as spawnSync4 } from "child_process";
|
|
4846
|
-
import fs9 from "fs";
|
|
4847
|
-
import path6 from "path";
|
|
4848
4657
|
function assertServiceLabelSafe() {
|
|
4849
4658
|
if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
|
|
4850
4659
|
throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
|
|
@@ -4866,10 +4675,10 @@ function bootstrapDomain() {
|
|
|
4866
4675
|
return `gui/${process.getuid?.() ?? 0}`;
|
|
4867
4676
|
}
|
|
4868
4677
|
function isServiceInstalled() {
|
|
4869
|
-
return
|
|
4678
|
+
return fs8.existsSync(PATHS.userAgentPlist);
|
|
4870
4679
|
}
|
|
4871
4680
|
function detectLegacySystemInstall() {
|
|
4872
|
-
return
|
|
4681
|
+
return fs8.existsSync(PATHS.systemDaemonPlist);
|
|
4873
4682
|
}
|
|
4874
4683
|
function parseServicePrint(output) {
|
|
4875
4684
|
const stateMatch = output.match(/^\tstate = (.+)$/m);
|
|
@@ -4891,12 +4700,12 @@ function parseDisabledList(output, label) {
|
|
|
4891
4700
|
return value === "true" || value === "disabled";
|
|
4892
4701
|
}
|
|
4893
4702
|
var LAUNCHCTL_NOT_LOADED = 113;
|
|
4894
|
-
function runLaunchctl(args) {
|
|
4703
|
+
function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
4895
4704
|
try {
|
|
4896
|
-
const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout:
|
|
4897
|
-
return { status: result.status, stdout: result.stdout || "" };
|
|
4705
|
+
const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
|
|
4706
|
+
return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
|
|
4898
4707
|
} catch {
|
|
4899
|
-
return { status: null, stdout: "" };
|
|
4708
|
+
return { status: null, stdout: "", stderr: "" };
|
|
4900
4709
|
}
|
|
4901
4710
|
}
|
|
4902
4711
|
function assertLaunchctlQueryOk(status, what) {
|
|
@@ -4984,45 +4793,62 @@ ${argsXml}
|
|
|
4984
4793
|
`;
|
|
4985
4794
|
}
|
|
4986
4795
|
function ensureServiceSymlink() {
|
|
4987
|
-
if (!
|
|
4796
|
+
if (!fs8.existsSync(PATHS.mihomoBinary)) {
|
|
4988
4797
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4989
4798
|
}
|
|
4990
4799
|
try {
|
|
4991
|
-
const current =
|
|
4800
|
+
const current = fs8.readlinkSync(PATHS.serviceBinary);
|
|
4992
4801
|
if (current === "mihomo") return;
|
|
4993
|
-
|
|
4802
|
+
fs8.unlinkSync(PATHS.serviceBinary);
|
|
4994
4803
|
} catch (e) {
|
|
4995
4804
|
const code = e.code;
|
|
4996
4805
|
if (code === "EINVAL") {
|
|
4997
4806
|
try {
|
|
4998
|
-
|
|
4807
|
+
fs8.unlinkSync(PATHS.serviceBinary);
|
|
4999
4808
|
} catch {
|
|
5000
4809
|
}
|
|
5001
4810
|
} else if (code !== "ENOENT") {
|
|
5002
4811
|
throw e;
|
|
5003
4812
|
}
|
|
5004
4813
|
}
|
|
5005
|
-
|
|
4814
|
+
fs8.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
5006
4815
|
}
|
|
5007
|
-
function
|
|
5008
|
-
const
|
|
5009
|
-
|
|
5010
|
-
|
|
5011
|
-
|
|
5012
|
-
|
|
5013
|
-
|
|
5014
|
-
}
|
|
4816
|
+
function runLaunchctlOrThrow(args, what) {
|
|
4817
|
+
const result = runLaunchctl(args);
|
|
4818
|
+
if (result.status === 0) return;
|
|
4819
|
+
const detail = result.stderr.trim();
|
|
4820
|
+
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4821
|
+
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
|
|
4822
|
+
});
|
|
5015
4823
|
}
|
|
5016
|
-
function
|
|
5017
|
-
const
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
|
|
4824
|
+
function bootoutService() {
|
|
4825
|
+
const result = runLaunchctl(["bootout", serviceTarget()]);
|
|
4826
|
+
if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
4827
|
+
const detail = result.stderr.trim();
|
|
4828
|
+
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4829
|
+
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
4830
|
+
});
|
|
4831
|
+
}
|
|
4832
|
+
var UNLOADED_POLL_ATTEMPTS = 25;
|
|
4833
|
+
var UNLOADED_POLL_INTERVAL_MS = 200;
|
|
4834
|
+
async function waitUntilUnloaded(target = serviceTarget()) {
|
|
4835
|
+
for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
|
|
4836
|
+
const result = runLaunchctl(["print", target]);
|
|
4837
|
+
if (result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
4838
|
+
if (result.status !== 0) {
|
|
4839
|
+
throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4840
|
+
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
|
|
4841
|
+
});
|
|
5023
4842
|
}
|
|
5024
|
-
|
|
5025
|
-
|
|
4843
|
+
await sleep(UNLOADED_POLL_INTERVAL_MS);
|
|
4844
|
+
}
|
|
4845
|
+
throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
|
|
4846
|
+
hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
|
|
4847
|
+
});
|
|
4848
|
+
}
|
|
4849
|
+
function cleanupRootResidue() {
|
|
4850
|
+
const rootPids = getMihomoPids().filter(isProcessRoot);
|
|
4851
|
+
if (rootPids.length === 0 && !isPidFileOwnedByRoot()) return;
|
|
5026
4852
|
const script = [
|
|
5027
4853
|
"#!/bin/bash",
|
|
5028
4854
|
// pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
|
|
@@ -5049,71 +4875,45 @@ function killResidualKernels() {
|
|
|
5049
4875
|
}
|
|
5050
4876
|
if (rootPids.length > 0) cleanupRootResidue();
|
|
5051
4877
|
}
|
|
5052
|
-
function
|
|
5053
|
-
const target = shellQuote(serviceTarget());
|
|
5054
|
-
return [
|
|
5055
|
-
"n=0",
|
|
5056
|
-
"while [ $n -lt 25 ]; do",
|
|
5057
|
-
` launchctl print ${target} >/dev/null 2>&1`,
|
|
5058
|
-
" rc=$?",
|
|
5059
|
-
" [ $rc -eq 113 ] && break",
|
|
5060
|
-
" [ $rc -ne 0 ] && exit 6",
|
|
5061
|
-
" sleep 0.2",
|
|
5062
|
-
" n=$((n+1))",
|
|
5063
|
-
"done",
|
|
5064
|
-
`launchctl print ${target} >/dev/null 2>&1; rc=$?`,
|
|
5065
|
-
"[ $rc -eq 0 ] && exit 7",
|
|
5066
|
-
"[ $rc -ne 113 ] && exit 6"
|
|
5067
|
-
];
|
|
5068
|
-
}
|
|
5069
|
-
function installService(wasRunning) {
|
|
4878
|
+
async function installService(wasRunning) {
|
|
5070
4879
|
assertServiceLabelSafe();
|
|
5071
4880
|
ensureDirs();
|
|
5072
4881
|
ensureServiceSymlink();
|
|
5073
4882
|
const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
|
|
5074
4883
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5075
|
-
const target = shellQuote(serviceTarget());
|
|
5076
|
-
const dest = shellQuote(PATHS.userAgentPlist);
|
|
5077
|
-
const stage = shellQuote(stagePath);
|
|
5078
|
-
const destDir = shellQuote(path6.dirname(PATHS.userAgentPlist));
|
|
5079
|
-
const steps = [
|
|
5080
|
-
`plutil -lint ${stage} >/dev/null || exit 2`,
|
|
5081
|
-
`launchctl bootout ${target} 2>/dev/null || true`,
|
|
5082
|
-
...waitUnloadedSteps(),
|
|
5083
|
-
// ~/Library/LaunchAgents 在全新系统上可能不存在;只在缺失时创建,避免改动已有目录权限
|
|
5084
|
-
`[ -d ${destDir} ] || mkdir -p ${destDir}`,
|
|
5085
|
-
`install -m 644 ${stage} ${dest} || exit 3`,
|
|
5086
|
-
...wasRunning ? [`launchctl enable ${target} || exit 5`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 4`] : []
|
|
5087
|
-
];
|
|
5088
4884
|
try {
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
if (
|
|
5101
|
-
|
|
4885
|
+
const lint = spawnSync4("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
|
|
4886
|
+
if (lint.status !== 0) {
|
|
4887
|
+
throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
|
|
4888
|
+
hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
|
|
4889
|
+
});
|
|
4890
|
+
}
|
|
4891
|
+
await bootoutService();
|
|
4892
|
+
await waitUntilUnloaded();
|
|
4893
|
+
fs8.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
4894
|
+
fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
4895
|
+
fs8.chmodSync(PATHS.userAgentPlist, 420);
|
|
4896
|
+
if (wasRunning) {
|
|
4897
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
4898
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
|
|
5102
4899
|
}
|
|
5103
4900
|
} finally {
|
|
5104
4901
|
try {
|
|
5105
|
-
|
|
4902
|
+
fs8.unlinkSync(stagePath);
|
|
5106
4903
|
} catch {
|
|
5107
4904
|
}
|
|
5108
4905
|
}
|
|
4906
|
+
if (!wasRunning) {
|
|
4907
|
+
disableServiceAutoStart();
|
|
4908
|
+
}
|
|
5109
4909
|
}
|
|
5110
|
-
function startService() {
|
|
4910
|
+
async function startService() {
|
|
5111
4911
|
assertServiceLabelSafe();
|
|
5112
4912
|
ensureServiceSymlink();
|
|
5113
4913
|
if (!isServiceInstalled()) {
|
|
5114
4914
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5115
4915
|
}
|
|
5116
|
-
if (!
|
|
4916
|
+
if (!fs8.existsSync(PATHS.configFile)) {
|
|
5117
4917
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
|
|
5118
4918
|
}
|
|
5119
4919
|
if (getConfigInfo()?.tun) {
|
|
@@ -5128,142 +4928,578 @@ function startService() {
|
|
|
5128
4928
|
});
|
|
5129
4929
|
}
|
|
5130
4930
|
cleanupRootResidue();
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
|
|
5134
|
-
action: "\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B",
|
|
5135
|
-
codeMessages: {
|
|
5136
|
-
6: "\u65E0\u6CD5\u786E\u8BA4\u65E7\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
|
|
5137
|
-
7: "\u65E7\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001"
|
|
5138
|
-
}
|
|
5139
|
-
});
|
|
4931
|
+
await bootoutService();
|
|
4932
|
+
await waitUntilUnloaded();
|
|
5140
4933
|
rotateAndCleanupLogs();
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
codeMessages: { 2: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09", 3: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
|
|
5144
|
-
});
|
|
4934
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
4935
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
|
|
5145
4936
|
}
|
|
5146
4937
|
function disableServiceAutoStart() {
|
|
5147
4938
|
assertServiceLabelSafe();
|
|
5148
|
-
|
|
5149
|
-
runLaunchctlSteps([`launchctl disable ${target} || exit 2`], {
|
|
5150
|
-
action: "\u5173\u95ED\u670D\u52A1\u81EA\u542F",
|
|
5151
|
-
codeMessages: { 2: "\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF08launchctl disable\uFF09" }
|
|
5152
|
-
});
|
|
4939
|
+
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F");
|
|
5153
4940
|
if (!isServiceDisabledInLaunchd()) {
|
|
5154
4941
|
throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
|
|
5155
4942
|
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"]
|
|
5156
4943
|
});
|
|
5157
4944
|
}
|
|
5158
4945
|
}
|
|
5159
|
-
function stopService() {
|
|
4946
|
+
async function stopService() {
|
|
5160
4947
|
assertServiceLabelSafe();
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
action: "\u505C\u6B62\u670D\u52A1",
|
|
5164
|
-
codeMessages: {
|
|
5165
|
-
6: "\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
|
|
5166
|
-
7: "\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09"
|
|
5167
|
-
}
|
|
5168
|
-
});
|
|
4948
|
+
await bootoutService();
|
|
4949
|
+
await waitUntilUnloaded();
|
|
5169
4950
|
disableServiceAutoStart();
|
|
5170
4951
|
killResidualKernels();
|
|
5171
4952
|
}
|
|
5172
|
-
function uninstallService() {
|
|
4953
|
+
async function uninstallService() {
|
|
5173
4954
|
assertServiceLabelSafe();
|
|
5174
|
-
|
|
5175
|
-
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
|
|
5187
|
-
|
|
4955
|
+
await bootoutService();
|
|
4956
|
+
await waitUntilUnloaded();
|
|
4957
|
+
try {
|
|
4958
|
+
fs8.rmSync(PATHS.userAgentPlist, { force: true });
|
|
4959
|
+
} catch (e) {
|
|
4960
|
+
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
4961
|
+
}
|
|
4962
|
+
disableServiceAutoStart();
|
|
4963
|
+
killResidualKernels();
|
|
4964
|
+
try {
|
|
4965
|
+
fs8.rmSync(PATHS.serviceBinary, { force: true });
|
|
4966
|
+
} catch {
|
|
4967
|
+
}
|
|
4968
|
+
}
|
|
4969
|
+
function cleanupLegacySystemInstall() {
|
|
4970
|
+
assertServiceLabelSafe();
|
|
4971
|
+
const script = [
|
|
4972
|
+
"#!/bin/bash",
|
|
4973
|
+
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || true`,
|
|
4974
|
+
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
4975
|
+
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
4976
|
+
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
4977
|
+
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
4978
|
+
"exit 0",
|
|
4979
|
+
""
|
|
4980
|
+
].join("\n");
|
|
4981
|
+
runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
|
|
4982
|
+
}
|
|
4983
|
+
function logOversized() {
|
|
4984
|
+
try {
|
|
4985
|
+
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
4986
|
+
} catch {
|
|
4987
|
+
return false;
|
|
4988
|
+
}
|
|
4989
|
+
}
|
|
4990
|
+
async function tryHotReload() {
|
|
4991
|
+
const status = getServiceStatus();
|
|
4992
|
+
if (!status.running || status.pid === null) return false;
|
|
4993
|
+
const controller = new AbortController();
|
|
4994
|
+
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
4995
|
+
const secret = readSettings().controller_secret;
|
|
4996
|
+
const headers = { "Content-Type": "application/json" };
|
|
4997
|
+
if (secret) headers.Authorization = `Bearer ${secret}`;
|
|
4998
|
+
try {
|
|
4999
|
+
const probe = await fetch(`${CONTROLLER_BASE_URL}/version`, { headers, signal: controller.signal });
|
|
5000
|
+
if (!probe.ok) return false;
|
|
5001
|
+
const info = await probe.json();
|
|
5002
|
+
if (typeof info?.version !== "string") return false;
|
|
5003
|
+
const res = await fetch(`${CONTROLLER_BASE_URL}/configs?force=true`, {
|
|
5004
|
+
method: "PUT",
|
|
5005
|
+
headers,
|
|
5006
|
+
body: "{}",
|
|
5007
|
+
signal: controller.signal
|
|
5008
|
+
});
|
|
5009
|
+
return res.status === 204 || res.ok;
|
|
5010
|
+
} catch {
|
|
5011
|
+
return false;
|
|
5012
|
+
} finally {
|
|
5013
|
+
clearTimeout(timer);
|
|
5014
|
+
}
|
|
5015
|
+
}
|
|
5016
|
+
async function restartService() {
|
|
5017
|
+
if (!isServiceInstalled()) {
|
|
5018
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5019
|
+
}
|
|
5020
|
+
if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
|
|
5021
|
+
if (logOversized()) {
|
|
5022
|
+
const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
|
|
5023
|
+
try {
|
|
5024
|
+
fs8.copyFileSync(PATHS.logFile, archiveFile);
|
|
5025
|
+
fs8.writeFileSync(PATHS.logFile, "");
|
|
5026
|
+
} catch {
|
|
5027
|
+
}
|
|
5028
|
+
}
|
|
5029
|
+
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
5030
|
+
if (kick.status !== 0) {
|
|
5031
|
+
runLaunchctl(["enable", serviceTarget()]);
|
|
5032
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
|
|
5033
|
+
}
|
|
5034
|
+
cleanupOldLogs();
|
|
5035
|
+
return { hotReloaded: false };
|
|
5036
|
+
}
|
|
5037
|
+
|
|
5038
|
+
// src/commands/help.ts
|
|
5039
|
+
function printShortHelp() {
|
|
5040
|
+
console.log(`
|
|
5041
|
+
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
|
|
5042
|
+
`);
|
|
5043
|
+
const steps = [];
|
|
5044
|
+
if (!hasKernel()) steps.push(["mihomo kernel", "\u4E0B\u8F7D\u5185\u6838"]);
|
|
5045
|
+
if (getSubscriptions().length === 0) steps.push(["mihomo sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
|
|
5046
|
+
if (!getServiceStatus().installed) steps.push(["mihomo install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
|
|
5047
|
+
if (steps.length > 0) {
|
|
5048
|
+
steps.push(["mihomo start", "\u542F\u52A8\u4EE3\u7406"]);
|
|
5049
|
+
const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
|
|
5050
|
+
console.log("\u5F00\u59CB\u4F7F\u7528:");
|
|
5051
|
+
steps.forEach(([cmd, desc], i) => {
|
|
5052
|
+
console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
|
|
5053
|
+
});
|
|
5054
|
+
console.log("");
|
|
5055
|
+
return;
|
|
5056
|
+
}
|
|
5057
|
+
console.log(
|
|
5058
|
+
`\u5E38\u7528\u547D\u4EE4:
|
|
5059
|
+
${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
|
|
5060
|
+
${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
|
|
5061
|
+
${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
|
|
5062
|
+
${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
|
|
5063
|
+
`
|
|
5064
|
+
);
|
|
5065
|
+
}
|
|
5066
|
+
var GROUP_TITLES = [
|
|
5067
|
+
["control", "\u63A7\u5236:"],
|
|
5068
|
+
["interface", "\u754C\u9762:"],
|
|
5069
|
+
["subscription", "\u8BA2\u9605:"],
|
|
5070
|
+
["config", "\u914D\u7F6E:"],
|
|
5071
|
+
["system", "\u7CFB\u7EDF:"]
|
|
5072
|
+
];
|
|
5073
|
+
function printHelp(commands) {
|
|
5074
|
+
const lines = [`
|
|
5075
|
+
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
|
|
5076
|
+
const allUsage = commands.flatMap((c) => c.usage);
|
|
5077
|
+
const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
|
|
5078
|
+
const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
|
|
5079
|
+
for (const [group, title] of GROUP_TITLES) {
|
|
5080
|
+
const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
|
|
5081
|
+
if (usageLines.length === 0) continue;
|
|
5082
|
+
lines.push("", colors.cyan(title));
|
|
5083
|
+
for (const u of usageLines) lines.push(formatUsage(u));
|
|
5084
|
+
}
|
|
5085
|
+
const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
|
|
5086
|
+
if (meta.length > 0) {
|
|
5087
|
+
lines.push("", colors.cyan("\u5143:"));
|
|
5088
|
+
for (const u of meta) lines.push(formatUsage(u));
|
|
5089
|
+
}
|
|
5090
|
+
lines.push(
|
|
5091
|
+
"",
|
|
5092
|
+
`${colors.cyan("\u793A\u4F8B:")}`,
|
|
5093
|
+
" mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
|
|
5094
|
+
" mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
|
|
5095
|
+
" mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
|
|
5096
|
+
" mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
|
|
5097
|
+
" mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
5098
|
+
" mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
5099
|
+
" mihomo ui # \u6253\u5F00 Web UI",
|
|
5100
|
+
"",
|
|
5101
|
+
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
5102
|
+
" tun = start tun",
|
|
5103
|
+
"",
|
|
5104
|
+
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
5105
|
+
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
|
|
5106
|
+
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
|
|
5107
|
+
"",
|
|
5108
|
+
`${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
|
|
5109
|
+
" \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
|
|
5110
|
+
` \u9ED8\u8BA4: ${USER_DATA_DIR}`
|
|
5111
|
+
);
|
|
5112
|
+
console.log(lines.join("\n"));
|
|
5113
|
+
}
|
|
5114
|
+
function printVersion() {
|
|
5115
|
+
const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
|
|
5116
|
+
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
5117
|
+
console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
|
|
5118
|
+
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
5119
|
+
}
|
|
5120
|
+
|
|
5121
|
+
// src/commands/completion.ts
|
|
5122
|
+
var COMMAND_WORDS = [
|
|
5123
|
+
{ word: "install", desc: "\u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09" },
|
|
5124
|
+
{ word: "start", desc: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F" },
|
|
5125
|
+
{ word: "stop", desc: "\u505C\u6B62\u4EE3\u7406\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F" },
|
|
5126
|
+
{ word: "uninstall", desc: "\u5378\u8F7D\u670D\u52A1" },
|
|
5127
|
+
{ word: "status", desc: "\u67E5\u770B\u72B6\u6001\uFF08--json \u673A\u5668\u53EF\u8BFB\uFF09" },
|
|
5128
|
+
{ word: "logs", desc: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B" },
|
|
5129
|
+
{ word: "ui", desc: "\u6253\u5F00 Web UI" },
|
|
5130
|
+
{ word: "subscription", desc: "\u8BA2\u9605\u7BA1\u7406" },
|
|
5131
|
+
{ word: "overwrite", desc: "\u8986\u5199\u914D\u7F6E" },
|
|
5132
|
+
{ word: "directory", desc: "\u6570\u636E\u76EE\u5F55" },
|
|
5133
|
+
{ word: "kernel", desc: "\u66F4\u65B0\u5185\u6838" },
|
|
5134
|
+
{ word: "update", desc: "\u66F4\u65B0 mihomo-cli" },
|
|
5135
|
+
{ word: "reset", desc: "\u91CD\u7F6E\u7528\u6237\u6570\u636E" },
|
|
5136
|
+
{ word: "doctor", desc: "\u4F53\u68C0\u8BCA\u65AD" },
|
|
5137
|
+
{ word: "completion", desc: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C" },
|
|
5138
|
+
{ word: "use", desc: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF09" },
|
|
5139
|
+
{ word: "tun", desc: "\u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08= start tun\uFF09" },
|
|
5140
|
+
{ word: "help", desc: "\u663E\u793A\u5E2E\u52A9" },
|
|
5141
|
+
{ word: "version", desc: "\u663E\u793A\u7248\u672C" }
|
|
5142
|
+
];
|
|
5143
|
+
var SUBCOMMANDS = {
|
|
5144
|
+
subscription: [
|
|
5145
|
+
{ word: "use", desc: "\u5207\u6362\u8BA2\u9605" },
|
|
5146
|
+
{ word: "add", desc: "\u6DFB\u52A0\u8BA2\u9605" },
|
|
5147
|
+
{ word: "update", desc: "\u66F4\u65B0\u8BA2\u9605" },
|
|
5148
|
+
{ word: "remove", desc: "\u5220\u9664\u8BA2\u9605" },
|
|
5149
|
+
{ word: "rm", desc: "\u5220\u9664\u8BA2\u9605" },
|
|
5150
|
+
{ word: "delete", desc: "\u5220\u9664\u8BA2\u9605" }
|
|
5151
|
+
],
|
|
5152
|
+
overwrite: [
|
|
5153
|
+
{ word: "on", desc: "\u542F\u7528\u8986\u5199" },
|
|
5154
|
+
{ word: "off", desc: "\u7981\u7528\u8986\u5199" },
|
|
5155
|
+
{ word: "enable", desc: "\u542F\u7528\u8986\u5199" },
|
|
5156
|
+
{ word: "disable", desc: "\u7981\u7528\u8986\u5199" }
|
|
5157
|
+
],
|
|
5158
|
+
directory: [{ word: "open", desc: "\u6253\u5F00\u76EE\u5F55" }]
|
|
5159
|
+
};
|
|
5160
|
+
var DIR_TARGETS = ["root", "subs", "logs", "data", "runtime", "kernel"];
|
|
5161
|
+
var UI_NAMES = ["zash", "dash", "yacd"];
|
|
5162
|
+
var SHELLS = ["zsh", "bash", "fish"];
|
|
5163
|
+
function buildZsh() {
|
|
5164
|
+
const lines = [
|
|
5165
|
+
"#compdef mihomo mhm mh mihomo-cli",
|
|
5166
|
+
"",
|
|
5167
|
+
'# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: \u5199\u5165 ~/.zsh/completions/_mihomo \u6216 eval "$(mihomo completion zsh)"\uFF09',
|
|
5168
|
+
"",
|
|
5169
|
+
"_mihomo() {",
|
|
5170
|
+
" local -a commands subcmds",
|
|
5171
|
+
" commands=(",
|
|
5172
|
+
...COMMAND_WORDS.map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
|
|
5173
|
+
" )",
|
|
5174
|
+
"",
|
|
5175
|
+
" _arguments -C \\",
|
|
5176
|
+
" '1: :->cmd' \\",
|
|
5177
|
+
" '*::arg:->args'",
|
|
5178
|
+
"",
|
|
5179
|
+
" case $state in",
|
|
5180
|
+
" cmd)",
|
|
5181
|
+
" _describe 'command' commands",
|
|
5182
|
+
" ;;",
|
|
5183
|
+
" args)",
|
|
5184
|
+
" case ${words[1]} in"
|
|
5185
|
+
];
|
|
5186
|
+
for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
|
|
5187
|
+
const aliases = group === "subscription" ? "subscription|sub|subs|subscriptions" : group === "overwrite" ? "overwrite|ow" : "directory|dir|dirs|directories";
|
|
5188
|
+
lines.push(` ${aliases})`);
|
|
5189
|
+
lines.push(" subcmds=(");
|
|
5190
|
+
for (const s of subs) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
|
|
5191
|
+
lines.push(" )");
|
|
5192
|
+
lines.push(" if (( CURRENT == 2 )); then");
|
|
5193
|
+
lines.push(" _describe 'subcommand' subcmds");
|
|
5194
|
+
lines.push(" else");
|
|
5195
|
+
lines.push(" _files");
|
|
5196
|
+
lines.push(" fi");
|
|
5197
|
+
lines.push(" ;;");
|
|
5198
|
+
}
|
|
5199
|
+
lines.push(
|
|
5200
|
+
" directory|dir|dirs|directories)",
|
|
5201
|
+
" if (( CURRENT == 3 )); then",
|
|
5202
|
+
` _values 'target' ${DIR_TARGETS.join(" ")}`,
|
|
5203
|
+
" fi",
|
|
5204
|
+
" ;;",
|
|
5205
|
+
" logs)",
|
|
5206
|
+
" _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
|
|
5207
|
+
" ;;",
|
|
5208
|
+
" ui)",
|
|
5209
|
+
` _values 'ui' ${UI_NAMES.join(" ")}`,
|
|
5210
|
+
" ;;",
|
|
5211
|
+
" kernel)",
|
|
5212
|
+
" _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:' '--no-mirror[\u76F4\u8FDE\u4E0B\u8F7D]'",
|
|
5213
|
+
" ;;",
|
|
5214
|
+
" reset)",
|
|
5215
|
+
` _values 'target' subs logs data runtime settings kernel overwrites service`,
|
|
5216
|
+
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
5217
|
+
" ;;",
|
|
5218
|
+
" completion)",
|
|
5219
|
+
` _values 'shell' ${SHELLS.join(" ")}`,
|
|
5220
|
+
" ;;",
|
|
5221
|
+
" *)",
|
|
5222
|
+
" _files",
|
|
5223
|
+
" ;;",
|
|
5224
|
+
" esac",
|
|
5225
|
+
" ;;",
|
|
5226
|
+
" esac",
|
|
5227
|
+
"}",
|
|
5228
|
+
"",
|
|
5229
|
+
'_mihomo "$@"'
|
|
5230
|
+
);
|
|
5231
|
+
return lines.join("\n");
|
|
5232
|
+
}
|
|
5233
|
+
function buildBash() {
|
|
5234
|
+
const top = COMMAND_WORDS.map((c) => c.word).join(" ");
|
|
5235
|
+
return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
|
|
5236
|
+
|
|
5237
|
+
_mihomo_completions() {
|
|
5238
|
+
local cur prev
|
|
5239
|
+
COMPREPLY=()
|
|
5240
|
+
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
5241
|
+
prev="\${COMP_WORDS[COMP_CWORD-1]}"
|
|
5242
|
+
|
|
5243
|
+
if [[ \${COMP_CWORD} -eq 1 ]]; then
|
|
5244
|
+
COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
|
|
5245
|
+
return 0
|
|
5246
|
+
fi
|
|
5247
|
+
|
|
5248
|
+
case "\${COMP_WORDS[1]}" in
|
|
5249
|
+
subscription|sub|subs|subscriptions)
|
|
5250
|
+
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
5251
|
+
COMPREPLY=( $(compgen -W "use add update remove rm delete" -- "\${cur}") )
|
|
5252
|
+
fi
|
|
5253
|
+
;;
|
|
5254
|
+
overwrite|ow)
|
|
5255
|
+
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
5256
|
+
COMPREPLY=( $(compgen -W "on off enable disable" -- "\${cur}") )
|
|
5257
|
+
fi
|
|
5258
|
+
;;
|
|
5259
|
+
directory|dir|dirs|directories)
|
|
5260
|
+
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
5261
|
+
COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
|
|
5262
|
+
elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
|
|
5263
|
+
COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
|
|
5264
|
+
fi
|
|
5265
|
+
;;
|
|
5266
|
+
logs)
|
|
5267
|
+
COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
|
|
5268
|
+
;;
|
|
5269
|
+
ui)
|
|
5270
|
+
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
5271
|
+
;;
|
|
5272
|
+
kernel)
|
|
5273
|
+
COMPREPLY=( $(compgen -W "--mirror --no-mirror" -- "\${cur}") )
|
|
5274
|
+
;;
|
|
5275
|
+
reset)
|
|
5276
|
+
COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
|
|
5277
|
+
;;
|
|
5278
|
+
completion)
|
|
5279
|
+
COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
|
|
5280
|
+
;;
|
|
5281
|
+
esac
|
|
5282
|
+
}
|
|
5283
|
+
complete -F _mihomo_completions mihomo mhm mh mihomo-cli
|
|
5284
|
+
`;
|
|
5285
|
+
}
|
|
5286
|
+
function buildFish() {
|
|
5287
|
+
const lines = [
|
|
5288
|
+
"# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
|
|
5289
|
+
"",
|
|
5290
|
+
"for cmd in mihomo mhm mh mihomo-cli"
|
|
5291
|
+
];
|
|
5292
|
+
for (const c of COMMAND_WORDS) {
|
|
5293
|
+
lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
|
|
5294
|
+
}
|
|
5295
|
+
const subAliases = {
|
|
5296
|
+
subscription: "subscription sub subs subscriptions",
|
|
5297
|
+
overwrite: "overwrite ow",
|
|
5298
|
+
directory: "directory dir dirs directories"
|
|
5299
|
+
};
|
|
5300
|
+
for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
|
|
5301
|
+
for (const s of subs) {
|
|
5302
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${subAliases[group]}" -a '${s.word}' -d '${s.desc}'`);
|
|
5303
|
+
}
|
|
5304
|
+
}
|
|
5305
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
|
|
5306
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
|
|
5307
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
|
|
5308
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
|
|
5309
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
|
|
5310
|
+
lines.push("end");
|
|
5311
|
+
return lines.join("\n");
|
|
5312
|
+
}
|
|
5313
|
+
function buildCompletionScript(shell) {
|
|
5314
|
+
switch (shell) {
|
|
5315
|
+
case "zsh":
|
|
5316
|
+
return buildZsh();
|
|
5317
|
+
case "bash":
|
|
5318
|
+
return buildBash();
|
|
5319
|
+
case "fish":
|
|
5320
|
+
return buildFish();
|
|
5321
|
+
default: {
|
|
5322
|
+
const suggestion = suggestSimilar(shell, [...SHELLS]);
|
|
5323
|
+
throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
|
|
5324
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
5325
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
|
|
5326
|
+
});
|
|
5327
|
+
}
|
|
5328
|
+
}
|
|
5329
|
+
}
|
|
5330
|
+
function cmdCompletion(args) {
|
|
5331
|
+
const shell = args[1];
|
|
5332
|
+
if (!shell) {
|
|
5333
|
+
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
5334
|
+
hint: [`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`, '\u5B89\u88C5: eval "$(mihomo completion zsh)"\uFF0C\u6216\u5199\u5165\u5BF9\u5E94 shell \u7684\u8865\u5168\u76EE\u5F55']
|
|
5335
|
+
});
|
|
5336
|
+
}
|
|
5337
|
+
console.log(buildCompletionScript(shell));
|
|
5338
|
+
}
|
|
5339
|
+
|
|
5340
|
+
// src/open.ts
|
|
5341
|
+
import { spawn } from "child_process";
|
|
5342
|
+
|
|
5343
|
+
// src/lifecycle.ts
|
|
5344
|
+
var silentSigint = false;
|
|
5345
|
+
function setSilentSigint(value) {
|
|
5346
|
+
silentSigint = value;
|
|
5347
|
+
}
|
|
5348
|
+
function isSilentSigint() {
|
|
5349
|
+
return silentSigint;
|
|
5350
|
+
}
|
|
5351
|
+
|
|
5352
|
+
// src/open.ts
|
|
5353
|
+
function openUrl(url) {
|
|
5354
|
+
try {
|
|
5355
|
+
const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
|
|
5356
|
+
child.unref();
|
|
5357
|
+
child.on("error", () => {
|
|
5358
|
+
});
|
|
5359
|
+
return true;
|
|
5360
|
+
} catch {
|
|
5361
|
+
return false;
|
|
5362
|
+
}
|
|
5363
|
+
}
|
|
5364
|
+
function openLogFile(logPath, label) {
|
|
5365
|
+
const displayLabel = label || logPath;
|
|
5366
|
+
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
|
|
5367
|
+
const success = openUrl(logPath);
|
|
5368
|
+
if (!success) {
|
|
5369
|
+
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
5370
|
+
}
|
|
5371
|
+
}
|
|
5372
|
+
function viewLogWithTail(logPath, options) {
|
|
5373
|
+
const follow = options?.follow;
|
|
5374
|
+
const lines = options?.lines || 100;
|
|
5375
|
+
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
5376
|
+
if (follow) {
|
|
5377
|
+
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
5378
|
+
} else {
|
|
5379
|
+
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
5380
|
+
`);
|
|
5381
|
+
}
|
|
5382
|
+
const tailArgs = [];
|
|
5383
|
+
if (follow) tailArgs.push("-f");
|
|
5384
|
+
tailArgs.push("-n", lines.toString());
|
|
5385
|
+
tailArgs.push(logPath);
|
|
5386
|
+
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5387
|
+
if (follow) setSilentSigint(true);
|
|
5388
|
+
tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
|
|
5389
|
+
tail.on("error", (e) => {
|
|
5390
|
+
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5391
|
+
process.exit(1);
|
|
5392
|
+
});
|
|
5393
|
+
}
|
|
5394
|
+
|
|
5395
|
+
// src/commands/shared.ts
|
|
5396
|
+
import readline from "readline";
|
|
5397
|
+
|
|
5398
|
+
// src/process-start.ts
|
|
5399
|
+
import fs9 from "fs";
|
|
5400
|
+
var TUN_MODE_POST_WAIT_MS = 500;
|
|
5401
|
+
function buildTunLaunchScript() {
|
|
5402
|
+
const binary = shellQuote(PATHS.mihomoBinary);
|
|
5403
|
+
const configFile = shellQuote(PATHS.configFile);
|
|
5404
|
+
const logFile = shellQuote(PATHS.logFile);
|
|
5405
|
+
const pidFile = shellQuote(PATHS.pidFile);
|
|
5406
|
+
const dataDir = shellQuote(DIRS.data);
|
|
5407
|
+
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
5408
|
+
return `#!/bin/bash
|
|
5409
|
+
BINARY=${binary}
|
|
5410
|
+
CONFIG_FILE=${configFile}
|
|
5411
|
+
LOG_FILE=${logFile}
|
|
5412
|
+
PID_FILE=${pidFile}
|
|
5413
|
+
DATA_DIR=${dataDir}
|
|
5414
|
+
KILL_PATTERN=${killPattern}
|
|
5415
|
+
|
|
5416
|
+
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
5417
|
+
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
5418
|
+
sleep 0.2
|
|
5419
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5420
|
+
|
|
5421
|
+
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
5422
|
+
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
5423
|
+
|
|
5424
|
+
# \u542F\u52A8
|
|
5425
|
+
cd /tmp
|
|
5426
|
+
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
5427
|
+
NEW_PID=$!
|
|
5428
|
+
echo \${NEW_PID} > "\${PID_FILE}"
|
|
5429
|
+
|
|
5430
|
+
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
5431
|
+
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
5432
|
+
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
5433
|
+
is_alive() {
|
|
5434
|
+
local stat
|
|
5435
|
+
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
5436
|
+
case "\${stat}" in
|
|
5437
|
+
Z*|'') return 1 ;;
|
|
5438
|
+
*) return 0 ;;
|
|
5439
|
+
esac
|
|
5440
|
+
}
|
|
5441
|
+
|
|
5442
|
+
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
5443
|
+
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
5444
|
+
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
5445
|
+
i=0
|
|
5446
|
+
while [ $i -lt 12 ]; do
|
|
5447
|
+
sleep 0.1
|
|
5448
|
+
is_alive \${NEW_PID} || break
|
|
5449
|
+
i=$((i+1))
|
|
5450
|
+
done
|
|
5451
|
+
if is_alive \${NEW_PID}; then
|
|
5452
|
+
exit 0
|
|
5453
|
+
fi
|
|
5454
|
+
|
|
5455
|
+
# \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
|
|
5456
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5457
|
+
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
5458
|
+
echo ""
|
|
5459
|
+
echo "--- \u65E5\u5FD7 ---"
|
|
5460
|
+
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
5461
|
+
exit 2
|
|
5462
|
+
`;
|
|
5463
|
+
}
|
|
5464
|
+
async function startTun() {
|
|
5465
|
+
ensureDirs();
|
|
5466
|
+
rotateAndCleanupLogs();
|
|
5467
|
+
if (!fs9.existsSync(PATHS.mihomoBinary)) {
|
|
5468
|
+
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
5469
|
+
}
|
|
5470
|
+
if (!fs9.existsSync(PATHS.configFile)) {
|
|
5471
|
+
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
5472
|
+
}
|
|
5473
|
+
const logFile = PATHS.logFile;
|
|
5474
|
+
if (fs9.existsSync(logFile)) {
|
|
5475
|
+
try {
|
|
5476
|
+
fs9.accessSync(logFile, fs9.constants.W_OK);
|
|
5477
|
+
} catch {
|
|
5478
|
+
try {
|
|
5479
|
+
fs9.unlinkSync(logFile);
|
|
5480
|
+
} catch {
|
|
5188
5481
|
}
|
|
5189
5482
|
}
|
|
5190
|
-
);
|
|
5191
|
-
disableServiceAutoStart();
|
|
5192
|
-
killResidualKernels();
|
|
5193
|
-
try {
|
|
5194
|
-
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5195
|
-
} catch {
|
|
5196
5483
|
}
|
|
5197
|
-
|
|
5198
|
-
|
|
5199
|
-
|
|
5200
|
-
const script = [
|
|
5201
|
-
"#!/bin/bash",
|
|
5202
|
-
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || true`,
|
|
5203
|
-
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5204
|
-
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
5205
|
-
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
5206
|
-
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
5207
|
-
"exit 0",
|
|
5208
|
-
""
|
|
5209
|
-
].join("\n");
|
|
5210
|
-
runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
|
|
5211
|
-
}
|
|
5212
|
-
function logOversized() {
|
|
5213
|
-
try {
|
|
5214
|
-
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5215
|
-
} catch {
|
|
5216
|
-
return false;
|
|
5484
|
+
const staleState = checkStaleState();
|
|
5485
|
+
if (staleState.needsCleanup) {
|
|
5486
|
+
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
5217
5487
|
}
|
|
5218
|
-
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
const
|
|
5226
|
-
if (
|
|
5227
|
-
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
const info = await probe.json();
|
|
5231
|
-
if (typeof info?.version !== "string") return false;
|
|
5232
|
-
const res = await fetch(`${CONTROLLER_BASE_URL}/configs?force=true`, {
|
|
5233
|
-
method: "PUT",
|
|
5234
|
-
headers,
|
|
5235
|
-
body: "{}",
|
|
5236
|
-
signal: controller.signal
|
|
5488
|
+
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
5489
|
+
runSudoScript(buildTunLaunchScript(), {
|
|
5490
|
+
action: "TUN \u542F\u52A8",
|
|
5491
|
+
file: "launch-tun.sh",
|
|
5492
|
+
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
5493
|
+
});
|
|
5494
|
+
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
5495
|
+
const finalPid = getPid();
|
|
5496
|
+
if (!finalPid || !isRunning()) {
|
|
5497
|
+
const tail = readLogTail();
|
|
5498
|
+
throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
|
|
5499
|
+
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
|
|
5237
5500
|
});
|
|
5238
|
-
return res.status === 204 || res.ok;
|
|
5239
|
-
} catch {
|
|
5240
|
-
return false;
|
|
5241
|
-
} finally {
|
|
5242
|
-
clearTimeout(timer);
|
|
5243
|
-
}
|
|
5244
|
-
}
|
|
5245
|
-
async function restartService() {
|
|
5246
|
-
if (!isServiceInstalled()) {
|
|
5247
|
-
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5248
5501
|
}
|
|
5249
|
-
|
|
5250
|
-
const target = shellQuote(serviceTarget());
|
|
5251
|
-
const dest = shellQuote(PATHS.userAgentPlist);
|
|
5252
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
5253
|
-
const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
|
|
5254
|
-
runLaunchctlSteps(
|
|
5255
|
-
[
|
|
5256
|
-
`if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
|
|
5257
|
-
` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
|
|
5258
|
-
"fi",
|
|
5259
|
-
`if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
|
|
5260
|
-
`launchctl enable ${target} 2>/dev/null || true`,
|
|
5261
|
-
`launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`
|
|
5262
|
-
],
|
|
5263
|
-
{ action: "\u91CD\u542F\u670D\u52A1", codeMessages: { 3: "\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" } }
|
|
5264
|
-
);
|
|
5265
|
-
cleanupOldLogs();
|
|
5266
|
-
return { hotReloaded: false };
|
|
5502
|
+
return { success: true, pid: finalPid, mode: "tun" };
|
|
5267
5503
|
}
|
|
5268
5504
|
|
|
5269
5505
|
// src/runtime.ts
|
|
@@ -5295,7 +5531,7 @@ async function launchOrRestart(mode) {
|
|
|
5295
5531
|
const { hotReloaded } = await restartService();
|
|
5296
5532
|
if (hotReloaded) return getServiceStatus().pid;
|
|
5297
5533
|
} else {
|
|
5298
|
-
startService();
|
|
5534
|
+
await startService();
|
|
5299
5535
|
}
|
|
5300
5536
|
return assertServiceHealthy();
|
|
5301
5537
|
}
|
|
@@ -5319,8 +5555,7 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
5319
5555
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5320
5556
|
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5321
5557
|
function createHttpClient(options = {}) {
|
|
5322
|
-
const { timeout = 6e4
|
|
5323
|
-
const authHeaders = secret ? { Authorization: `Bearer ${secret}` } : {};
|
|
5558
|
+
const { timeout = 6e4 } = options;
|
|
5324
5559
|
return {
|
|
5325
5560
|
async get(url, config) {
|
|
5326
5561
|
const controller = new AbortController();
|
|
@@ -5329,7 +5564,7 @@ function createHttpClient(options = {}) {
|
|
|
5329
5564
|
try {
|
|
5330
5565
|
const response = await fetch(url, {
|
|
5331
5566
|
signal,
|
|
5332
|
-
headers: { "User-Agent": `mihomo-cli/${VERSION}
|
|
5567
|
+
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5333
5568
|
});
|
|
5334
5569
|
if (!response.ok) {
|
|
5335
5570
|
const error = new Error(`HTTP ${response.status}`);
|
|
@@ -5378,6 +5613,31 @@ async function readBodyWithLimit(response, controller, limit) {
|
|
|
5378
5613
|
return Buffer.concat(chunks).toString("utf8");
|
|
5379
5614
|
}
|
|
5380
5615
|
|
|
5616
|
+
// src/spinner.ts
|
|
5617
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
5618
|
+
var INTERVAL_MS = 80;
|
|
5619
|
+
async function withSpinner(label, fn) {
|
|
5620
|
+
if (!process.stdout.isTTY) {
|
|
5621
|
+
console.log(label);
|
|
5622
|
+
return fn();
|
|
5623
|
+
}
|
|
5624
|
+
const start = Date.now();
|
|
5625
|
+
let frame = 0;
|
|
5626
|
+
const render = () => {
|
|
5627
|
+
const secs = ((Date.now() - start) / 1e3).toFixed(0);
|
|
5628
|
+
process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
|
|
5629
|
+
frame = (frame + 1) % FRAMES.length;
|
|
5630
|
+
};
|
|
5631
|
+
render();
|
|
5632
|
+
const timer = setInterval(render, INTERVAL_MS);
|
|
5633
|
+
try {
|
|
5634
|
+
return await fn();
|
|
5635
|
+
} finally {
|
|
5636
|
+
clearInterval(timer);
|
|
5637
|
+
process.stdout.write("\r\x1B[K");
|
|
5638
|
+
}
|
|
5639
|
+
}
|
|
5640
|
+
|
|
5381
5641
|
// src/subscription.ts
|
|
5382
5642
|
function isGithubUrl(url) {
|
|
5383
5643
|
return /github\.com|raw\.githubusercontent\.com/i.test(url);
|
|
@@ -5634,7 +5894,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5634
5894
|
)
|
|
5635
5895
|
);
|
|
5636
5896
|
try {
|
|
5637
|
-
await withTimeout(updatePromise, timeoutMs);
|
|
5897
|
+
await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
|
|
5638
5898
|
} catch (e) {
|
|
5639
5899
|
if (!(e instanceof TimeoutError)) throw e;
|
|
5640
5900
|
controller.abort();
|
|
@@ -5650,15 +5910,147 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5650
5910
|
return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
|
|
5651
5911
|
}
|
|
5652
5912
|
|
|
5913
|
+
// src/proxy-probe.ts
|
|
5914
|
+
import { execFile } from "child_process";
|
|
5915
|
+
import { promisify } from "util";
|
|
5916
|
+
var execFileAsync = promisify(execFile);
|
|
5917
|
+
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
5918
|
+
function isProbeSuccessStatus(code) {
|
|
5919
|
+
return code !== null && code >= 200 && code < 300;
|
|
5920
|
+
}
|
|
5921
|
+
async function probeProxyConnectivity(port, timeoutMs = 5e3) {
|
|
5922
|
+
const start = Date.now();
|
|
5923
|
+
try {
|
|
5924
|
+
const { stdout } = await execFileAsync(
|
|
5925
|
+
"curl",
|
|
5926
|
+
[
|
|
5927
|
+
"-x",
|
|
5928
|
+
`http://127.0.0.1:${port}`,
|
|
5929
|
+
"-s",
|
|
5930
|
+
"-o",
|
|
5931
|
+
"/dev/null",
|
|
5932
|
+
"-w",
|
|
5933
|
+
"%{http_code}",
|
|
5934
|
+
"--connect-timeout",
|
|
5935
|
+
"3",
|
|
5936
|
+
"--max-time",
|
|
5937
|
+
String(Math.ceil(timeoutMs / 1e3)),
|
|
5938
|
+
PROBE_URL
|
|
5939
|
+
],
|
|
5940
|
+
{ timeout: timeoutMs + 2e3 }
|
|
5941
|
+
);
|
|
5942
|
+
const code = Number.parseInt(stdout.trim(), 10);
|
|
5943
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
5944
|
+
const ok = isProbeSuccessStatus(statusCode);
|
|
5945
|
+
return {
|
|
5946
|
+
ok,
|
|
5947
|
+
statusCode,
|
|
5948
|
+
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
5949
|
+
durationMs: Date.now() - start
|
|
5950
|
+
};
|
|
5951
|
+
} catch (e) {
|
|
5952
|
+
const err = e;
|
|
5953
|
+
const stderr = err.stderr?.toString().trim();
|
|
5954
|
+
const lastLine = stderr ? stderr.split("\n").pop() : void 0;
|
|
5955
|
+
const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
5956
|
+
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
5957
|
+
}
|
|
5958
|
+
}
|
|
5959
|
+
|
|
5653
5960
|
// src/commands/status.ts
|
|
5654
|
-
|
|
5961
|
+
function connectivityHint(urgency) {
|
|
5962
|
+
if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
|
|
5963
|
+
if (urgency === "traffic-exhausted") return "\u8BA2\u9605\u6D41\u91CF\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
|
|
5964
|
+
return "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0C\u53EF\u5728 Web UI \u4E2D\u5207\u6362\u8282\u70B9 (mihomo ui)";
|
|
5965
|
+
}
|
|
5966
|
+
function trafficColor(line, urgency, total, upload, download) {
|
|
5967
|
+
if (urgency === "traffic-exhausted") return colors.red(line);
|
|
5968
|
+
if (total && total > 0) {
|
|
5969
|
+
const used = (upload || 0) + (download || 0);
|
|
5970
|
+
if (used / total >= 0.9) return colors.yellow(line);
|
|
5971
|
+
}
|
|
5972
|
+
return line;
|
|
5973
|
+
}
|
|
5974
|
+
function expireColor(line, urgency) {
|
|
5975
|
+
if (urgency === "expired") return colors.red(line);
|
|
5976
|
+
if (urgency === "expiring") return colors.yellow(line);
|
|
5977
|
+
return line;
|
|
5978
|
+
}
|
|
5979
|
+
function buildStatusJson(args) {
|
|
5980
|
+
const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
|
|
5981
|
+
return {
|
|
5982
|
+
version: VERSION,
|
|
5983
|
+
running: args.running,
|
|
5984
|
+
connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
|
|
5985
|
+
mode: args.info ? args.info.tun ? "tun" : "mixed" : null,
|
|
5986
|
+
carrier: args.kind,
|
|
5987
|
+
pid: args.pid,
|
|
5988
|
+
kernel: getKernelVersion(),
|
|
5989
|
+
kernelInstalled: hasKernel(),
|
|
5990
|
+
ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
|
|
5991
|
+
...args.info.mixedPort ? { mixed: args.info.mixedPort } : {},
|
|
5992
|
+
...args.info.httpPort ? { http: args.info.httpPort } : {},
|
|
5993
|
+
...args.info.socksPort ? { socks: args.info.socksPort } : {}
|
|
5994
|
+
} : {},
|
|
5995
|
+
subscription: args.activeSub ? {
|
|
5996
|
+
name: args.activeSub.name,
|
|
5997
|
+
proxies: args.info?.proxies ?? 0,
|
|
5998
|
+
proxyGroups: args.info?.proxyGroups ?? 0,
|
|
5999
|
+
...args.cached?.upload !== void 0 ? { upload: args.cached.upload } : {},
|
|
6000
|
+
...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
|
|
6001
|
+
...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
|
|
6002
|
+
...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
|
|
6003
|
+
urgency
|
|
6004
|
+
} : null,
|
|
6005
|
+
overwrite: { enabled: args.overwriteEnabled, files: args.overwriteFiles },
|
|
6006
|
+
service: {
|
|
6007
|
+
installed: args.service.installed,
|
|
6008
|
+
loaded: args.service.loaded,
|
|
6009
|
+
running: args.service.running,
|
|
6010
|
+
disabled: args.service.disabled,
|
|
6011
|
+
lastExitCode: args.service.lastExitCode,
|
|
6012
|
+
legacySystemInstall: args.legacy
|
|
6013
|
+
}
|
|
6014
|
+
};
|
|
6015
|
+
}
|
|
6016
|
+
async function printStatus(args = []) {
|
|
6017
|
+
const asJson = hasFlag(args, "-j", "--json");
|
|
5655
6018
|
const state = getRunningState();
|
|
5656
6019
|
const service = getServiceStatus();
|
|
5657
6020
|
const info = getConfigInfo();
|
|
5658
6021
|
const overwriteEnabled = isOverwriteEnabled();
|
|
5659
6022
|
const overwriteFiles = listOverwriteFile().files;
|
|
5660
6023
|
const activeSub = getActiveSubscription();
|
|
5661
|
-
const
|
|
6024
|
+
const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
|
|
6025
|
+
const legacy = detectLegacySystemInstall();
|
|
6026
|
+
const { running, pid, kind } = state;
|
|
6027
|
+
let probe = null;
|
|
6028
|
+
if (running && info?.mixedPort) {
|
|
6029
|
+
probe = await probeProxyConnectivity(info.mixedPort);
|
|
6030
|
+
}
|
|
6031
|
+
if (asJson) {
|
|
6032
|
+
console.log(
|
|
6033
|
+
JSON.stringify(
|
|
6034
|
+
buildStatusJson({
|
|
6035
|
+
running,
|
|
6036
|
+
kind,
|
|
6037
|
+
pid,
|
|
6038
|
+
probe,
|
|
6039
|
+
info,
|
|
6040
|
+
activeSub,
|
|
6041
|
+
cached,
|
|
6042
|
+
overwriteEnabled,
|
|
6043
|
+
overwriteFiles: overwriteFiles.map((f) => f.name),
|
|
6044
|
+
service,
|
|
6045
|
+
legacy
|
|
6046
|
+
}),
|
|
6047
|
+
null,
|
|
6048
|
+
2
|
|
6049
|
+
)
|
|
6050
|
+
);
|
|
6051
|
+
return;
|
|
6052
|
+
}
|
|
6053
|
+
const urgency = cached ? subscriptionUrgency(cached) : null;
|
|
5662
6054
|
console.log("");
|
|
5663
6055
|
let modeLabel = "";
|
|
5664
6056
|
if (info) {
|
|
@@ -5666,17 +6058,30 @@ async function printStatus() {
|
|
|
5666
6058
|
const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
|
|
5667
6059
|
modeLabel = colors.cyan(` (${mode}${carrier})`);
|
|
5668
6060
|
}
|
|
5669
|
-
|
|
6061
|
+
let statusText;
|
|
6062
|
+
if (!running) {
|
|
6063
|
+
statusText = colors.yellow("\u4E0D\u5728\u8FD0\u884C");
|
|
6064
|
+
} else if (probe && !probe.ok) {
|
|
6065
|
+
statusText = colors.yellow("\u25CF \u8FD0\u884C\u4E2D\uFF08\u4EE3\u7406\u4E0D\u901A\uFF09");
|
|
6066
|
+
} else {
|
|
6067
|
+
statusText = colors.green("\u25CF \u8FD0\u884C\u4E2D");
|
|
6068
|
+
}
|
|
5670
6069
|
console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
|
|
6070
|
+
if (running && probe && !probe.ok) {
|
|
6071
|
+
console.log(colors.yellow(` \u5F02\u5E38: ${connectivityHint(urgency)}`));
|
|
6072
|
+
}
|
|
5671
6073
|
if (!running && service.installed && !service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
|
|
5672
6074
|
console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
|
|
5673
6075
|
console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
|
|
5674
6076
|
}
|
|
5675
|
-
|
|
6077
|
+
const kernelVersion = getKernelVersion();
|
|
6078
|
+
console.log(
|
|
6079
|
+
kernelVersion ? `${colors.gray("\u5185\u6838: ")}${kernelVersion}` : `${colors.gray("\u5185\u6838: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(\u4E0B\u8F7D: mihomo kernel)")}`
|
|
6080
|
+
);
|
|
5676
6081
|
if (pid) {
|
|
5677
6082
|
console.log(`${colors.gray("PID: ")}${pid}`);
|
|
5678
|
-
if (kind === "tun" && processInfo) {
|
|
5679
|
-
console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
|
|
6083
|
+
if (kind === "tun" && state.processInfo) {
|
|
6084
|
+
console.log(`${colors.gray("\u5185\u5B58: ")}${state.processInfo.memory}`);
|
|
5680
6085
|
}
|
|
5681
6086
|
}
|
|
5682
6087
|
if (info) {
|
|
@@ -5698,16 +6103,15 @@ async function printStatus() {
|
|
|
5698
6103
|
subLine += ` (${formatProxySummary(info)})`;
|
|
5699
6104
|
}
|
|
5700
6105
|
console.log(subLine);
|
|
5701
|
-
const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
|
|
5702
6106
|
const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
|
|
5703
6107
|
if (traffic) {
|
|
5704
|
-
console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6108
|
+
console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
|
|
5705
6109
|
}
|
|
5706
6110
|
if (cached?.expire !== void 0) {
|
|
5707
|
-
console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
|
|
6111
|
+
console.log(`${colors.gray("\u5230\u671F: ")}${expireColor(formatTimestamp(cached.expire), urgency)}`);
|
|
5708
6112
|
}
|
|
5709
6113
|
} else {
|
|
5710
|
-
console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E`);
|
|
6114
|
+
console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
|
|
5711
6115
|
}
|
|
5712
6116
|
if (overwriteEnabled && overwriteFiles.length > 0) {
|
|
5713
6117
|
const names = overwriteFiles.map((f) => f.name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6").join(", ");
|
|
@@ -5717,11 +6121,10 @@ async function printStatus() {
|
|
|
5717
6121
|
} else {
|
|
5718
6122
|
console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
|
|
5719
6123
|
}
|
|
5720
|
-
printServiceLines(service);
|
|
6124
|
+
printServiceLines(service, legacy);
|
|
5721
6125
|
console.log("");
|
|
5722
6126
|
}
|
|
5723
|
-
function printServiceLines(service) {
|
|
5724
|
-
const legacy = detectLegacySystemInstall();
|
|
6127
|
+
function printServiceLines(service, legacy) {
|
|
5725
6128
|
if (!service.installed && !service.loaded) {
|
|
5726
6129
|
console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
|
|
5727
6130
|
} else if (!service.installed) {
|
|
@@ -5905,12 +6308,12 @@ function printDirectoryInfo() {
|
|
|
5905
6308
|
console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
|
|
5906
6309
|
console.log("");
|
|
5907
6310
|
}
|
|
5908
|
-
var
|
|
6311
|
+
var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
|
|
5909
6312
|
async function cmdDirectory(args) {
|
|
5910
|
-
await dispatchSubcommand(args,
|
|
6313
|
+
await dispatchSubcommand(args, SUBCOMMANDS2, {
|
|
5911
6314
|
fallback: printDirectoryInfo,
|
|
5912
6315
|
onUnknown: (action) => {
|
|
5913
|
-
const names =
|
|
6316
|
+
const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
5914
6317
|
const suggestion = suggestSimilar(action, names);
|
|
5915
6318
|
throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
|
|
5916
6319
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
|
|
@@ -5919,9 +6322,188 @@ async function cmdDirectory(args) {
|
|
|
5919
6322
|
});
|
|
5920
6323
|
}
|
|
5921
6324
|
|
|
5922
|
-
// src/
|
|
6325
|
+
// src/commands/doctor.ts
|
|
5923
6326
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
5924
6327
|
import fs10 from "fs";
|
|
6328
|
+
function isPortListening(port) {
|
|
6329
|
+
try {
|
|
6330
|
+
const r = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
6331
|
+
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
6332
|
+
} catch {
|
|
6333
|
+
return false;
|
|
6334
|
+
}
|
|
6335
|
+
}
|
|
6336
|
+
function collectChecks() {
|
|
6337
|
+
const checks = [];
|
|
6338
|
+
const push = (name, status, detail, fix) => {
|
|
6339
|
+
checks.push({ name, status, detail, fix });
|
|
6340
|
+
};
|
|
6341
|
+
if (!hasKernel()) {
|
|
6342
|
+
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
6343
|
+
} else {
|
|
6344
|
+
const v = getKernelVersion();
|
|
6345
|
+
const r = spawnSync5(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6346
|
+
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
6347
|
+
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
6348
|
+
} else {
|
|
6349
|
+
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
|
|
6350
|
+
}
|
|
6351
|
+
}
|
|
6352
|
+
try {
|
|
6353
|
+
fs10.accessSync(USER_DATA_DIR, fs10.constants.W_OK);
|
|
6354
|
+
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
6355
|
+
} catch {
|
|
6356
|
+
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
6357
|
+
}
|
|
6358
|
+
if (fs10.existsSync(PATHS.settingsFile)) {
|
|
6359
|
+
try {
|
|
6360
|
+
const parsed = JSON.parse(fs10.readFileSync(PATHS.settingsFile, "utf8"));
|
|
6361
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
6362
|
+
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
6363
|
+
} else {
|
|
6364
|
+
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
6365
|
+
}
|
|
6366
|
+
} catch {
|
|
6367
|
+
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "JSON \u635F\u574F\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
6368
|
+
}
|
|
6369
|
+
} else {
|
|
6370
|
+
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
|
|
6371
|
+
}
|
|
6372
|
+
const subs = getSubscriptionsWithCache();
|
|
6373
|
+
const active = getActiveSubscription();
|
|
6374
|
+
if (subs.length === 0) {
|
|
6375
|
+
push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
|
|
6376
|
+
} else {
|
|
6377
|
+
push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
|
|
6378
|
+
if (active) {
|
|
6379
|
+
if (!readSubscriptionRawConfig(active.name)) {
|
|
6380
|
+
push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
|
|
6381
|
+
} else {
|
|
6382
|
+
push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
|
|
6383
|
+
}
|
|
6384
|
+
const cached = subs.find((s) => s.name === active.name);
|
|
6385
|
+
if (cached?.updated_at) {
|
|
6386
|
+
const rel = formatRelativeTime(cached.updated_at);
|
|
6387
|
+
const intervalH = resolveUpdateInterval(cached.url, cached.update_interval);
|
|
6388
|
+
const ageH = (Date.now() - new Date(cached.updated_at).getTime()) / 36e5;
|
|
6389
|
+
if (ageH > intervalH) {
|
|
6390
|
+
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${intervalH} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
|
|
6391
|
+
} else {
|
|
6392
|
+
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
|
|
6393
|
+
}
|
|
6394
|
+
}
|
|
6395
|
+
}
|
|
6396
|
+
}
|
|
6397
|
+
const service = getServiceStatus();
|
|
6398
|
+
const legacy = detectLegacySystemInstall();
|
|
6399
|
+
if (legacy) {
|
|
6400
|
+
push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
|
|
6401
|
+
} else if (!service.installed && !service.loaded) {
|
|
6402
|
+
push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo install");
|
|
6403
|
+
} else if (!service.installed) {
|
|
6404
|
+
push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo uninstall");
|
|
6405
|
+
} else if (service.running) {
|
|
6406
|
+
const exitNote = service.lastExitCode !== null && service.lastExitCode !== 0 ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${service.lastExitCode}\uFF09` : "";
|
|
6407
|
+
push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${exitNote}`);
|
|
6408
|
+
if (service.lastExitCode !== null && service.lastExitCode !== 0) {
|
|
6409
|
+
push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
|
|
6410
|
+
}
|
|
6411
|
+
} else {
|
|
6412
|
+
push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
|
|
6413
|
+
}
|
|
6414
|
+
const state = getRunningState();
|
|
6415
|
+
const info = getConfigInfo();
|
|
6416
|
+
const mixedPort = info?.mixedPort ?? 7890;
|
|
6417
|
+
if (state.running) {
|
|
6418
|
+
if (isPortListening(mixedPort)) {
|
|
6419
|
+
push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
|
|
6420
|
+
} else {
|
|
6421
|
+
push("\u7AEF\u53E3", "fail", `\u5185\u6838\u5728\u8DD1\u4F46 ${mixedPort} \u672A\u76D1\u542C`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
|
|
6422
|
+
}
|
|
6423
|
+
} else if (isPortListening(mixedPort)) {
|
|
6424
|
+
push("\u7AEF\u53E3", "warn", `${mixedPort} \u88AB\u5176\u4ED6\u8FDB\u7A0B\u5360\u7528\uFF0Cstart \u4F1A\u5931\u8D25`, `lsof -nP -iTCP:${mixedPort} \u67E5\u770B\u5360\u7528\u8005`);
|
|
6425
|
+
} else {
|
|
6426
|
+
push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
|
|
6427
|
+
}
|
|
6428
|
+
if (active) {
|
|
6429
|
+
try {
|
|
6430
|
+
const mode = info?.tun ? "tun" : "mixed";
|
|
6431
|
+
prepareConfigForStart(mode, active.name);
|
|
6432
|
+
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u53EF\u6B63\u5E38\u6784\u5EFA\uFF08${mode}\uFF09`);
|
|
6433
|
+
} catch (e) {
|
|
6434
|
+
push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start");
|
|
6435
|
+
}
|
|
6436
|
+
} else {
|
|
6437
|
+
push("\u914D\u7F6E\u6784\u5EFA", "warn", "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
|
|
6438
|
+
}
|
|
6439
|
+
if (state.running && info?.mixedPort) {
|
|
6440
|
+
const probe = probeProxyConnectivitySyncShim(info.mixedPort);
|
|
6441
|
+
if (probe.ok) {
|
|
6442
|
+
push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
|
|
6443
|
+
} else {
|
|
6444
|
+
push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
|
|
6445
|
+
}
|
|
6446
|
+
} else {
|
|
6447
|
+
push("\u4EE3\u7406\u8FDE\u901A", "ok", "\u672A\u8FD0\u884C\uFF0C\u8DF3\u8FC7");
|
|
6448
|
+
}
|
|
6449
|
+
return checks;
|
|
6450
|
+
}
|
|
6451
|
+
function probeProxyConnectivitySyncShim(port) {
|
|
6452
|
+
const start = Date.now();
|
|
6453
|
+
try {
|
|
6454
|
+
const r = spawnSync5(
|
|
6455
|
+
"curl",
|
|
6456
|
+
[
|
|
6457
|
+
"-x",
|
|
6458
|
+
`http://127.0.0.1:${port}`,
|
|
6459
|
+
"-s",
|
|
6460
|
+
"-o",
|
|
6461
|
+
"/dev/null",
|
|
6462
|
+
"-w",
|
|
6463
|
+
"%{http_code}",
|
|
6464
|
+
"--connect-timeout",
|
|
6465
|
+
"3",
|
|
6466
|
+
"--max-time",
|
|
6467
|
+
"5",
|
|
6468
|
+
"https://www.gstatic.com/generate_204"
|
|
6469
|
+
],
|
|
6470
|
+
{ encoding: "utf8", timeout: 8e3 }
|
|
6471
|
+
);
|
|
6472
|
+
const code = Number.parseInt((r.stdout || "").trim(), 10);
|
|
6473
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
6474
|
+
const ok = statusCode !== null && statusCode >= 200 && statusCode < 300;
|
|
6475
|
+
return { ok, statusCode, error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`, durationMs: Date.now() - start };
|
|
6476
|
+
} catch (e) {
|
|
6477
|
+
return { ok: false, statusCode: null, error: e.message, durationMs: Date.now() - start };
|
|
6478
|
+
}
|
|
6479
|
+
}
|
|
6480
|
+
async function cmdDoctor() {
|
|
6481
|
+
const checks = collectChecks();
|
|
6482
|
+
console.log("");
|
|
6483
|
+
for (const c of checks) {
|
|
6484
|
+
const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : colors.red("\u2717");
|
|
6485
|
+
console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
|
|
6486
|
+
if (c.status !== "ok" && c.fix) {
|
|
6487
|
+
console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
|
|
6488
|
+
}
|
|
6489
|
+
}
|
|
6490
|
+
const ok = checks.filter((c) => c.status === "ok").length;
|
|
6491
|
+
const warn = checks.filter((c) => c.status === "warn").length;
|
|
6492
|
+
const fail = checks.filter((c) => c.status === "fail").length;
|
|
6493
|
+
console.log("");
|
|
6494
|
+
console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38`);
|
|
6495
|
+
console.log("");
|
|
6496
|
+
if (fail > 0) {
|
|
6497
|
+
throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
|
|
6498
|
+
label: "\u4F53\u68C0\u672A\u901A\u8FC7",
|
|
6499
|
+
hint: checks.filter((c) => c.status === "fail" && c.fix).map((c) => `${c.name}: ${c.fix}`)
|
|
6500
|
+
});
|
|
6501
|
+
}
|
|
6502
|
+
}
|
|
6503
|
+
|
|
6504
|
+
// src/kernel.ts
|
|
6505
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6506
|
+
import fs11 from "fs";
|
|
5925
6507
|
import path7 from "path";
|
|
5926
6508
|
|
|
5927
6509
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
@@ -6060,10 +6642,10 @@ async function checkUpdate() {
|
|
|
6060
6642
|
}
|
|
6061
6643
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
6062
6644
|
if (maxDepth <= 0) return null;
|
|
6063
|
-
const files =
|
|
6645
|
+
const files = fs11.readdirSync(dir);
|
|
6064
6646
|
for (const f of files) {
|
|
6065
6647
|
const fullPath = path7.join(dir, f);
|
|
6066
|
-
const stat =
|
|
6648
|
+
const stat = fs11.lstatSync(fullPath);
|
|
6067
6649
|
if (stat.isDirectory()) {
|
|
6068
6650
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
6069
6651
|
if (found) return found;
|
|
@@ -6100,7 +6682,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6100
6682
|
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
6101
6683
|
}
|
|
6102
6684
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
6103
|
-
const curlResult =
|
|
6685
|
+
const curlResult = spawnSync6(
|
|
6104
6686
|
"curl",
|
|
6105
6687
|
[
|
|
6106
6688
|
"-L",
|
|
@@ -6129,19 +6711,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6129
6711
|
}
|
|
6130
6712
|
if (curlResult.status !== 0) {
|
|
6131
6713
|
try {
|
|
6132
|
-
|
|
6714
|
+
fs11.unlinkSync(tempPath);
|
|
6133
6715
|
} catch {
|
|
6134
6716
|
}
|
|
6135
6717
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
6136
6718
|
}
|
|
6137
|
-
if (!
|
|
6719
|
+
if (!fs11.existsSync(tempPath)) {
|
|
6138
6720
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
6139
6721
|
}
|
|
6140
6722
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
6141
|
-
const actual =
|
|
6723
|
+
const actual = fs11.statSync(tempPath).size;
|
|
6142
6724
|
if (actual !== asset.size) {
|
|
6143
6725
|
try {
|
|
6144
|
-
|
|
6726
|
+
fs11.unlinkSync(tempPath);
|
|
6145
6727
|
} catch {
|
|
6146
6728
|
}
|
|
6147
6729
|
throw new Error(
|
|
@@ -6157,7 +6739,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6157
6739
|
let extractedBinary = null;
|
|
6158
6740
|
try {
|
|
6159
6741
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
6160
|
-
const listResult =
|
|
6742
|
+
const listResult = spawnSync6("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6161
6743
|
if (listResult.error) throw listResult.error;
|
|
6162
6744
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
6163
6745
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6165,7 +6747,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6165
6747
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
6166
6748
|
}
|
|
6167
6749
|
}
|
|
6168
|
-
const typeResult =
|
|
6750
|
+
const typeResult = spawnSync6("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6169
6751
|
if (typeResult.error) throw typeResult.error;
|
|
6170
6752
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
6171
6753
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6174,7 +6756,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6174
6756
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
6175
6757
|
}
|
|
6176
6758
|
}
|
|
6177
|
-
const tarResult =
|
|
6759
|
+
const tarResult = spawnSync6("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
|
|
6178
6760
|
stdio: ["ignore", "ignore", "inherit"],
|
|
6179
6761
|
timeout: 6e4
|
|
6180
6762
|
});
|
|
@@ -6183,15 +6765,15 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6183
6765
|
} else if (tempPath.endsWith(".gz")) {
|
|
6184
6766
|
const baseName = path7.basename(tempPath, ".gz");
|
|
6185
6767
|
const outputPath = path7.join(extractPath, baseName);
|
|
6186
|
-
const gzipResult =
|
|
6768
|
+
const gzipResult = spawnSync6("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
6187
6769
|
if (gzipResult.error) throw gzipResult.error;
|
|
6188
6770
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
6189
|
-
|
|
6771
|
+
fs11.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
6190
6772
|
extractedBinary = outputPath;
|
|
6191
6773
|
}
|
|
6192
6774
|
} catch (e) {
|
|
6193
6775
|
try {
|
|
6194
|
-
|
|
6776
|
+
fs11.unlinkSync(tempPath);
|
|
6195
6777
|
} catch {
|
|
6196
6778
|
}
|
|
6197
6779
|
throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
|
|
@@ -6199,35 +6781,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6199
6781
|
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
6200
6782
|
if (!foundBinary) {
|
|
6201
6783
|
try {
|
|
6202
|
-
|
|
6784
|
+
fs11.unlinkSync(tempPath);
|
|
6203
6785
|
} catch {
|
|
6204
6786
|
}
|
|
6205
6787
|
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
6206
6788
|
}
|
|
6207
6789
|
const targetPath = PATHS.mihomoBinary;
|
|
6208
6790
|
if (foundBinary !== targetPath) {
|
|
6209
|
-
if (
|
|
6210
|
-
|
|
6791
|
+
if (fs11.existsSync(targetPath)) {
|
|
6792
|
+
fs11.chmodSync(targetPath, 493);
|
|
6211
6793
|
try {
|
|
6212
|
-
|
|
6794
|
+
fs11.unlinkSync(targetPath);
|
|
6213
6795
|
} catch {
|
|
6214
6796
|
}
|
|
6215
6797
|
}
|
|
6216
|
-
|
|
6798
|
+
fs11.renameSync(foundBinary, targetPath);
|
|
6217
6799
|
}
|
|
6218
|
-
|
|
6800
|
+
fs11.chmodSync(targetPath, 493);
|
|
6219
6801
|
if (progressCallback) {
|
|
6220
6802
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
6221
6803
|
}
|
|
6222
|
-
const check =
|
|
6804
|
+
const check = spawnSync6(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6223
6805
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
6224
6806
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
6225
6807
|
try {
|
|
6226
|
-
|
|
6808
|
+
fs11.unlinkSync(targetPath);
|
|
6227
6809
|
} catch {
|
|
6228
6810
|
}
|
|
6229
6811
|
try {
|
|
6230
|
-
|
|
6812
|
+
fs11.unlinkSync(tempPath);
|
|
6231
6813
|
} catch {
|
|
6232
6814
|
}
|
|
6233
6815
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
|
|
@@ -6235,7 +6817,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6235
6817
|
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
6236
6818
|
}
|
|
6237
6819
|
try {
|
|
6238
|
-
|
|
6820
|
+
fs11.unlinkSync(tempPath);
|
|
6239
6821
|
} catch {
|
|
6240
6822
|
}
|
|
6241
6823
|
clearKernelVersionCache();
|
|
@@ -6262,28 +6844,23 @@ function assertKnownKernelFlags(args) {
|
|
|
6262
6844
|
}
|
|
6263
6845
|
async function cmdKernel(args) {
|
|
6264
6846
|
assertKnownKernelFlags(args);
|
|
6265
|
-
const
|
|
6847
|
+
const savedMirror = readSettings().kernel_mirror ?? null;
|
|
6848
|
+
const mirrorInfo = parseMirrorArg(args, savedMirror);
|
|
6266
6849
|
const effectiveMirror = mirrorInfo.mirror;
|
|
6850
|
+
if (mirrorInfo.remember) {
|
|
6851
|
+
writeSettings({ kernel_mirror: mirrorInfo.mirror ?? void 0 });
|
|
6852
|
+
} else if (mirrorInfo.clearSaved && savedMirror) {
|
|
6853
|
+
writeSettings({ kernel_mirror: void 0 });
|
|
6854
|
+
}
|
|
6267
6855
|
if (effectiveMirror) {
|
|
6268
|
-
|
|
6856
|
+
const host = effectiveMirror.replace(/^https?:\/\//, "").replace(/\/$/, "");
|
|
6857
|
+
const note = mirrorInfo.remember ? "\u5DF2\u8BB0\u4F4F\u504F\u597D\uFF0C\u540E\u7EED\u9ED8\u8BA4\u8D70\u955C\u50CF\uFF08--no-mirror \u76F4\u8FDE\u5E76\u6E05\u9664\u504F\u597D\uFF09" : !mirrorInfo.isOverride ? "\u5DF2\u8BB0\u4F4F\u7684\u504F\u597D\uFF08--no-mirror \u76F4\u8FDE\u5E76\u6E05\u9664\u504F\u597D\uFF09" : "\u4EC5\u4E0B\u8F7D\u8D70\u955C\u50CF\uFF0C\u7248\u672C\u67E5\u8BE2\u6052\u76F4\u8FDE";
|
|
6858
|
+
console.log(`\u955C\u50CF: ${host} (${note})`);
|
|
6269
6859
|
console.log("");
|
|
6270
6860
|
}
|
|
6271
|
-
|
|
6861
|
+
let info;
|
|
6272
6862
|
try {
|
|
6273
|
-
|
|
6274
|
-
console.log(`\u5F53\u524D: ${info.current}`);
|
|
6275
|
-
console.log(`\u6700\u65B0: ${info.latest}`);
|
|
6276
|
-
if (!info.needsUpdate) {
|
|
6277
|
-
console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
|
|
6278
|
-
} else {
|
|
6279
|
-
console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
|
|
6280
|
-
const result = await downloadKernel((msg) => console.log(msg), mirrorInfo.mirror, info.release);
|
|
6281
|
-
console.log(`
|
|
6282
|
-
\u5DF2\u66F4\u65B0\u5230 ${result.version}`);
|
|
6283
|
-
if (getRunningState().running) {
|
|
6284
|
-
console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C mihomo start \u91CD\u542F\u540E\u751F\u6548"));
|
|
6285
|
-
}
|
|
6286
|
-
}
|
|
6863
|
+
info = await withSpinner("\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09", () => checkUpdate());
|
|
6287
6864
|
} catch (e) {
|
|
6288
6865
|
if (e instanceof CliError) throw e;
|
|
6289
6866
|
const err = e;
|
|
@@ -6298,12 +6875,25 @@ async function cmdKernel(args) {
|
|
|
6298
6875
|
hint.push(
|
|
6299
6876
|
"",
|
|
6300
6877
|
"\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
|
|
6301
|
-
" mihomo kernel --mirror [\u955C\u50CF] # \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09",
|
|
6878
|
+
" mihomo kernel --mirror [\u955C\u50CF] # \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09\uFF0C\u4E00\u6B21\u4F7F\u7528\u540E\u8BB0\u4F4F\u504F\u597D",
|
|
6302
6879
|
` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
|
|
6303
6880
|
);
|
|
6304
6881
|
}
|
|
6305
6882
|
throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
|
|
6306
6883
|
}
|
|
6884
|
+
console.log(`\u5F53\u524D: ${info.current}`);
|
|
6885
|
+
console.log(`\u6700\u65B0: ${info.latest}`);
|
|
6886
|
+
if (!info.needsUpdate) {
|
|
6887
|
+
console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
|
|
6888
|
+
} else {
|
|
6889
|
+
console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
|
|
6890
|
+
const result = await downloadKernel((msg) => console.log(msg), mirrorInfo.mirror, info.release);
|
|
6891
|
+
console.log(`
|
|
6892
|
+
\u5DF2\u66F4\u65B0\u5230 ${result.version}`);
|
|
6893
|
+
if (getRunningState().running) {
|
|
6894
|
+
console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5185\u6838\u4ECD\u662F\u65E7\u7248\u672C\uFF0C\u6267\u884C mihomo start \u91CD\u542F\u540E\u751F\u6548"));
|
|
6895
|
+
}
|
|
6896
|
+
}
|
|
6307
6897
|
}
|
|
6308
6898
|
|
|
6309
6899
|
// src/commands/log.ts
|
|
@@ -6420,19 +7010,19 @@ async function setOverwrite(enabled, args) {
|
|
|
6420
7010
|
console.log("");
|
|
6421
7011
|
printOverwriteList();
|
|
6422
7012
|
}
|
|
6423
|
-
var
|
|
7013
|
+
var SUBCOMMANDS3 = [
|
|
6424
7014
|
{ name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
|
|
6425
7015
|
{ name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
|
|
6426
7016
|
];
|
|
6427
7017
|
async function cmdOverwrite(args) {
|
|
6428
|
-
await dispatchSubcommand(args,
|
|
7018
|
+
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6429
7019
|
// 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
|
|
6430
7020
|
fallback: () => {
|
|
6431
7021
|
console.log("");
|
|
6432
7022
|
printOverwriteList();
|
|
6433
7023
|
},
|
|
6434
7024
|
onUnknown: (action) => {
|
|
6435
|
-
const names =
|
|
7025
|
+
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6436
7026
|
const suggestion = suggestSimilar(action, names);
|
|
6437
7027
|
throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
|
|
6438
7028
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
|
|
@@ -6449,30 +7039,30 @@ function removedCommand(name, version, hint) {
|
|
|
6449
7039
|
}
|
|
6450
7040
|
|
|
6451
7041
|
// src/commands/reset.ts
|
|
6452
|
-
import
|
|
7042
|
+
import fs13 from "fs";
|
|
6453
7043
|
|
|
6454
7044
|
// src/process-stop.ts
|
|
6455
|
-
import { spawnSync as
|
|
6456
|
-
import
|
|
7045
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7046
|
+
import fs12 from "fs";
|
|
6457
7047
|
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6458
7048
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
6459
7049
|
var BATCH_KILL_THRESHOLD = 3;
|
|
6460
7050
|
function clearRuntime() {
|
|
6461
|
-
if (
|
|
7051
|
+
if (fs12.existsSync(DIRS.runtime)) {
|
|
6462
7052
|
rmrf(DIRS.runtime);
|
|
6463
7053
|
}
|
|
6464
7054
|
ensureDirs();
|
|
6465
7055
|
}
|
|
6466
7056
|
function clearPid() {
|
|
6467
|
-
if (!
|
|
7057
|
+
if (!fs12.existsSync(PATHS.pidFile)) return;
|
|
6468
7058
|
if (isPidFileOwnedByRoot()) {
|
|
6469
7059
|
try {
|
|
6470
|
-
|
|
7060
|
+
spawnSync7("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
6471
7061
|
} catch {
|
|
6472
7062
|
}
|
|
6473
7063
|
} else {
|
|
6474
7064
|
try {
|
|
6475
|
-
|
|
7065
|
+
fs12.unlinkSync(PATHS.pidFile);
|
|
6476
7066
|
} catch {
|
|
6477
7067
|
}
|
|
6478
7068
|
}
|
|
@@ -6490,7 +7080,7 @@ function killAllMihomo(forceSudo = false) {
|
|
|
6490
7080
|
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
6491
7081
|
const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
|
|
6492
7082
|
try {
|
|
6493
|
-
const result =
|
|
7083
|
+
const result = spawnSync7(argv[0], argv[1], options);
|
|
6494
7084
|
if (result.error) return false;
|
|
6495
7085
|
return result.status === 0 || result.status === 1;
|
|
6496
7086
|
} catch {
|
|
@@ -6567,9 +7157,9 @@ var RESET_TARGETS = [
|
|
|
6567
7157
|
label: "\u8BA2\u9605",
|
|
6568
7158
|
paths: () => [DIRS.subscriptions],
|
|
6569
7159
|
needsStop: true,
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
|
|
7160
|
+
onAfter: () => {
|
|
7161
|
+
writeSettings({ subscriptions: void 0, active_subscription: void 0 });
|
|
7162
|
+
}
|
|
6573
7163
|
},
|
|
6574
7164
|
{
|
|
6575
7165
|
id: "logs",
|
|
@@ -6619,8 +7209,8 @@ var RESET_TARGETS = [
|
|
|
6619
7209
|
label: "\u8986\u5199",
|
|
6620
7210
|
paths: () => {
|
|
6621
7211
|
const dir = USER_DATA_DIR;
|
|
6622
|
-
if (!
|
|
6623
|
-
return
|
|
7212
|
+
if (!fs13.existsSync(dir)) return [];
|
|
7213
|
+
return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
6624
7214
|
},
|
|
6625
7215
|
needsStop: false
|
|
6626
7216
|
},
|
|
@@ -6633,9 +7223,9 @@ var RESET_TARGETS = [
|
|
|
6633
7223
|
// onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
|
|
6634
7224
|
paths: () => [],
|
|
6635
7225
|
needsStop: false,
|
|
6636
|
-
onAfter: () => {
|
|
7226
|
+
onAfter: async () => {
|
|
6637
7227
|
const st = getServiceStatus();
|
|
6638
|
-
if (st.installed || st.loaded) uninstallService();
|
|
7228
|
+
if (st.installed || st.loaded) await uninstallService();
|
|
6639
7229
|
if (detectLegacySystemInstall()) cleanupLegacyInstallOrThrow();
|
|
6640
7230
|
},
|
|
6641
7231
|
checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
|
|
@@ -6731,9 +7321,9 @@ async function cmdReset(args) {
|
|
|
6731
7321
|
if ((uninstallsService || stopsService) && serviceActive) {
|
|
6732
7322
|
try {
|
|
6733
7323
|
if (uninstallsService) {
|
|
6734
|
-
uninstallService();
|
|
7324
|
+
await uninstallService();
|
|
6735
7325
|
} else {
|
|
6736
|
-
stopService();
|
|
7326
|
+
await stopService();
|
|
6737
7327
|
}
|
|
6738
7328
|
} catch (e) {
|
|
6739
7329
|
if (e instanceof CliError) throw e;
|
|
@@ -6761,7 +7351,7 @@ async function cmdReset(args) {
|
|
|
6761
7351
|
}
|
|
6762
7352
|
for (const t of targets) {
|
|
6763
7353
|
for (const p of t.paths()) {
|
|
6764
|
-
if (
|
|
7354
|
+
if (fs13.existsSync(p)) {
|
|
6765
7355
|
try {
|
|
6766
7356
|
rmrf(p);
|
|
6767
7357
|
} catch (e) {
|
|
@@ -6769,7 +7359,7 @@ async function cmdReset(args) {
|
|
|
6769
7359
|
}
|
|
6770
7360
|
}
|
|
6771
7361
|
}
|
|
6772
|
-
t.onAfter?.();
|
|
7362
|
+
await t.onAfter?.();
|
|
6773
7363
|
}
|
|
6774
7364
|
ensureDirs();
|
|
6775
7365
|
if (targets.some((t) => t.id === "settings")) {
|
|
@@ -6779,7 +7369,7 @@ async function cmdReset(args) {
|
|
|
6779
7369
|
}
|
|
6780
7370
|
|
|
6781
7371
|
// src/commands/service.ts
|
|
6782
|
-
import
|
|
7372
|
+
import fs14 from "fs";
|
|
6783
7373
|
async function handleLegacyInstall() {
|
|
6784
7374
|
if (!detectLegacySystemInstall()) return;
|
|
6785
7375
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
|
|
@@ -6796,7 +7386,7 @@ async function cmdInstall(_args) {
|
|
|
6796
7386
|
}
|
|
6797
7387
|
await handleLegacyInstall();
|
|
6798
7388
|
const wasRunning = getServiceStatus().running;
|
|
6799
|
-
installService(wasRunning);
|
|
7389
|
+
await installService(wasRunning);
|
|
6800
7390
|
console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
|
|
6801
7391
|
console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
|
|
6802
7392
|
console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
|
|
@@ -6814,7 +7404,7 @@ async function cmdInstall(_args) {
|
|
|
6814
7404
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
6815
7405
|
} else {
|
|
6816
7406
|
console.log("\u542F\u52A8: mihomo start");
|
|
6817
|
-
if (!
|
|
7407
|
+
if (!fs14.existsSync(PATHS.configFile)) {
|
|
6818
7408
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
6819
7409
|
}
|
|
6820
7410
|
}
|
|
@@ -6833,7 +7423,7 @@ async function cmdUninstall(_args) {
|
|
|
6833
7423
|
console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
|
|
6834
7424
|
}
|
|
6835
7425
|
if (status.installed || status.loaded) {
|
|
6836
|
-
uninstallService();
|
|
7426
|
+
await uninstallService();
|
|
6837
7427
|
console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
|
|
6838
7428
|
}
|
|
6839
7429
|
if (legacy) {
|
|
@@ -6879,7 +7469,7 @@ async function cmdStop(args) {
|
|
|
6879
7469
|
console.log(colors.green("\u5DF2\u505C\u6B62"));
|
|
6880
7470
|
return;
|
|
6881
7471
|
}
|
|
6882
|
-
stopService();
|
|
7472
|
+
await stopService();
|
|
6883
7473
|
const remaining = getMihomoPids();
|
|
6884
7474
|
if (remaining.length > 0) {
|
|
6885
7475
|
throw new CliError(remaining.join(", "), {
|
|
@@ -6909,7 +7499,8 @@ function printSubscriptionList() {
|
|
|
6909
7499
|
const activeSub = getActiveSubscription();
|
|
6910
7500
|
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6911
7501
|
subs.forEach((s, i) => {
|
|
6912
|
-
const
|
|
7502
|
+
const rel = formatRelativeTime(s.updated_at);
|
|
7503
|
+
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6913
7504
|
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6914
7505
|
const interval = resolveUpdateInterval(s.url, s.update_interval);
|
|
6915
7506
|
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
@@ -6956,7 +7547,7 @@ async function subAdd(args) {
|
|
|
6956
7547
|
console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
|
|
6957
7548
|
addSubscription(url, name);
|
|
6958
7549
|
try {
|
|
6959
|
-
const info = await downloadSubscription(url, name);
|
|
7550
|
+
const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
|
|
6960
7551
|
setDefaultSubscription(name);
|
|
6961
7552
|
console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
|
|
6962
7553
|
} catch (e) {
|
|
@@ -6975,7 +7566,7 @@ async function subUpdate(args) {
|
|
|
6975
7566
|
}
|
|
6976
7567
|
if (!name) {
|
|
6977
7568
|
console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
|
|
6978
|
-
const results = await Promise.all(subs.map((sub) => tryUpdateOne(sub)));
|
|
7569
|
+
const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
|
|
6979
7570
|
let ok = 0;
|
|
6980
7571
|
for (const r of results) {
|
|
6981
7572
|
if (r.success) ok++;
|
|
@@ -6989,7 +7580,7 @@ async function subUpdate(args) {
|
|
|
6989
7580
|
}
|
|
6990
7581
|
const target = resolveSubscription(subs, name);
|
|
6991
7582
|
console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
|
|
6992
|
-
const result = await tryUpdateOne(target);
|
|
7583
|
+
const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
|
|
6993
7584
|
if (!result.success) {
|
|
6994
7585
|
throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
|
|
6995
7586
|
}
|
|
@@ -7001,9 +7592,12 @@ async function subUpdate(args) {
|
|
|
7001
7592
|
async function subUse(args) {
|
|
7002
7593
|
const name = args[2];
|
|
7003
7594
|
const subs = getSubscriptions();
|
|
7595
|
+
if (subs.length === 0) {
|
|
7596
|
+
throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
|
|
7597
|
+
}
|
|
7004
7598
|
if (!name) {
|
|
7005
7599
|
throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
|
|
7006
|
-
hint:
|
|
7600
|
+
hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
|
|
7007
7601
|
});
|
|
7008
7602
|
}
|
|
7009
7603
|
const target = resolveSubscription(subs, name);
|
|
@@ -7053,18 +7647,18 @@ async function subRemove(args) {
|
|
|
7053
7647
|
console.log("");
|
|
7054
7648
|
printSubscriptionList();
|
|
7055
7649
|
}
|
|
7056
|
-
var
|
|
7650
|
+
var SUBCOMMANDS4 = [
|
|
7057
7651
|
{ name: "add", handler: subAdd },
|
|
7058
7652
|
{ name: "update", handler: subUpdate },
|
|
7059
7653
|
{ name: "use", handler: subUse },
|
|
7060
7654
|
{ name: "remove", aliases: ["rm", "delete"], handler: subRemove }
|
|
7061
7655
|
];
|
|
7062
7656
|
async function cmdSubscription(args) {
|
|
7063
|
-
await dispatchSubcommand(args,
|
|
7657
|
+
await dispatchSubcommand(args, SUBCOMMANDS4, {
|
|
7064
7658
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
7065
7659
|
fallback: printSubscriptionList,
|
|
7066
7660
|
onUnknown: (action) => {
|
|
7067
|
-
const names =
|
|
7661
|
+
const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7068
7662
|
const suggestion = suggestSimilar(action, names);
|
|
7069
7663
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
7070
7664
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
@@ -7074,6 +7668,14 @@ async function cmdSubscription(args) {
|
|
|
7074
7668
|
}
|
|
7075
7669
|
|
|
7076
7670
|
// src/commands/ui.ts
|
|
7671
|
+
import { spawnSync as spawnSync8 } from "child_process";
|
|
7672
|
+
function copyToClipboard(text) {
|
|
7673
|
+
try {
|
|
7674
|
+
return spawnSync8("pbcopy", [], { input: text }).status === 0;
|
|
7675
|
+
} catch {
|
|
7676
|
+
return false;
|
|
7677
|
+
}
|
|
7678
|
+
}
|
|
7077
7679
|
function cmdUI(args) {
|
|
7078
7680
|
const uiName = args[1] || "zash";
|
|
7079
7681
|
if (!Object.hasOwn(UI_URLS, uiName)) {
|
|
@@ -7088,7 +7690,9 @@ function cmdUI(args) {
|
|
|
7088
7690
|
console.log(`\u5730\u5740: ${url}`);
|
|
7089
7691
|
const secret = readSettings().controller_secret;
|
|
7090
7692
|
if (secret) {
|
|
7091
|
-
console.log(
|
|
7693
|
+
console.log(
|
|
7694
|
+
copyToClipboard(secret) ? "\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34\uFF09" : "\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08UI \u8FDE\u63A5 127.0.0.1:9090 \u65F6\u9700\u8F93\u5165\uFF0C\u5BC6\u94A5\u89C1 settings.json\uFF09"
|
|
7695
|
+
);
|
|
7092
7696
|
}
|
|
7093
7697
|
const success = openUrl(url);
|
|
7094
7698
|
if (!success) {
|
|
@@ -7097,13 +7701,13 @@ function cmdUI(args) {
|
|
|
7097
7701
|
}
|
|
7098
7702
|
|
|
7099
7703
|
// src/commands/update.ts
|
|
7100
|
-
import { execFile, spawn as spawn2 } from "child_process";
|
|
7101
|
-
import { promisify } from "util";
|
|
7102
|
-
var
|
|
7704
|
+
import { execFile as execFile2, spawn as spawn2 } from "child_process";
|
|
7705
|
+
import { promisify as promisify2 } from "util";
|
|
7706
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
7103
7707
|
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
7104
7708
|
async function getLatestNpmVersion() {
|
|
7105
7709
|
try {
|
|
7106
|
-
const { stdout } = await
|
|
7710
|
+
const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
|
|
7107
7711
|
const version = stdout.trim().split("\n").pop()?.trim();
|
|
7108
7712
|
return version || null;
|
|
7109
7713
|
} catch {
|
|
@@ -7113,8 +7717,7 @@ async function getLatestNpmVersion() {
|
|
|
7113
7717
|
async function cmdUpdate() {
|
|
7114
7718
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
7115
7719
|
console.log("");
|
|
7116
|
-
|
|
7117
|
-
const latest = await getLatestNpmVersion();
|
|
7720
|
+
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
7118
7721
|
if (latest && latest === VERSION) {
|
|
7119
7722
|
console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
|
|
7120
7723
|
return;
|
|
@@ -7142,7 +7745,7 @@ async function cmdUpdate() {
|
|
|
7142
7745
|
});
|
|
7143
7746
|
});
|
|
7144
7747
|
try {
|
|
7145
|
-
const { stdout } = await
|
|
7748
|
+
const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
|
|
7146
7749
|
const result = JSON.parse(stdout);
|
|
7147
7750
|
const newVersion = result.dependencies?.[PKG_NAME]?.version;
|
|
7148
7751
|
console.log("");
|
|
@@ -7169,10 +7772,10 @@ var COMMANDS = [
|
|
|
7169
7772
|
},
|
|
7170
7773
|
{
|
|
7171
7774
|
name: "start",
|
|
7172
|
-
aliases: [],
|
|
7775
|
+
aliases: ["restart"],
|
|
7173
7776
|
handler: cmdStart,
|
|
7174
7777
|
group: "control",
|
|
7175
|
-
usage: [{ signature: "start [tun|mixed] [-s] [-u ms]", description: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F\uFF08\u9ED8\u8BA4 mixed\uFF09" }]
|
|
7778
|
+
usage: [{ signature: "start [tun|mixed] [-s] [-u ms]", description: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F\uFF08\u9ED8\u8BA4 mixed\uFF1B= \u91CD\u542F\uFF09" }]
|
|
7176
7779
|
},
|
|
7177
7780
|
{
|
|
7178
7781
|
name: "tun",
|
|
@@ -7257,6 +7860,15 @@ var COMMANDS = [
|
|
|
7257
7860
|
usage: [{ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]", description: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF0C-f \u8DDF\u968F\uFF1B\u7701\u7565\u7F16\u53F7\u5373\u5F53\u524D\uFF09" }]
|
|
7258
7861
|
},
|
|
7259
7862
|
// === 订阅 ===
|
|
7863
|
+
{
|
|
7864
|
+
// 顶层快捷方式:`mihomo use <name>` = `mihomo subscription use <name>`(与 tun 同范式)
|
|
7865
|
+
name: "use",
|
|
7866
|
+
aliases: [],
|
|
7867
|
+
handler: cmdSubscription,
|
|
7868
|
+
rewrite: (args) => ["subscription", "use", ...args.slice(1)],
|
|
7869
|
+
group: "subscription",
|
|
7870
|
+
usage: [{ signature: "use <name>", description: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF0C\u81EA\u52A8\u91CD\u542F\uFF09" }]
|
|
7871
|
+
},
|
|
7260
7872
|
{
|
|
7261
7873
|
name: "subscription",
|
|
7262
7874
|
aliases: ["sub", "subs", "subscriptions"],
|
|
@@ -7313,6 +7925,20 @@ var COMMANDS = [
|
|
|
7313
7925
|
group: "system",
|
|
7314
7926
|
usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
|
|
7315
7927
|
},
|
|
7928
|
+
{
|
|
7929
|
+
name: "doctor",
|
|
7930
|
+
aliases: [],
|
|
7931
|
+
handler: cmdDoctor,
|
|
7932
|
+
group: "system",
|
|
7933
|
+
usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
|
|
7934
|
+
},
|
|
7935
|
+
{
|
|
7936
|
+
name: "completion",
|
|
7937
|
+
aliases: [],
|
|
7938
|
+
handler: cmdCompletion,
|
|
7939
|
+
group: "system",
|
|
7940
|
+
usage: [{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C\uFF08eval \u6216\u5199\u5165\u8865\u5168\u76EE\u5F55\uFF09" }]
|
|
7941
|
+
},
|
|
7316
7942
|
// === meta(不在分组清单展示,help 末尾单列) ===
|
|
7317
7943
|
{
|
|
7318
7944
|
name: "help",
|
|
@@ -7380,11 +8006,11 @@ function clearProxyEnv() {
|
|
|
7380
8006
|
delete process.env.all_proxy;
|
|
7381
8007
|
delete process.env.ALL_PROXY;
|
|
7382
8008
|
}
|
|
7383
|
-
var
|
|
8009
|
+
var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
|
|
7384
8010
|
function assertNotRoot(commandName) {
|
|
7385
8011
|
const uid = process.getuid?.();
|
|
7386
8012
|
if (uid !== 0) return;
|
|
7387
|
-
if (
|
|
8013
|
+
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
7388
8014
|
throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo", {
|
|
7389
8015
|
label: "\u8EAB\u4EFD\u9519\u8BEF",
|
|
7390
8016
|
hint: [
|
|
@@ -7398,10 +8024,9 @@ function assertNotRoot(commandName) {
|
|
|
7398
8024
|
]
|
|
7399
8025
|
});
|
|
7400
8026
|
}
|
|
7401
|
-
var PLATFORM_FREE_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
|
|
7402
8027
|
function assertSupportedPlatform(commandName) {
|
|
7403
8028
|
if (process.platform === "darwin") return;
|
|
7404
|
-
if (
|
|
8029
|
+
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
7405
8030
|
if (process.env.MIHOMO_CLI_ALLOW_ANY_PLATFORM === "1") return;
|
|
7406
8031
|
throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
|
|
7407
8032
|
label: "\u5E73\u53F0\u4E0D\u652F\u6301",
|