mihomo-cli 3.11.0 → 3.12.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 +38 -0
- package/README.md +17 -22
- package/dist/index.js +776 -859
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -17,7 +17,7 @@ var colors = {
|
|
|
17
17
|
|
|
18
18
|
// src/config.ts
|
|
19
19
|
import { spawnSync } from "child_process";
|
|
20
|
-
import
|
|
20
|
+
import fs4 from "fs";
|
|
21
21
|
|
|
22
22
|
// node_modules/js-yaml/dist/js-yaml.mjs
|
|
23
23
|
var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
|
|
@@ -3183,9 +3183,6 @@ var PATHS = {
|
|
|
3183
3183
|
configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
|
|
3184
3184
|
configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
|
|
3185
3185
|
configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
|
|
3186
|
-
// ssh 单列一个 stage:它不受 overwrite 开关约束,混进 2.overwrite.yaml 会让
|
|
3187
|
-
// `ow off` 时的调试输出自相矛盾(覆写已禁用,文件里却有内容)
|
|
3188
|
-
configStage4Ssh: path.join(DIRS.runtime, "4.ssh.yaml"),
|
|
3189
3186
|
// launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
|
|
3190
3187
|
launchDaemonPlist: path.join("/Library/LaunchDaemons", `${LAUNCH_DAEMON_LABEL}.plist`)
|
|
3191
3188
|
};
|
|
@@ -3384,16 +3381,21 @@ function saveSubscriptionCache(subName, data) {
|
|
|
3384
3381
|
cache[subName] = { ...cache[subName], ...data };
|
|
3385
3382
|
writeSubscriptionCache(cache);
|
|
3386
3383
|
}
|
|
3387
|
-
function
|
|
3388
|
-
const
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
|
|
3384
|
+
function readSettingsList(key, isValid, reAddHint) {
|
|
3385
|
+
const list = readSettings()[key];
|
|
3386
|
+
if (!Array.isArray(list)) {
|
|
3387
|
+
if (list !== void 0) {
|
|
3388
|
+
console.warn(`\u8B66\u544A: settings.json \u7684 ${key} \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08${reAddHint}\uFF09`);
|
|
3393
3389
|
}
|
|
3394
3390
|
return [];
|
|
3395
3391
|
}
|
|
3396
|
-
return
|
|
3392
|
+
return list.filter(isValid);
|
|
3393
|
+
}
|
|
3394
|
+
function isValidSubscription(s) {
|
|
3395
|
+
return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
|
|
3396
|
+
}
|
|
3397
|
+
function getSubscriptions() {
|
|
3398
|
+
return readSettingsList("subscriptions", isValidSubscription, "\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0");
|
|
3397
3399
|
}
|
|
3398
3400
|
function getSubscriptionsWithCache() {
|
|
3399
3401
|
const subs = getSubscriptions();
|
|
@@ -3404,16 +3406,11 @@ function getSubscriptionsWithCache() {
|
|
|
3404
3406
|
}));
|
|
3405
3407
|
}
|
|
3406
3408
|
var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
|
|
3409
|
+
function isValidSshConfig(t) {
|
|
3410
|
+
return t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port);
|
|
3411
|
+
}
|
|
3407
3412
|
function getSshTunnels() {
|
|
3408
|
-
|
|
3409
|
-
const tunnels = settings.ssh;
|
|
3410
|
-
if (!Array.isArray(tunnels)) {
|
|
3411
|
-
if (tunnels !== void 0) {
|
|
3412
|
-
console.warn("\u8B66\u544A: settings.json \u7684 ssh \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0\uFF09");
|
|
3413
|
-
}
|
|
3414
|
-
return [];
|
|
3415
|
-
}
|
|
3416
|
-
return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
|
|
3413
|
+
return readSettingsList("ssh", isValidSshConfig, "\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0");
|
|
3417
3414
|
}
|
|
3418
3415
|
function validateSshName(name) {
|
|
3419
3416
|
if (!name || !SAFE_NAME_RE.test(name)) {
|
|
@@ -3738,103 +3735,6 @@ function listOverwriteFile() {
|
|
|
3738
3735
|
};
|
|
3739
3736
|
}
|
|
3740
3737
|
|
|
3741
|
-
// src/ssh-config.ts
|
|
3742
|
-
import fs4 from "fs";
|
|
3743
|
-
import path4 from "path";
|
|
3744
|
-
var SSH_FILENAME_RE = /^ssh\.(.+)\.ya?ml$/;
|
|
3745
|
-
function isSshFilename(filename) {
|
|
3746
|
-
return SSH_FILENAME_RE.test(filename);
|
|
3747
|
-
}
|
|
3748
|
-
function getSshConfigPath(name) {
|
|
3749
|
-
validateSshName(name);
|
|
3750
|
-
return path4.join(USER_DATA_DIR, `ssh.${name}.yaml`);
|
|
3751
|
-
}
|
|
3752
|
-
function capitalize(name) {
|
|
3753
|
-
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
3754
|
-
}
|
|
3755
|
-
function getSshProxyName(name) {
|
|
3756
|
-
return `SSH-${capitalize(name)}-Host`;
|
|
3757
|
-
}
|
|
3758
|
-
function getSshGroupName(name) {
|
|
3759
|
-
return `SSH-${capitalize(name)}`;
|
|
3760
|
-
}
|
|
3761
|
-
function renderSshProxy(tunnel) {
|
|
3762
|
-
return {
|
|
3763
|
-
name: getSshProxyName(tunnel.name),
|
|
3764
|
-
type: "socks5",
|
|
3765
|
-
server: "127.0.0.1",
|
|
3766
|
-
port: tunnel.port
|
|
3767
|
-
};
|
|
3768
|
-
}
|
|
3769
|
-
function collectSshProxyNames(tunnels) {
|
|
3770
|
-
return tunnels.map((t) => getSshProxyName(t.name));
|
|
3771
|
-
}
|
|
3772
|
-
function loadSshConfigFiles() {
|
|
3773
|
-
if (!fs4.existsSync(USER_DATA_DIR)) return [];
|
|
3774
|
-
const files = fs4.readdirSync(USER_DATA_DIR).filter(isSshFilename).sort();
|
|
3775
|
-
const results = [];
|
|
3776
|
-
for (const file of files) {
|
|
3777
|
-
const filePath = path4.join(USER_DATA_DIR, file);
|
|
3778
|
-
try {
|
|
3779
|
-
const parsed = load(fs4.readFileSync(filePath, "utf8"), { maxAliases: 200 });
|
|
3780
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
3781
|
-
if ("match" in parsed) {
|
|
3782
|
-
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u7684 match \u5757\u4E0D\u751F\u6548\uFF08ssh \u96A7\u9053\u6052\u5168\u5C40\uFF09\uFF0C\u5DF2\u5FFD\u7565`);
|
|
3783
|
-
delete parsed.match;
|
|
3784
|
-
}
|
|
3785
|
-
results.push({ name: file, path: filePath, config: parsed });
|
|
3786
|
-
} else if (parsed !== null) {
|
|
3787
|
-
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
|
|
3788
|
-
}
|
|
3789
|
-
} catch (e) {
|
|
3790
|
-
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
|
|
3791
|
-
}
|
|
3792
|
-
}
|
|
3793
|
-
return results;
|
|
3794
|
-
}
|
|
3795
|
-
function applySshConfig(baseConfig, sshFiles, tunnels) {
|
|
3796
|
-
let result = { ...baseConfig };
|
|
3797
|
-
for (const file of sshFiles) {
|
|
3798
|
-
result = deepMergeWithOverrides(result, file.config);
|
|
3799
|
-
}
|
|
3800
|
-
if (tunnels.length > 0) {
|
|
3801
|
-
result = deepMergeWithOverrides(result, { "~proxies": tunnels.map(renderSshProxy) });
|
|
3802
|
-
}
|
|
3803
|
-
return result;
|
|
3804
|
-
}
|
|
3805
|
-
function renderSshConfigTemplate(tunnel) {
|
|
3806
|
-
const proxyName = getSshProxyName(tunnel.name);
|
|
3807
|
-
const groupName = getSshGroupName(tunnel.name);
|
|
3808
|
-
return `# mihomo-cli ssh \u96A7\u9053\u914D\u7F6E\uFF08ssh: ${tunnel.name}\uFF09
|
|
3809
|
-
# \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
|
|
3810
|
-
#
|
|
3811
|
-
# \u8282\u70B9 ${proxyName} \u7531 CLI \u4F9D\u636E settings \u91CC\u7684 host/port \u81EA\u52A8\u6CE8\u5165\uFF0C
|
|
3812
|
-
# \u65E0\u9700\u4E5F\u4E0D\u8981\u5728\u6B64\u58F0\u660E\uFF1A\u7AEF\u53E3\u4EE5 \`mihomo ssh\` \u663E\u793A\u7684\u4E3A\u51C6\uFF0C\u6539\u7AEF\u53E3\u7528 \`mihomo ssh add\`\u3002
|
|
3813
|
-
#
|
|
3814
|
-
# \u672C\u6587\u4EF6\u4E0D\u53D7 \`mihomo ow off\` \u5F71\u54CD\uFF08ssh \u5206\u6D41\u662F\u521A\u9700\uFF0C\u8986\u5199\u662F\u53EF\u9009\u8C03\u4F18\uFF09\u3002
|
|
3815
|
-
# ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF0C\u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\u3002
|
|
3816
|
-
|
|
3817
|
-
~proxy-groups:
|
|
3818
|
-
- name: ${groupName}
|
|
3819
|
-
type: select
|
|
3820
|
-
proxies:
|
|
3821
|
-
- ${proxyName}
|
|
3822
|
-
- DIRECT
|
|
3823
|
-
|
|
3824
|
-
# \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
|
|
3825
|
-
# +rules:
|
|
3826
|
-
# - DOMAIN-SUFFIX,example.internal,${groupName}
|
|
3827
|
-
# - IP-CIDR,10.0.0.0/8,${groupName}
|
|
3828
|
-
`;
|
|
3829
|
-
}
|
|
3830
|
-
function ensureSshConfigFile(tunnel) {
|
|
3831
|
-
const filePath = getSshConfigPath(tunnel.name);
|
|
3832
|
-
if (fs4.existsSync(filePath)) return false;
|
|
3833
|
-
fs4.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 448 });
|
|
3834
|
-
fs4.writeFileSync(filePath, renderSshConfigTemplate(tunnel), { mode: 384 });
|
|
3835
|
-
return true;
|
|
3836
|
-
}
|
|
3837
|
-
|
|
3838
3738
|
// src/utils.ts
|
|
3839
3739
|
var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
3840
3740
|
function sleepSync(ms) {
|
|
@@ -3859,6 +3759,15 @@ function formatBytes(bytes) {
|
|
|
3859
3759
|
const i = Math.min(Math.floor(Math.log(num) / Math.log(k)), sizes.length - 1);
|
|
3860
3760
|
return `${parseFloat((num / k ** i).toFixed(2))} ${sizes[i]}`;
|
|
3861
3761
|
}
|
|
3762
|
+
function formatTraffic(upload, download, total) {
|
|
3763
|
+
if (download === void 0 && total === void 0) return null;
|
|
3764
|
+
const used = (upload || 0) + (download || 0);
|
|
3765
|
+
let line = `${formatBytes(used)} / ${formatBytes(total)}`;
|
|
3766
|
+
if (total && total > 0) {
|
|
3767
|
+
line += ` (${Math.min(used / total * 100, 100).toFixed(1)}%)`;
|
|
3768
|
+
}
|
|
3769
|
+
return line;
|
|
3770
|
+
}
|
|
3862
3771
|
function formatTimestamp(ts) {
|
|
3863
3772
|
if (ts === void 0 || ts === null) return "\u672A\u77E5";
|
|
3864
3773
|
if (ts === 0) return "\u6C38\u4E45";
|
|
@@ -4077,8 +3986,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
|
|
|
4077
3986
|
}
|
|
4078
3987
|
return names;
|
|
4079
3988
|
}
|
|
4080
|
-
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles
|
|
4081
|
-
const injectedNames =
|
|
3989
|
+
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
|
|
3990
|
+
const injectedNames = collectOverwriteProxyNames(overwriteFiles);
|
|
4082
3991
|
if (injectedNames.length === 0) return;
|
|
4083
3992
|
const groups = config["proxy-groups"];
|
|
4084
3993
|
if (!groups) return;
|
|
@@ -4262,35 +4171,31 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4262
4171
|
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4263
4172
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4264
4173
|
const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
const withSsh = applySshConfig(withOverwrites, sshFiles, sshTunnels);
|
|
4268
|
-
const sshProxyNames = collectSshProxyNames(sshTunnels);
|
|
4269
|
-
if (overwriteFiles.length > 0 || sshProxyNames.length > 0) {
|
|
4270
|
-
excludeOverwriteProxiesFromIncludeAll(withSsh, overwriteFiles, sshProxyNames);
|
|
4174
|
+
if (overwriteFiles.length > 0) {
|
|
4175
|
+
excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
|
|
4271
4176
|
}
|
|
4272
4177
|
const systemConfig = {};
|
|
4273
4178
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4274
|
-
if (!(key in
|
|
4179
|
+
if (!(key in withOverwrites)) {
|
|
4275
4180
|
systemConfig[key] = value;
|
|
4276
4181
|
}
|
|
4277
4182
|
}
|
|
4278
4183
|
systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
|
|
4279
4184
|
systemConfig["mixed-port"] = BASE_CONFIG["mixed-port"];
|
|
4280
|
-
delete
|
|
4281
|
-
delete
|
|
4282
|
-
delete
|
|
4283
|
-
delete
|
|
4284
|
-
delete
|
|
4285
|
-
delete
|
|
4286
|
-
delete
|
|
4185
|
+
delete withOverwrites["mixed-port"];
|
|
4186
|
+
delete withOverwrites.port;
|
|
4187
|
+
delete withOverwrites["socks-port"];
|
|
4188
|
+
delete withOverwrites["external-ui"];
|
|
4189
|
+
delete withOverwrites["external-ui-name"];
|
|
4190
|
+
delete withOverwrites["external-ui-url"];
|
|
4191
|
+
delete withOverwrites.secret;
|
|
4287
4192
|
const controllerSecret = readSettings().controller_secret;
|
|
4288
4193
|
if (controllerSecret) {
|
|
4289
4194
|
systemConfig.secret = controllerSecret;
|
|
4290
4195
|
}
|
|
4291
4196
|
if (mode === "tun") {
|
|
4292
4197
|
systemConfig.tun = TUN_CONFIG.tun;
|
|
4293
|
-
const subDns =
|
|
4198
|
+
const subDns = withOverwrites.dns || {};
|
|
4294
4199
|
const dns = {};
|
|
4295
4200
|
if (!("enable" in subDns)) dns.enable = true;
|
|
4296
4201
|
if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
|
|
@@ -4299,14 +4204,14 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4299
4204
|
systemConfig.dns = dns;
|
|
4300
4205
|
}
|
|
4301
4206
|
} else {
|
|
4302
|
-
delete
|
|
4207
|
+
delete withOverwrites.tun;
|
|
4303
4208
|
}
|
|
4304
|
-
const merged = { ...
|
|
4209
|
+
const merged = { ...withOverwrites, ...systemConfig };
|
|
4305
4210
|
if (systemConfig.dns) {
|
|
4306
|
-
merged.dns = { ...
|
|
4211
|
+
merged.dns = { ...withOverwrites.dns || {}, ...systemConfig.dns };
|
|
4307
4212
|
}
|
|
4308
4213
|
const mergedDns = merged.dns || {};
|
|
4309
|
-
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in
|
|
4214
|
+
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withOverwrites)) {
|
|
4310
4215
|
merged.sniffer = {
|
|
4311
4216
|
enable: true,
|
|
4312
4217
|
sniff: {
|
|
@@ -4318,7 +4223,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4318
4223
|
};
|
|
4319
4224
|
}
|
|
4320
4225
|
const warnings = validateConfig(merged);
|
|
4321
|
-
return { config: merged, subscriptionConfig, overwriteFiles,
|
|
4226
|
+
return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
|
|
4322
4227
|
}
|
|
4323
4228
|
function writeMihomoConfig(configObj) {
|
|
4324
4229
|
ensureDirs();
|
|
@@ -4327,32 +4232,22 @@ function writeMihomoConfig(configObj) {
|
|
|
4327
4232
|
}
|
|
4328
4233
|
function writeDebugConfig(buildResult) {
|
|
4329
4234
|
ensureDirs();
|
|
4330
|
-
|
|
4235
|
+
fs4.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
|
|
4331
4236
|
const overwriteMerged = {};
|
|
4332
4237
|
for (const f of buildResult.overwriteFiles) {
|
|
4333
4238
|
Object.assign(overwriteMerged, f.config);
|
|
4334
4239
|
}
|
|
4335
4240
|
const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
const sshMerged = {};
|
|
4339
|
-
for (const f of buildResult.sshFiles) {
|
|
4340
|
-
Object.assign(sshMerged, f.config);
|
|
4341
|
-
}
|
|
4342
|
-
const sshTunnels = getSshTunnels();
|
|
4343
|
-
if (sshTunnels.length > 0) {
|
|
4344
|
-
sshMerged["~proxies"] = sshTunnels.map(renderSshProxy);
|
|
4345
|
-
}
|
|
4346
|
-
const sshContent = Object.keys(sshMerged).length > 0 ? dumpYaml(sshMerged) : "# \u672A\u914D\u7F6E ssh \u96A7\u9053\n";
|
|
4347
|
-
fs5.writeFileSync(PATHS.configStage4Ssh, sshContent, { mode: 384 });
|
|
4241
|
+
fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
|
|
4242
|
+
fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
|
|
4348
4243
|
}
|
|
4349
4244
|
function hasConfig() {
|
|
4350
|
-
return
|
|
4245
|
+
return fs4.existsSync(PATHS.configFile);
|
|
4351
4246
|
}
|
|
4352
4247
|
function getConfigInfo() {
|
|
4353
4248
|
if (!hasConfig()) return null;
|
|
4354
4249
|
try {
|
|
4355
|
-
const content =
|
|
4250
|
+
const content = fs4.readFileSync(PATHS.configFile, "utf8");
|
|
4356
4251
|
const cfg = loadYamlSafe(content);
|
|
4357
4252
|
if (!cfg) return null;
|
|
4358
4253
|
const proxies = cfg.proxies;
|
|
@@ -4372,7 +4267,7 @@ function getConfigInfo() {
|
|
|
4372
4267
|
}
|
|
4373
4268
|
}
|
|
4374
4269
|
function hasKernel() {
|
|
4375
|
-
return
|
|
4270
|
+
return fs4.existsSync(PATHS.mihomoBinary);
|
|
4376
4271
|
}
|
|
4377
4272
|
var kernelVersionCache = null;
|
|
4378
4273
|
var kernelVersionCached = false;
|
|
@@ -4478,48 +4373,91 @@ function printVersion() {
|
|
|
4478
4373
|
}
|
|
4479
4374
|
|
|
4480
4375
|
// src/daemon.ts
|
|
4481
|
-
import
|
|
4482
|
-
import fs7 from "fs";
|
|
4376
|
+
import fs8 from "fs";
|
|
4483
4377
|
import path6 from "path";
|
|
4484
4378
|
|
|
4485
|
-
// src/
|
|
4486
|
-
import
|
|
4487
|
-
import
|
|
4488
|
-
|
|
4489
|
-
|
|
4490
|
-
|
|
4491
|
-
|
|
4492
|
-
var silentSigint = false;
|
|
4493
|
-
function setSilentSigint(value) {
|
|
4494
|
-
silentSigint = value;
|
|
4379
|
+
// src/log-files.ts
|
|
4380
|
+
import fs5 from "fs";
|
|
4381
|
+
import path4 from "path";
|
|
4382
|
+
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
4383
|
+
function rotateAndCleanupLogs() {
|
|
4384
|
+
rotateLog();
|
|
4385
|
+
cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
|
|
4495
4386
|
}
|
|
4496
|
-
function
|
|
4497
|
-
return
|
|
4387
|
+
function getLogPath() {
|
|
4388
|
+
return PATHS.logFile;
|
|
4498
4389
|
}
|
|
4499
|
-
function
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4390
|
+
function rotateLog() {
|
|
4391
|
+
const logFile = PATHS.logFile;
|
|
4392
|
+
if (!fs5.existsSync(logFile)) return null;
|
|
4393
|
+
const stat = fs5.statSync(logFile);
|
|
4394
|
+
if (stat.size === 0) return null;
|
|
4395
|
+
const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
|
|
4396
|
+
const rotatedPath = path4.join(DIRS.logs, rotatedName);
|
|
4397
|
+
fs5.renameSync(logFile, rotatedPath);
|
|
4398
|
+
return rotatedPath;
|
|
4504
4399
|
}
|
|
4505
|
-
function
|
|
4506
|
-
|
|
4400
|
+
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
4401
|
+
const logsDir = DIRS.logs;
|
|
4402
|
+
if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
|
|
4403
|
+
const files = fs5.readdirSync(logsDir);
|
|
4404
|
+
const now = Date.now();
|
|
4405
|
+
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
|
|
4406
|
+
let deleted = 0;
|
|
4407
|
+
let errors = 0;
|
|
4408
|
+
for (const file of files) {
|
|
4409
|
+
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
|
|
4507
4410
|
try {
|
|
4508
|
-
|
|
4411
|
+
const filePath = path4.join(logsDir, file);
|
|
4412
|
+
const stat = fs5.statSync(filePath);
|
|
4413
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
4414
|
+
fs5.unlinkSync(filePath);
|
|
4415
|
+
deleted++;
|
|
4416
|
+
}
|
|
4509
4417
|
} catch {
|
|
4418
|
+
errors++;
|
|
4510
4419
|
}
|
|
4511
4420
|
}
|
|
4512
|
-
|
|
4421
|
+
return { deleted, errors };
|
|
4422
|
+
}
|
|
4423
|
+
function listLogs() {
|
|
4424
|
+
const logsDir = DIRS.logs;
|
|
4425
|
+
const result = { current: null, archives: [] };
|
|
4426
|
+
if (fs5.existsSync(PATHS.logFile)) {
|
|
4427
|
+
const stat = fs5.statSync(PATHS.logFile);
|
|
4428
|
+
result.current = {
|
|
4429
|
+
name: "mihomo.log (\u5F53\u524D)",
|
|
4430
|
+
path: PATHS.logFile,
|
|
4431
|
+
size: stat.size,
|
|
4432
|
+
mtime: stat.mtime,
|
|
4433
|
+
isCurrent: true
|
|
4434
|
+
};
|
|
4435
|
+
}
|
|
4436
|
+
if (!fs5.existsSync(logsDir)) return result;
|
|
4437
|
+
const files = fs5.readdirSync(logsDir);
|
|
4438
|
+
for (const file of files) {
|
|
4439
|
+
const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
|
|
4440
|
+
if (!match) continue;
|
|
4441
|
+
try {
|
|
4442
|
+
const filePath = path4.join(logsDir, file);
|
|
4443
|
+
const stat = fs5.statSync(filePath);
|
|
4444
|
+
result.archives.push({
|
|
4445
|
+
name: file,
|
|
4446
|
+
path: filePath,
|
|
4447
|
+
size: stat.size,
|
|
4448
|
+
mtime: stat.mtime,
|
|
4449
|
+
isCurrent: false
|
|
4450
|
+
});
|
|
4451
|
+
} catch {
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
4455
|
+
return result;
|
|
4513
4456
|
}
|
|
4514
4457
|
|
|
4515
|
-
// src/process.ts
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
var STARTUP_WAIT_MS = 800;
|
|
4519
|
-
var SUDO_TIMEOUT_MS = 6e4;
|
|
4520
|
-
var TUN_MODE_POST_WAIT_MS = 500;
|
|
4521
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
4522
|
-
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
4458
|
+
// src/process-probe.ts
|
|
4459
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
4460
|
+
import fs6 from "fs";
|
|
4523
4461
|
var PS_TIMEOUT_MS = 5e3;
|
|
4524
4462
|
function isProcessRunning(pid) {
|
|
4525
4463
|
if (!pid) return false;
|
|
@@ -4549,12 +4487,6 @@ function isProcessRoot(pid) {
|
|
|
4549
4487
|
}
|
|
4550
4488
|
}
|
|
4551
4489
|
var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
|
|
4552
|
-
function clearRuntime() {
|
|
4553
|
-
if (fs6.existsSync(DIRS.runtime)) {
|
|
4554
|
-
rmrf(DIRS.runtime);
|
|
4555
|
-
}
|
|
4556
|
-
ensureDirs();
|
|
4557
|
-
}
|
|
4558
4490
|
function getPid() {
|
|
4559
4491
|
if (!fs6.existsSync(PATHS.pidFile)) return null;
|
|
4560
4492
|
try {
|
|
@@ -4603,447 +4535,96 @@ function checkStaleState() {
|
|
|
4603
4535
|
function hasRootResidue() {
|
|
4604
4536
|
return checkStaleState().needsSudo;
|
|
4605
4537
|
}
|
|
4606
|
-
function
|
|
4607
|
-
|
|
4608
|
-
|
|
4538
|
+
function getProcessInfo(pid) {
|
|
4539
|
+
try {
|
|
4540
|
+
const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
|
|
4541
|
+
const psOutput = (result.stdout || "").trim();
|
|
4542
|
+
if (!psOutput) return null;
|
|
4543
|
+
const rss = parseInt(psOutput, 10);
|
|
4544
|
+
return {
|
|
4545
|
+
pid,
|
|
4546
|
+
memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
4547
|
+
isRoot: isProcessRoot(pid)
|
|
4548
|
+
};
|
|
4549
|
+
} catch {
|
|
4550
|
+
return { pid, memory: "\u672A\u77E5", isRoot: false };
|
|
4551
|
+
}
|
|
4609
4552
|
}
|
|
4610
|
-
function
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4553
|
+
function getStatus() {
|
|
4554
|
+
const running = isRunning();
|
|
4555
|
+
const pid = getPid();
|
|
4556
|
+
const allPids = getMihomoPids();
|
|
4557
|
+
return {
|
|
4558
|
+
running,
|
|
4559
|
+
pid: running ? pid : null,
|
|
4560
|
+
processInfo: running && pid ? getProcessInfo(pid) : null,
|
|
4561
|
+
hasConfig: hasConfig(),
|
|
4562
|
+
hasKernel: hasKernel(),
|
|
4563
|
+
kernelVersion: getKernelVersion(),
|
|
4564
|
+
allProcesses: allPids,
|
|
4565
|
+
hasStaleProcesses: allPids.length > (running ? 1 : 0)
|
|
4566
|
+
};
|
|
4567
|
+
}
|
|
4568
|
+
|
|
4569
|
+
// src/sudo.ts
|
|
4570
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
4571
|
+
import fs7 from "fs";
|
|
4572
|
+
import path5 from "path";
|
|
4573
|
+
var SUDO_TIMEOUT_MS = 6e4;
|
|
4574
|
+
function runSudoScript(scriptBody, opts) {
|
|
4575
|
+
if (!process.stdin.isTTY) {
|
|
4576
|
+
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
4577
|
+
}
|
|
4578
|
+
ensureDirs();
|
|
4579
|
+
const scriptPath = path5.join(DIRS.runtime, opts.file);
|
|
4580
|
+
fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
4581
|
+
fs7.chmodSync(scriptPath, 448);
|
|
4582
|
+
try {
|
|
4583
|
+
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
4584
|
+
if (result.error) throw result.error;
|
|
4585
|
+
if (result.status !== 0) {
|
|
4586
|
+
if (result.status === 1) {
|
|
4587
|
+
throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4588
|
+
}
|
|
4589
|
+
if (result.status == null) {
|
|
4590
|
+
throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4591
|
+
}
|
|
4592
|
+
const custom = opts.codeMessages?.[result.status];
|
|
4593
|
+
throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
|
|
4616
4594
|
}
|
|
4617
|
-
}
|
|
4595
|
+
} finally {
|
|
4618
4596
|
try {
|
|
4619
|
-
|
|
4597
|
+
fs7.unlinkSync(scriptPath);
|
|
4620
4598
|
} catch {
|
|
4621
4599
|
}
|
|
4622
4600
|
}
|
|
4623
4601
|
}
|
|
4624
|
-
|
|
4602
|
+
|
|
4603
|
+
// src/daemon.ts
|
|
4604
|
+
var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
|
|
4605
|
+
function assertDaemonLabelSafe() {
|
|
4606
|
+
if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
|
|
4607
|
+
throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
|
|
4608
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4609
|
+
hint: [
|
|
4610
|
+
'\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
|
|
4611
|
+
"\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
|
|
4612
|
+
]
|
|
4613
|
+
});
|
|
4614
|
+
}
|
|
4615
|
+
}
|
|
4616
|
+
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
4617
|
+
var DAEMON_BOOT_WAIT_MS = 500;
|
|
4618
|
+
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4619
|
+
function logOversized() {
|
|
4625
4620
|
try {
|
|
4626
|
-
|
|
4627
|
-
return true;
|
|
4621
|
+
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
4628
4622
|
} catch {
|
|
4629
4623
|
return false;
|
|
4630
4624
|
}
|
|
4631
4625
|
}
|
|
4632
|
-
function
|
|
4633
|
-
|
|
4634
|
-
if (forceSudo) {
|
|
4635
|
-
try {
|
|
4636
|
-
spawnSync2("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
|
|
4637
|
-
return true;
|
|
4638
|
-
} catch {
|
|
4639
|
-
return false;
|
|
4640
|
-
}
|
|
4641
|
-
} else {
|
|
4642
|
-
try {
|
|
4643
|
-
spawnSync2("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
|
|
4644
|
-
return true;
|
|
4645
|
-
} catch {
|
|
4646
|
-
return false;
|
|
4647
|
-
}
|
|
4648
|
-
}
|
|
4649
|
-
}
|
|
4650
|
-
function cleanupAll(forceSudo = false) {
|
|
4651
|
-
const pids = getMihomoPids();
|
|
4652
|
-
if (pids.length === 0) {
|
|
4653
|
-
clearPid();
|
|
4654
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
4655
|
-
}
|
|
4656
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
4657
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
4658
|
-
let killedCount = 0;
|
|
4659
|
-
const failedPids = [];
|
|
4660
|
-
if (needsSudo) {
|
|
4661
|
-
const success = killAllMihomo(true);
|
|
4662
|
-
if (success) {
|
|
4663
|
-
killedCount = pids.length;
|
|
4664
|
-
} else {
|
|
4665
|
-
failedPids.push(...pids);
|
|
4666
|
-
}
|
|
4667
|
-
} else {
|
|
4668
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
4669
|
-
killAllMihomo(false);
|
|
4670
|
-
killedCount = pids.length;
|
|
4671
|
-
} else {
|
|
4672
|
-
for (const pid of pids) {
|
|
4673
|
-
if (killProcess(pid)) {
|
|
4674
|
-
killedCount++;
|
|
4675
|
-
} else {
|
|
4676
|
-
failedPids.push(pid);
|
|
4677
|
-
}
|
|
4678
|
-
}
|
|
4679
|
-
}
|
|
4680
|
-
}
|
|
4681
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
4682
|
-
if (getMihomoPids().length === 0) break;
|
|
4683
|
-
sleepSync(PROCESS_WAIT_INTERVAL);
|
|
4684
|
-
}
|
|
4685
|
-
clearPid();
|
|
4686
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
4687
|
-
}
|
|
4688
|
-
function createTunLaunchScript() {
|
|
4689
|
-
const binary = shellQuote(PATHS.mihomoBinary);
|
|
4690
|
-
const configFile = shellQuote(PATHS.configFile);
|
|
4691
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
4692
|
-
const pidFile = shellQuote(PATHS.pidFile);
|
|
4693
|
-
const dataDir = shellQuote(DIRS.data);
|
|
4694
|
-
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
4695
|
-
const scriptContent = `#!/bin/bash
|
|
4696
|
-
BINARY=${binary}
|
|
4697
|
-
CONFIG_FILE=${configFile}
|
|
4698
|
-
LOG_FILE=${logFile}
|
|
4699
|
-
PID_FILE=${pidFile}
|
|
4700
|
-
DATA_DIR=${dataDir}
|
|
4701
|
-
KILL_PATTERN=${killPattern}
|
|
4702
|
-
|
|
4703
|
-
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
4704
|
-
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
4705
|
-
sleep 0.2
|
|
4706
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4707
|
-
|
|
4708
|
-
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
4709
|
-
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
4710
|
-
|
|
4711
|
-
# \u542F\u52A8
|
|
4712
|
-
cd /tmp
|
|
4713
|
-
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
4714
|
-
NEW_PID=$!
|
|
4715
|
-
echo \${NEW_PID} > "\${PID_FILE}"
|
|
4716
|
-
|
|
4717
|
-
# \u9A8C\u8BC1
|
|
4718
|
-
for i in 1 2 3 4 5; do
|
|
4719
|
-
sleep 0.4
|
|
4720
|
-
if kill -0 \${NEW_PID} 2>/dev/null; then
|
|
4721
|
-
exit 0
|
|
4722
|
-
fi
|
|
4723
|
-
done
|
|
4724
|
-
|
|
4725
|
-
# \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
|
|
4726
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4727
|
-
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
4728
|
-
echo ""
|
|
4729
|
-
echo "--- \u65E5\u5FD7 ---"
|
|
4730
|
-
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
4731
|
-
exit 2
|
|
4732
|
-
`;
|
|
4733
|
-
const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
|
|
4734
|
-
fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
|
|
4735
|
-
fs6.chmodSync(scriptPath, 448);
|
|
4736
|
-
return scriptPath;
|
|
4737
|
-
}
|
|
4738
|
-
function getProcessInfo(pid) {
|
|
4739
|
-
try {
|
|
4740
|
-
const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
|
|
4741
|
-
const psOutput = (result.stdout || "").trim();
|
|
4742
|
-
if (!psOutput) return null;
|
|
4743
|
-
const rss = parseInt(psOutput, 10);
|
|
4744
|
-
return {
|
|
4745
|
-
pid,
|
|
4746
|
-
memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
4747
|
-
isRoot: isProcessRoot(pid)
|
|
4748
|
-
};
|
|
4749
|
-
} catch {
|
|
4750
|
-
return { pid, memory: "\u672A\u77E5", isRoot: false };
|
|
4751
|
-
}
|
|
4752
|
-
}
|
|
4753
|
-
function getStatus() {
|
|
4754
|
-
const running = isRunning();
|
|
4755
|
-
const pid = getPid();
|
|
4756
|
-
const allPids = getMihomoPids();
|
|
4757
|
-
return {
|
|
4758
|
-
running,
|
|
4759
|
-
pid: running ? pid : null,
|
|
4760
|
-
processInfo: running && pid ? getProcessInfo(pid) : null,
|
|
4761
|
-
hasConfig: hasConfig(),
|
|
4762
|
-
hasKernel: hasKernel(),
|
|
4763
|
-
kernelVersion: getKernelVersion(),
|
|
4764
|
-
allProcesses: allPids,
|
|
4765
|
-
hasStaleProcesses: allPids.length > (running ? 1 : 0)
|
|
4766
|
-
};
|
|
4767
|
-
}
|
|
4768
|
-
async function start(mode = "mixed") {
|
|
4769
|
-
const isTunMode = mode === "tun";
|
|
4770
|
-
ensureDirs();
|
|
4771
|
-
rotateAndCleanupLogs();
|
|
4772
|
-
const binary = PATHS.mihomoBinary;
|
|
4773
|
-
if (!fs6.existsSync(binary)) {
|
|
4774
|
-
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
4775
|
-
}
|
|
4776
|
-
const configFile = PATHS.configFile;
|
|
4777
|
-
if (!fs6.existsSync(configFile)) {
|
|
4778
|
-
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
4779
|
-
}
|
|
4780
|
-
const staleState = checkStaleState();
|
|
4781
|
-
if (isTunMode) {
|
|
4782
|
-
return startTunMode(staleState);
|
|
4783
|
-
}
|
|
4784
|
-
return startMixedMode(staleState);
|
|
4785
|
-
}
|
|
4786
|
-
async function startMixedMode(staleState) {
|
|
4787
|
-
if (staleState.needsCleanup) {
|
|
4788
|
-
if (staleState.needsSudo) {
|
|
4789
|
-
console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
|
|
4790
|
-
console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
|
|
4791
|
-
console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
|
|
4792
|
-
throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
|
|
4793
|
-
}
|
|
4794
|
-
const cleanupResult = cleanupAll();
|
|
4795
|
-
if (cleanupResult.killed > 0) {
|
|
4796
|
-
console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
|
|
4797
|
-
}
|
|
4798
|
-
}
|
|
4799
|
-
if (isRunning()) {
|
|
4800
|
-
const pid2 = getPid();
|
|
4801
|
-
return { success: true, pid: pid2, alreadyRunning: true };
|
|
4802
|
-
}
|
|
4803
|
-
const configFile = PATHS.configFile;
|
|
4804
|
-
const logFile = PATHS.logFile;
|
|
4805
|
-
const args = ["-d", DIRS.data, "-f", configFile];
|
|
4806
|
-
if (fs6.existsSync(logFile)) {
|
|
4807
|
-
try {
|
|
4808
|
-
fs6.accessSync(logFile, fs6.constants.W_OK);
|
|
4809
|
-
} catch {
|
|
4810
|
-
try {
|
|
4811
|
-
fs6.unlinkSync(logFile);
|
|
4812
|
-
} catch {
|
|
4813
|
-
}
|
|
4814
|
-
}
|
|
4815
|
-
}
|
|
4816
|
-
const logFd = fs6.openSync(logFile, "a");
|
|
4817
|
-
const child = spawn(PATHS.mihomoBinary, args, {
|
|
4818
|
-
detached: true,
|
|
4819
|
-
stdio: ["ignore", logFd, logFd]
|
|
4820
|
-
});
|
|
4821
|
-
child.on("error", () => {
|
|
4822
|
-
});
|
|
4823
|
-
fs6.closeSync(logFd);
|
|
4824
|
-
child.unref();
|
|
4825
|
-
const pid = child.pid;
|
|
4826
|
-
if (!pid) {
|
|
4827
|
-
clearPid();
|
|
4828
|
-
throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
|
|
4829
|
-
}
|
|
4830
|
-
savePid(pid);
|
|
4831
|
-
await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
|
|
4832
|
-
if (!isRunning()) {
|
|
4833
|
-
clearPid();
|
|
4834
|
-
let errorMsg = "\u542F\u52A8\u5931\u8D25";
|
|
4835
|
-
if (fs6.existsSync(logFile)) {
|
|
4836
|
-
try {
|
|
4837
|
-
const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
|
|
4838
|
-
if (logs.trim()) {
|
|
4839
|
-
errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
|
|
4840
|
-
}
|
|
4841
|
-
} catch {
|
|
4842
|
-
}
|
|
4843
|
-
}
|
|
4844
|
-
throw new Error(errorMsg);
|
|
4845
|
-
}
|
|
4846
|
-
return { success: true, pid, mode: "mixed" };
|
|
4847
|
-
}
|
|
4848
|
-
async function startTunMode(staleState) {
|
|
4849
|
-
const launchScript = createTunLaunchScript();
|
|
4850
|
-
if (staleState.needsCleanup) {
|
|
4851
|
-
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
4852
|
-
}
|
|
4853
|
-
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
4854
|
-
try {
|
|
4855
|
-
const result = spawnSync2("sudo", [launchScript], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
4856
|
-
if (result.error) throw result.error;
|
|
4857
|
-
if (result.status !== 0) {
|
|
4858
|
-
const err = new Error("TUN \u542F\u52A8\u811A\u672C\u6267\u884C\u5931\u8D25");
|
|
4859
|
-
err.status = result.status ?? void 0;
|
|
4860
|
-
throw err;
|
|
4861
|
-
}
|
|
4862
|
-
} catch (e) {
|
|
4863
|
-
try {
|
|
4864
|
-
fs6.unlinkSync(launchScript);
|
|
4865
|
-
} catch {
|
|
4866
|
-
}
|
|
4867
|
-
if (e.status === 1) {
|
|
4868
|
-
throw new Error("\u5BC6\u7801\u9519\u8BEF\u6216\u53D6\u6D88");
|
|
4869
|
-
}
|
|
4870
|
-
if (e.status === 2) {
|
|
4871
|
-
throw new Error("TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09");
|
|
4872
|
-
}
|
|
4873
|
-
throw new Error(e.message);
|
|
4874
|
-
}
|
|
4875
|
-
try {
|
|
4876
|
-
fs6.unlinkSync(launchScript);
|
|
4877
|
-
} catch {
|
|
4878
|
-
}
|
|
4879
|
-
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
4880
|
-
const finalPid = getPid();
|
|
4881
|
-
if (!finalPid) {
|
|
4882
|
-
throw new Error("TUN \u542F\u52A8\u5931\u8D25");
|
|
4883
|
-
}
|
|
4884
|
-
return { success: true, pid: finalPid, mode: "tun" };
|
|
4885
|
-
}
|
|
4886
|
-
function stop(forceSudo = false) {
|
|
4887
|
-
const allPids = getMihomoPids();
|
|
4888
|
-
if (allPids.length === 0) {
|
|
4889
|
-
clearPid();
|
|
4890
|
-
clearRuntime();
|
|
4891
|
-
return { success: true, notRunning: true };
|
|
4892
|
-
}
|
|
4893
|
-
const result = cleanupAll(forceSudo);
|
|
4894
|
-
const remaining = getMihomoPids();
|
|
4895
|
-
if (remaining.length > 0) {
|
|
4896
|
-
console.log("");
|
|
4897
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
4898
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
4899
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
4900
|
-
console.log("");
|
|
4901
|
-
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
4902
|
-
}
|
|
4903
|
-
clearRuntime();
|
|
4904
|
-
return { success: true, killed: result.killed };
|
|
4905
|
-
}
|
|
4906
|
-
function rotateAndCleanupLogs() {
|
|
4907
|
-
rotateLog();
|
|
4908
|
-
cleanupOldLogs(DEFAULT_LOG_RETENTION_DAYS);
|
|
4909
|
-
}
|
|
4910
|
-
function getLogPath() {
|
|
4911
|
-
return PATHS.logFile;
|
|
4912
|
-
}
|
|
4913
|
-
function rotateLog() {
|
|
4914
|
-
const logFile = PATHS.logFile;
|
|
4915
|
-
if (!fs6.existsSync(logFile)) return null;
|
|
4916
|
-
const stat = fs6.statSync(logFile);
|
|
4917
|
-
if (stat.size === 0) return null;
|
|
4918
|
-
const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
|
|
4919
|
-
const rotatedPath = path5.join(DIRS.logs, rotatedName);
|
|
4920
|
-
fs6.renameSync(logFile, rotatedPath);
|
|
4921
|
-
return rotatedPath;
|
|
4922
|
-
}
|
|
4923
|
-
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
4924
|
-
const logsDir = DIRS.logs;
|
|
4925
|
-
if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
|
|
4926
|
-
const files = fs6.readdirSync(logsDir);
|
|
4927
|
-
const now = Date.now();
|
|
4928
|
-
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
|
|
4929
|
-
let deleted = 0;
|
|
4930
|
-
let errors = 0;
|
|
4931
|
-
for (const file of files) {
|
|
4932
|
-
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
|
|
4933
|
-
try {
|
|
4934
|
-
const filePath = path5.join(logsDir, file);
|
|
4935
|
-
const stat = fs6.statSync(filePath);
|
|
4936
|
-
if (now - stat.mtimeMs > maxAgeMs) {
|
|
4937
|
-
fs6.unlinkSync(filePath);
|
|
4938
|
-
deleted++;
|
|
4939
|
-
}
|
|
4940
|
-
} catch {
|
|
4941
|
-
errors++;
|
|
4942
|
-
}
|
|
4943
|
-
}
|
|
4944
|
-
return { deleted, errors };
|
|
4945
|
-
}
|
|
4946
|
-
function listLogs() {
|
|
4947
|
-
const logsDir = DIRS.logs;
|
|
4948
|
-
const result = { current: null, archives: [] };
|
|
4949
|
-
if (fs6.existsSync(PATHS.logFile)) {
|
|
4950
|
-
const stat = fs6.statSync(PATHS.logFile);
|
|
4951
|
-
result.current = {
|
|
4952
|
-
name: "mihomo.log (\u5F53\u524D)",
|
|
4953
|
-
path: PATHS.logFile,
|
|
4954
|
-
size: stat.size,
|
|
4955
|
-
mtime: stat.mtime,
|
|
4956
|
-
isCurrent: true
|
|
4957
|
-
};
|
|
4958
|
-
}
|
|
4959
|
-
if (!fs6.existsSync(logsDir)) return result;
|
|
4960
|
-
const files = fs6.readdirSync(logsDir);
|
|
4961
|
-
for (const file of files) {
|
|
4962
|
-
const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
|
|
4963
|
-
if (!match) continue;
|
|
4964
|
-
try {
|
|
4965
|
-
const filePath = path5.join(logsDir, file);
|
|
4966
|
-
const stat = fs6.statSync(filePath);
|
|
4967
|
-
result.archives.push({
|
|
4968
|
-
name: file,
|
|
4969
|
-
path: filePath,
|
|
4970
|
-
size: stat.size,
|
|
4971
|
-
mtime: stat.mtime,
|
|
4972
|
-
isCurrent: false
|
|
4973
|
-
});
|
|
4974
|
-
} catch {
|
|
4975
|
-
}
|
|
4976
|
-
}
|
|
4977
|
-
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
4978
|
-
return result;
|
|
4979
|
-
}
|
|
4980
|
-
function openUrl(url) {
|
|
4981
|
-
try {
|
|
4982
|
-
const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
|
|
4983
|
-
child.unref();
|
|
4984
|
-
child.on("error", () => {
|
|
4985
|
-
});
|
|
4986
|
-
return true;
|
|
4987
|
-
} catch {
|
|
4988
|
-
return false;
|
|
4989
|
-
}
|
|
4990
|
-
}
|
|
4991
|
-
function openLogFile(logPath, label) {
|
|
4992
|
-
const displayLabel = label || logPath;
|
|
4993
|
-
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
|
|
4994
|
-
const success = openUrl(logPath);
|
|
4995
|
-
if (!success) {
|
|
4996
|
-
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
4997
|
-
}
|
|
4998
|
-
}
|
|
4999
|
-
function viewLogWithTail(logPath, options) {
|
|
5000
|
-
const follow = options?.follow;
|
|
5001
|
-
const lines = options?.lines || 100;
|
|
5002
|
-
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
5003
|
-
if (follow) {
|
|
5004
|
-
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
5005
|
-
} else {
|
|
5006
|
-
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
5007
|
-
`);
|
|
5008
|
-
}
|
|
5009
|
-
const tailArgs = [];
|
|
5010
|
-
if (follow) tailArgs.push("-f");
|
|
5011
|
-
tailArgs.push("-n", lines.toString());
|
|
5012
|
-
tailArgs.push(logPath);
|
|
5013
|
-
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5014
|
-
if (follow) setSilentSigint(true);
|
|
5015
|
-
tail.on("close", () => process.exit(0));
|
|
5016
|
-
tail.on("error", (e) => {
|
|
5017
|
-
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5018
|
-
process.exit(1);
|
|
5019
|
-
});
|
|
5020
|
-
}
|
|
5021
|
-
|
|
5022
|
-
// src/daemon.ts
|
|
5023
|
-
var SERVICE_TARGET = `system/${LAUNCH_DAEMON_LABEL}`;
|
|
5024
|
-
function assertDaemonLabelSafe() {
|
|
5025
|
-
if (RAW_DAEMON_LABEL_INPUT !== void 0 && !isValidDaemonLabel(RAW_DAEMON_LABEL_INPUT)) {
|
|
5026
|
-
throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_DAEMON_LABEL_INPUT}"`, {
|
|
5027
|
-
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
5028
|
-
hint: [
|
|
5029
|
-
'\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
|
|
5030
|
-
"\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
|
|
5031
|
-
]
|
|
5032
|
-
});
|
|
5033
|
-
}
|
|
5034
|
-
}
|
|
5035
|
-
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
5036
|
-
var DAEMON_BOOT_WAIT_MS = 500;
|
|
5037
|
-
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5038
|
-
function logOversized() {
|
|
5039
|
-
try {
|
|
5040
|
-
return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5041
|
-
} catch {
|
|
5042
|
-
return false;
|
|
5043
|
-
}
|
|
5044
|
-
}
|
|
5045
|
-
function escapeXml(s) {
|
|
5046
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4626
|
+
function escapeXml(s) {
|
|
4627
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
5047
4628
|
}
|
|
5048
4629
|
function buildPlist() {
|
|
5049
4630
|
const programArguments = [PATHS.mihomoBinary, "-d", DIRS.data, "-f", PATHS.configFile];
|
|
@@ -5072,36 +4653,8 @@ ${argsXml}
|
|
|
5072
4653
|
</plist>
|
|
5073
4654
|
`;
|
|
5074
4655
|
}
|
|
5075
|
-
function runSudoScript(scriptBody, opts) {
|
|
5076
|
-
if (!process.stdin.isTTY) {
|
|
5077
|
-
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
5078
|
-
}
|
|
5079
|
-
ensureDirs();
|
|
5080
|
-
const scriptPath = path6.join(DIRS.runtime, opts.file);
|
|
5081
|
-
fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
5082
|
-
fs7.chmodSync(scriptPath, 448);
|
|
5083
|
-
try {
|
|
5084
|
-
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
5085
|
-
if (result.error) throw result.error;
|
|
5086
|
-
if (result.status !== 0) {
|
|
5087
|
-
if (result.status === 1) {
|
|
5088
|
-
throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
5089
|
-
}
|
|
5090
|
-
if (result.status == null) {
|
|
5091
|
-
throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
5092
|
-
}
|
|
5093
|
-
const custom = opts.codeMessages?.[result.status];
|
|
5094
|
-
throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
|
|
5095
|
-
}
|
|
5096
|
-
} finally {
|
|
5097
|
-
try {
|
|
5098
|
-
fs7.unlinkSync(scriptPath);
|
|
5099
|
-
} catch {
|
|
5100
|
-
}
|
|
5101
|
-
}
|
|
5102
|
-
}
|
|
5103
4656
|
function isDaemonEnabled() {
|
|
5104
|
-
return
|
|
4657
|
+
return fs8.existsSync(PATHS.launchDaemonPlist);
|
|
5105
4658
|
}
|
|
5106
4659
|
function getDaemonStatus() {
|
|
5107
4660
|
if (!isDaemonEnabled()) {
|
|
@@ -5115,10 +4668,10 @@ function isDaemonRunning(status) {
|
|
|
5115
4668
|
}
|
|
5116
4669
|
function enableDaemon() {
|
|
5117
4670
|
assertDaemonLabelSafe();
|
|
5118
|
-
if (!
|
|
4671
|
+
if (!fs8.existsSync(PATHS.mihomoBinary)) {
|
|
5119
4672
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
5120
4673
|
}
|
|
5121
|
-
if (!
|
|
4674
|
+
if (!fs8.existsSync(PATHS.configFile)) {
|
|
5122
4675
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
5123
4676
|
}
|
|
5124
4677
|
ensureDirs();
|
|
@@ -5154,7 +4707,7 @@ function enableDaemon() {
|
|
|
5154
4707
|
});
|
|
5155
4708
|
} finally {
|
|
5156
4709
|
try {
|
|
5157
|
-
|
|
4710
|
+
fs8.unlinkSync(stagePath);
|
|
5158
4711
|
} catch {
|
|
5159
4712
|
}
|
|
5160
4713
|
}
|
|
@@ -5215,7 +4768,7 @@ async function tryHotReload() {
|
|
|
5215
4768
|
}
|
|
5216
4769
|
}
|
|
5217
4770
|
async function restartDaemon() {
|
|
5218
|
-
if (!
|
|
4771
|
+
if (!fs8.existsSync(PATHS.launchDaemonPlist)) {
|
|
5219
4772
|
throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
|
|
5220
4773
|
}
|
|
5221
4774
|
if (!logOversized() && await tryHotReload()) return;
|
|
@@ -5493,6 +5046,18 @@ function prepareConfigForStart(mode, subName = "default") {
|
|
|
5493
5046
|
}
|
|
5494
5047
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5495
5048
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5049
|
+
const proxies = buildResult.config.proxies;
|
|
5050
|
+
const proxyGroups = buildResult.config["proxy-groups"];
|
|
5051
|
+
return {
|
|
5052
|
+
buildResult,
|
|
5053
|
+
info: {
|
|
5054
|
+
proxies: proxies ? proxies.length : 0,
|
|
5055
|
+
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
5056
|
+
}
|
|
5057
|
+
};
|
|
5058
|
+
}
|
|
5059
|
+
function commitPreparedConfig(prepared) {
|
|
5060
|
+
const { buildResult } = prepared;
|
|
5496
5061
|
if (buildResult.warnings.length > 0) {
|
|
5497
5062
|
for (const warning of buildResult.warnings) {
|
|
5498
5063
|
console.log(`${colors.yellow("\u81EA\u52A8\u4FEE\u590D:")} ${warning}`);
|
|
@@ -5501,12 +5066,7 @@ function prepareConfigForStart(mode, subName = "default") {
|
|
|
5501
5066
|
}
|
|
5502
5067
|
writeMihomoConfig(buildResult.config);
|
|
5503
5068
|
writeDebugConfig(buildResult);
|
|
5504
|
-
|
|
5505
|
-
const proxyGroups = buildResult.config["proxy-groups"];
|
|
5506
|
-
return {
|
|
5507
|
-
proxies: proxies ? proxies.length : 0,
|
|
5508
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
5509
|
-
};
|
|
5069
|
+
return prepared.info;
|
|
5510
5070
|
}
|
|
5511
5071
|
function needsAutoUpdate(sub) {
|
|
5512
5072
|
if (!sub.updated_at) return true;
|
|
@@ -5517,64 +5077,330 @@ function needsAutoUpdate(sub) {
|
|
|
5517
5077
|
const intervalMs = intervalHours * 60 * 60 * 1e3;
|
|
5518
5078
|
return Date.now() - lastUpdate > intervalMs;
|
|
5519
5079
|
}
|
|
5520
|
-
async function tryUpdateOne(sub, signal) {
|
|
5521
|
-
try {
|
|
5522
|
-
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
5523
|
-
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
5524
|
-
} catch (e) {
|
|
5525
|
-
return { name: sub.name, success: false, error: e.message };
|
|
5080
|
+
async function tryUpdateOne(sub, signal) {
|
|
5081
|
+
try {
|
|
5082
|
+
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
5083
|
+
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
5084
|
+
} catch (e) {
|
|
5085
|
+
return { name: sub.name, success: false, error: e.message };
|
|
5086
|
+
}
|
|
5087
|
+
}
|
|
5088
|
+
function printUpdateResult(r) {
|
|
5089
|
+
if (r.success) {
|
|
5090
|
+
console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
|
|
5091
|
+
} else {
|
|
5092
|
+
console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${(r.error || "").split("\n")[0]})`);
|
|
5093
|
+
}
|
|
5094
|
+
}
|
|
5095
|
+
async function autoUpdateStaleSubscription(options = {}) {
|
|
5096
|
+
const allSubs = getSubscriptionsWithCache();
|
|
5097
|
+
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
5098
|
+
if (staleSubs.length === 0) {
|
|
5099
|
+
return { total: 0, updated: 0, failed: 0 };
|
|
5100
|
+
}
|
|
5101
|
+
if (staleSubs.length === 1) {
|
|
5102
|
+
const sub = staleSubs[0];
|
|
5103
|
+
const interval = resolveUpdateInterval(sub.url, sub.update_interval);
|
|
5104
|
+
console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
|
|
5105
|
+
} else {
|
|
5106
|
+
console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
|
|
5107
|
+
}
|
|
5108
|
+
const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
|
|
5109
|
+
const controller = new AbortController();
|
|
5110
|
+
const results = [];
|
|
5111
|
+
const updatePromise = Promise.all(
|
|
5112
|
+
staleSubs.map(
|
|
5113
|
+
(sub) => tryUpdateOne(sub, controller.signal).then((r) => {
|
|
5114
|
+
results.push(r);
|
|
5115
|
+
return r;
|
|
5116
|
+
})
|
|
5117
|
+
)
|
|
5118
|
+
);
|
|
5119
|
+
try {
|
|
5120
|
+
await withTimeout(updatePromise, timeoutMs);
|
|
5121
|
+
} catch (e) {
|
|
5122
|
+
if (!(e instanceof TimeoutError)) throw e;
|
|
5123
|
+
controller.abort();
|
|
5124
|
+
await updatePromise.catch(() => {
|
|
5125
|
+
});
|
|
5126
|
+
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
5127
|
+
}
|
|
5128
|
+
let updatedCount = 0;
|
|
5129
|
+
for (const r of results) {
|
|
5130
|
+
if (r.success) updatedCount++;
|
|
5131
|
+
printUpdateResult(r);
|
|
5132
|
+
}
|
|
5133
|
+
return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
|
|
5134
|
+
}
|
|
5135
|
+
|
|
5136
|
+
// src/commands/shared.ts
|
|
5137
|
+
import readline from "readline";
|
|
5138
|
+
|
|
5139
|
+
// src/process-start.ts
|
|
5140
|
+
import { spawn } from "child_process";
|
|
5141
|
+
import fs10 from "fs";
|
|
5142
|
+
|
|
5143
|
+
// src/process-stop.ts
|
|
5144
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
5145
|
+
import fs9 from "fs";
|
|
5146
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
5147
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
5148
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
5149
|
+
function clearRuntime() {
|
|
5150
|
+
if (fs9.existsSync(DIRS.runtime)) {
|
|
5151
|
+
rmrf(DIRS.runtime);
|
|
5152
|
+
}
|
|
5153
|
+
ensureDirs();
|
|
5154
|
+
}
|
|
5155
|
+
function clearPid() {
|
|
5156
|
+
if (!fs9.existsSync(PATHS.pidFile)) return;
|
|
5157
|
+
if (isPidFileOwnedByRoot()) {
|
|
5158
|
+
try {
|
|
5159
|
+
spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
5160
|
+
} catch {
|
|
5161
|
+
}
|
|
5162
|
+
} else {
|
|
5163
|
+
try {
|
|
5164
|
+
fs9.unlinkSync(PATHS.pidFile);
|
|
5165
|
+
} catch {
|
|
5166
|
+
}
|
|
5167
|
+
}
|
|
5168
|
+
}
|
|
5169
|
+
function killProcess(pid) {
|
|
5170
|
+
try {
|
|
5171
|
+
process.kill(pid, "SIGKILL");
|
|
5172
|
+
return true;
|
|
5173
|
+
} catch {
|
|
5174
|
+
return false;
|
|
5175
|
+
}
|
|
5176
|
+
}
|
|
5177
|
+
function killAllMihomo(forceSudo = false) {
|
|
5178
|
+
const pattern = MAIN_INSTANCE_PATTERN;
|
|
5179
|
+
if (forceSudo) {
|
|
5180
|
+
try {
|
|
5181
|
+
spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
|
|
5182
|
+
return true;
|
|
5183
|
+
} catch {
|
|
5184
|
+
return false;
|
|
5185
|
+
}
|
|
5186
|
+
} else {
|
|
5187
|
+
try {
|
|
5188
|
+
spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
|
|
5189
|
+
return true;
|
|
5190
|
+
} catch {
|
|
5191
|
+
return false;
|
|
5192
|
+
}
|
|
5193
|
+
}
|
|
5194
|
+
}
|
|
5195
|
+
function cleanupAll(forceSudo = false) {
|
|
5196
|
+
const pids = getMihomoPids();
|
|
5197
|
+
if (pids.length === 0) {
|
|
5198
|
+
clearPid();
|
|
5199
|
+
return { killed: 0, failed: 0, remaining: [] };
|
|
5200
|
+
}
|
|
5201
|
+
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
5202
|
+
const needsSudo = forceSudo || hasRootProcess;
|
|
5203
|
+
let killedCount = 0;
|
|
5204
|
+
const failedPids = [];
|
|
5205
|
+
if (needsSudo) {
|
|
5206
|
+
const success = killAllMihomo(true);
|
|
5207
|
+
if (success) {
|
|
5208
|
+
killedCount = pids.length;
|
|
5209
|
+
} else {
|
|
5210
|
+
failedPids.push(...pids);
|
|
5211
|
+
}
|
|
5212
|
+
} else {
|
|
5213
|
+
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
5214
|
+
killAllMihomo(false);
|
|
5215
|
+
killedCount = pids.length;
|
|
5216
|
+
} else {
|
|
5217
|
+
for (const pid of pids) {
|
|
5218
|
+
if (killProcess(pid)) {
|
|
5219
|
+
killedCount++;
|
|
5220
|
+
} else {
|
|
5221
|
+
failedPids.push(pid);
|
|
5222
|
+
}
|
|
5223
|
+
}
|
|
5224
|
+
}
|
|
5225
|
+
}
|
|
5226
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
5227
|
+
if (getMihomoPids().length === 0) break;
|
|
5228
|
+
sleepSync(PROCESS_WAIT_INTERVAL);
|
|
5229
|
+
}
|
|
5230
|
+
clearPid();
|
|
5231
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
5232
|
+
}
|
|
5233
|
+
function stop(forceSudo = false) {
|
|
5234
|
+
const allPids = getMihomoPids();
|
|
5235
|
+
if (allPids.length === 0) {
|
|
5236
|
+
clearPid();
|
|
5237
|
+
clearRuntime();
|
|
5238
|
+
return { success: true, notRunning: true };
|
|
5239
|
+
}
|
|
5240
|
+
const result = cleanupAll(forceSudo);
|
|
5241
|
+
const remaining = getMihomoPids();
|
|
5242
|
+
if (remaining.length > 0) {
|
|
5243
|
+
console.log("");
|
|
5244
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5245
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5246
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
5247
|
+
console.log("");
|
|
5248
|
+
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
5249
|
+
}
|
|
5250
|
+
clearRuntime();
|
|
5251
|
+
return { success: true, killed: result.killed };
|
|
5252
|
+
}
|
|
5253
|
+
|
|
5254
|
+
// src/process-start.ts
|
|
5255
|
+
var STARTUP_WAIT_MS = 800;
|
|
5256
|
+
var TUN_MODE_POST_WAIT_MS = 500;
|
|
5257
|
+
function savePid(pid) {
|
|
5258
|
+
ensureDirs();
|
|
5259
|
+
fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
5260
|
+
}
|
|
5261
|
+
function buildTunLaunchScript() {
|
|
5262
|
+
const binary = shellQuote(PATHS.mihomoBinary);
|
|
5263
|
+
const configFile = shellQuote(PATHS.configFile);
|
|
5264
|
+
const logFile = shellQuote(PATHS.logFile);
|
|
5265
|
+
const pidFile = shellQuote(PATHS.pidFile);
|
|
5266
|
+
const dataDir = shellQuote(DIRS.data);
|
|
5267
|
+
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
5268
|
+
return `#!/bin/bash
|
|
5269
|
+
BINARY=${binary}
|
|
5270
|
+
CONFIG_FILE=${configFile}
|
|
5271
|
+
LOG_FILE=${logFile}
|
|
5272
|
+
PID_FILE=${pidFile}
|
|
5273
|
+
DATA_DIR=${dataDir}
|
|
5274
|
+
KILL_PATTERN=${killPattern}
|
|
5275
|
+
|
|
5276
|
+
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
5277
|
+
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
5278
|
+
sleep 0.2
|
|
5279
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5280
|
+
|
|
5281
|
+
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
5282
|
+
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
5283
|
+
|
|
5284
|
+
# \u542F\u52A8
|
|
5285
|
+
cd /tmp
|
|
5286
|
+
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
5287
|
+
NEW_PID=$!
|
|
5288
|
+
echo \${NEW_PID} > "\${PID_FILE}"
|
|
5289
|
+
|
|
5290
|
+
# \u9A8C\u8BC1
|
|
5291
|
+
for i in 1 2 3 4 5; do
|
|
5292
|
+
sleep 0.4
|
|
5293
|
+
if kill -0 \${NEW_PID} 2>/dev/null; then
|
|
5294
|
+
exit 0
|
|
5295
|
+
fi
|
|
5296
|
+
done
|
|
5297
|
+
|
|
5298
|
+
# \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
|
|
5299
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5300
|
+
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
5301
|
+
echo ""
|
|
5302
|
+
echo "--- \u65E5\u5FD7 ---"
|
|
5303
|
+
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
5304
|
+
exit 2
|
|
5305
|
+
`;
|
|
5306
|
+
}
|
|
5307
|
+
async function start(mode = "mixed") {
|
|
5308
|
+
const isTunMode = mode === "tun";
|
|
5309
|
+
ensureDirs();
|
|
5310
|
+
rotateAndCleanupLogs();
|
|
5311
|
+
const binary = PATHS.mihomoBinary;
|
|
5312
|
+
if (!fs10.existsSync(binary)) {
|
|
5313
|
+
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
5526
5314
|
}
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
|
|
5532
|
-
|
|
5315
|
+
const configFile = PATHS.configFile;
|
|
5316
|
+
if (!fs10.existsSync(configFile)) {
|
|
5317
|
+
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
5318
|
+
}
|
|
5319
|
+
const staleState = checkStaleState();
|
|
5320
|
+
if (isTunMode) {
|
|
5321
|
+
return startTunMode(staleState);
|
|
5533
5322
|
}
|
|
5323
|
+
return startMixedMode(staleState);
|
|
5534
5324
|
}
|
|
5535
|
-
async function
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5539
|
-
|
|
5325
|
+
async function startMixedMode(staleState) {
|
|
5326
|
+
if (staleState.needsCleanup) {
|
|
5327
|
+
if (staleState.needsSudo) {
|
|
5328
|
+
console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
|
|
5329
|
+
console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
|
|
5330
|
+
console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
|
|
5331
|
+
throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
|
|
5332
|
+
}
|
|
5333
|
+
const cleanupResult = cleanupAll();
|
|
5334
|
+
if (cleanupResult.killed > 0) {
|
|
5335
|
+
console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
|
|
5336
|
+
}
|
|
5540
5337
|
}
|
|
5541
|
-
if (
|
|
5542
|
-
const
|
|
5543
|
-
|
|
5544
|
-
console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
|
|
5545
|
-
} else {
|
|
5546
|
-
console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
|
|
5338
|
+
if (isRunning()) {
|
|
5339
|
+
const pid2 = getPid();
|
|
5340
|
+
return { success: true, pid: pid2, alreadyRunning: true };
|
|
5547
5341
|
}
|
|
5548
|
-
const
|
|
5549
|
-
const
|
|
5550
|
-
const
|
|
5551
|
-
|
|
5552
|
-
|
|
5553
|
-
(
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
await withTimeout(updatePromise, timeoutMs);
|
|
5561
|
-
} catch (e) {
|
|
5562
|
-
if (!(e instanceof TimeoutError)) throw e;
|
|
5563
|
-
controller.abort();
|
|
5564
|
-
await updatePromise.catch(() => {
|
|
5565
|
-
});
|
|
5566
|
-
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
5342
|
+
const configFile = PATHS.configFile;
|
|
5343
|
+
const logFile = PATHS.logFile;
|
|
5344
|
+
const args = ["-d", DIRS.data, "-f", configFile];
|
|
5345
|
+
if (fs10.existsSync(logFile)) {
|
|
5346
|
+
try {
|
|
5347
|
+
fs10.accessSync(logFile, fs10.constants.W_OK);
|
|
5348
|
+
} catch {
|
|
5349
|
+
try {
|
|
5350
|
+
fs10.unlinkSync(logFile);
|
|
5351
|
+
} catch {
|
|
5352
|
+
}
|
|
5353
|
+
}
|
|
5567
5354
|
}
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5355
|
+
const logFd = fs10.openSync(logFile, "a");
|
|
5356
|
+
const child = spawn(PATHS.mihomoBinary, args, {
|
|
5357
|
+
detached: true,
|
|
5358
|
+
stdio: ["ignore", logFd, logFd]
|
|
5359
|
+
});
|
|
5360
|
+
child.on("error", () => {
|
|
5361
|
+
});
|
|
5362
|
+
fs10.closeSync(logFd);
|
|
5363
|
+
child.unref();
|
|
5364
|
+
const pid = child.pid;
|
|
5365
|
+
if (!pid) {
|
|
5366
|
+
clearPid();
|
|
5367
|
+
throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
|
|
5572
5368
|
}
|
|
5573
|
-
|
|
5369
|
+
savePid(pid);
|
|
5370
|
+
await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
|
|
5371
|
+
if (!isRunning()) {
|
|
5372
|
+
clearPid();
|
|
5373
|
+
let errorMsg = "\u542F\u52A8\u5931\u8D25";
|
|
5374
|
+
if (fs10.existsSync(logFile)) {
|
|
5375
|
+
try {
|
|
5376
|
+
const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
|
|
5377
|
+
if (logs.trim()) {
|
|
5378
|
+
errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
|
|
5379
|
+
}
|
|
5380
|
+
} catch {
|
|
5381
|
+
}
|
|
5382
|
+
}
|
|
5383
|
+
throw new Error(errorMsg);
|
|
5384
|
+
}
|
|
5385
|
+
return { success: true, pid, mode: "mixed" };
|
|
5386
|
+
}
|
|
5387
|
+
async function startTunMode(staleState) {
|
|
5388
|
+
if (staleState.needsCleanup) {
|
|
5389
|
+
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
5390
|
+
}
|
|
5391
|
+
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
5392
|
+
runSudoScript(buildTunLaunchScript(), {
|
|
5393
|
+
action: "TUN \u542F\u52A8",
|
|
5394
|
+
file: "launch-tun.sh",
|
|
5395
|
+
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
5396
|
+
});
|
|
5397
|
+
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
5398
|
+
const finalPid = getPid();
|
|
5399
|
+
if (!finalPid) {
|
|
5400
|
+
throw new Error("TUN \u542F\u52A8\u5931\u8D25");
|
|
5401
|
+
}
|
|
5402
|
+
return { success: true, pid: finalPid, mode: "tun" };
|
|
5574
5403
|
}
|
|
5575
|
-
|
|
5576
|
-
// src/commands/shared.ts
|
|
5577
|
-
import readline from "readline";
|
|
5578
5404
|
|
|
5579
5405
|
// src/runtime.ts
|
|
5580
5406
|
function getRuntimeMode() {
|
|
@@ -5584,10 +5410,10 @@ function getRuntimeMode() {
|
|
|
5584
5410
|
function getRunningState() {
|
|
5585
5411
|
if (isDaemonEnabled()) {
|
|
5586
5412
|
const daemon = getDaemonStatus();
|
|
5587
|
-
return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true };
|
|
5413
|
+
return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
|
|
5588
5414
|
}
|
|
5589
5415
|
const status = getStatus();
|
|
5590
|
-
return { running: status.running, pid: status.pid, daemon: false };
|
|
5416
|
+
return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
|
|
5591
5417
|
}
|
|
5592
5418
|
function isRestartNeededOnChange() {
|
|
5593
5419
|
return isDaemonEnabled() || getStatus().running;
|
|
@@ -5604,9 +5430,36 @@ async function launchOrRestart(mode) {
|
|
|
5604
5430
|
|
|
5605
5431
|
// src/ssh.ts
|
|
5606
5432
|
import { spawn as spawn2 } from "child_process";
|
|
5607
|
-
import
|
|
5433
|
+
import fs11 from "fs";
|
|
5608
5434
|
import net from "net";
|
|
5609
5435
|
import path7 from "path";
|
|
5436
|
+
|
|
5437
|
+
// src/lifecycle.ts
|
|
5438
|
+
var cleanupFns = /* @__PURE__ */ new Set();
|
|
5439
|
+
var silentSigint = false;
|
|
5440
|
+
function setSilentSigint(value) {
|
|
5441
|
+
silentSigint = value;
|
|
5442
|
+
}
|
|
5443
|
+
function isSilentSigint() {
|
|
5444
|
+
return silentSigint;
|
|
5445
|
+
}
|
|
5446
|
+
function registerCleanup(fn) {
|
|
5447
|
+
cleanupFns.add(fn);
|
|
5448
|
+
return () => {
|
|
5449
|
+
cleanupFns.delete(fn);
|
|
5450
|
+
};
|
|
5451
|
+
}
|
|
5452
|
+
function runCleanup() {
|
|
5453
|
+
for (const fn of cleanupFns) {
|
|
5454
|
+
try {
|
|
5455
|
+
fn();
|
|
5456
|
+
} catch {
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
cleanupFns.clear();
|
|
5460
|
+
}
|
|
5461
|
+
|
|
5462
|
+
// src/ssh.ts
|
|
5610
5463
|
var PORT_PROBE_TIMEOUT_MS = 300;
|
|
5611
5464
|
var STOP_WAIT_ATTEMPTS = 20;
|
|
5612
5465
|
var STOP_WAIT_INTERVAL = 100;
|
|
@@ -5694,7 +5547,7 @@ function getSshRuntimePath(name) {
|
|
|
5694
5547
|
}
|
|
5695
5548
|
function readSshRuntime(name) {
|
|
5696
5549
|
try {
|
|
5697
|
-
const raw =
|
|
5550
|
+
const raw = fs11.readFileSync(getSshRuntimePath(name), "utf8");
|
|
5698
5551
|
const parsed = JSON.parse(raw);
|
|
5699
5552
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
5700
5553
|
const r = parsed;
|
|
@@ -5715,7 +5568,7 @@ function writeSshRuntime(name, runtime) {
|
|
|
5715
5568
|
}
|
|
5716
5569
|
function clearSshRuntime(name) {
|
|
5717
5570
|
try {
|
|
5718
|
-
|
|
5571
|
+
fs11.rmSync(getSshRuntimePath(name), { force: true });
|
|
5719
5572
|
} catch {
|
|
5720
5573
|
}
|
|
5721
5574
|
}
|
|
@@ -5803,14 +5656,14 @@ async function startSshTunnel(name, options) {
|
|
|
5803
5656
|
}
|
|
5804
5657
|
ensureDirs();
|
|
5805
5658
|
const logPath = getSshLogPath(name);
|
|
5806
|
-
const logFd =
|
|
5659
|
+
const logFd = fs11.openSync(logPath, "w");
|
|
5807
5660
|
const child = spawn2("ssh", buildSshArgs(config), {
|
|
5808
5661
|
detached: true,
|
|
5809
5662
|
stdio: ["ignore", logFd, logFd]
|
|
5810
5663
|
});
|
|
5811
5664
|
child.on("error", () => {
|
|
5812
5665
|
});
|
|
5813
|
-
|
|
5666
|
+
fs11.closeSync(logFd);
|
|
5814
5667
|
child.unref();
|
|
5815
5668
|
const pid = child.pid;
|
|
5816
5669
|
if (!pid) {
|
|
@@ -5855,7 +5708,7 @@ async function startSshTunnel(name, options) {
|
|
|
5855
5708
|
}
|
|
5856
5709
|
function readLogTail(logPath, maxLines = 5) {
|
|
5857
5710
|
try {
|
|
5858
|
-
const content =
|
|
5711
|
+
const content = fs11.readFileSync(logPath, "utf8").trim();
|
|
5859
5712
|
if (!content) return [];
|
|
5860
5713
|
return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
|
|
5861
5714
|
} catch {
|
|
@@ -5934,13 +5787,12 @@ function stopAllSshTunnels() {
|
|
|
5934
5787
|
|
|
5935
5788
|
// src/commands/status.ts
|
|
5936
5789
|
async function printStatus() {
|
|
5937
|
-
const status = getStatus();
|
|
5938
5790
|
const state = getRunningState();
|
|
5939
5791
|
const info = getConfigInfo();
|
|
5940
5792
|
const overwriteEnabled = isOverwriteEnabled();
|
|
5941
5793
|
const overwriteFiles = listOverwriteFile().files;
|
|
5942
5794
|
const activeSub = getActiveSubscription();
|
|
5943
|
-
const { running, pid, daemon: daemonManaged } = state;
|
|
5795
|
+
const { running, pid, daemon: daemonManaged, processInfo } = state;
|
|
5944
5796
|
console.log("");
|
|
5945
5797
|
let modeLabel = "";
|
|
5946
5798
|
if (info) {
|
|
@@ -5948,11 +5800,11 @@ async function printStatus() {
|
|
|
5948
5800
|
}
|
|
5949
5801
|
const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
|
|
5950
5802
|
console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
|
|
5951
|
-
console.log(`${colors.gray("\u5185\u6838: ")}${
|
|
5803
|
+
console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
|
|
5952
5804
|
if (pid) {
|
|
5953
5805
|
console.log(`${colors.gray("PID: ")}${pid}`);
|
|
5954
|
-
if (!daemonManaged &&
|
|
5955
|
-
console.log(`${colors.gray("\u5185\u5B58: ")}${
|
|
5806
|
+
if (!daemonManaged && processInfo) {
|
|
5807
|
+
console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
|
|
5956
5808
|
}
|
|
5957
5809
|
}
|
|
5958
5810
|
if (info) {
|
|
@@ -5975,13 +5827,9 @@ async function printStatus() {
|
|
|
5975
5827
|
}
|
|
5976
5828
|
console.log(subLine);
|
|
5977
5829
|
const cached = getSubscriptionsWithCache().find((s) => s.name === activeSub.name);
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
|
|
5981
|
-
if (cached.total && cached.total > 0) {
|
|
5982
|
-
trafficLine += ` (${Math.min(used / cached.total * 100, 100).toFixed(1)}%)`;
|
|
5983
|
-
}
|
|
5984
|
-
console.log(trafficLine);
|
|
5830
|
+
const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
|
|
5831
|
+
if (traffic) {
|
|
5832
|
+
console.log(`${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
5985
5833
|
}
|
|
5986
5834
|
if (cached?.expire !== void 0) {
|
|
5987
5835
|
console.log(`${colors.gray("\u5230\u671F: ")}${formatTimestamp(cached.expire)}`);
|
|
@@ -6007,7 +5855,7 @@ async function printStatus() {
|
|
|
6007
5855
|
const label = `${s.config.name}:${s.config.port}`;
|
|
6008
5856
|
if (s.state === "running") return colors.green(label);
|
|
6009
5857
|
if (s.state === "dead-port") return colors.yellow(`${label} \u5047\u6D3B`);
|
|
6010
|
-
return colors.gray(label);
|
|
5858
|
+
return colors.gray(`${label} \u672A\u8FD0\u884C`);
|
|
6011
5859
|
});
|
|
6012
5860
|
console.log(`${colors.gray("\u96A7\u9053: ")}${parts.join(", ")}`);
|
|
6013
5861
|
}
|
|
@@ -6065,12 +5913,16 @@ async function startAutoSshTunnelsWithWarning() {
|
|
|
6065
5913
|
console.log("");
|
|
6066
5914
|
}
|
|
6067
5915
|
}
|
|
6068
|
-
|
|
6069
|
-
const
|
|
5916
|
+
function resolveStartMode(args) {
|
|
5917
|
+
const modeArg = getNonFlagArg(args, 1);
|
|
5918
|
+
const modeToken = modeArg?.toLowerCase();
|
|
6070
5919
|
if (modeToken !== void 0 && modeToken !== "tun" && modeToken !== "mixed") {
|
|
6071
|
-
throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${
|
|
5920
|
+
throw new CliError(`\u672A\u77E5\u7684\u542F\u52A8\u6A21\u5F0F: ${modeArg}`, { hint: "\u7528\u6CD5: mihomo start [tun|mixed]\uFF08\u9ED8\u8BA4 mixed\uFF09" });
|
|
6072
5921
|
}
|
|
6073
|
-
|
|
5922
|
+
return modeToken === "tun" ? "tun" : "mixed";
|
|
5923
|
+
}
|
|
5924
|
+
async function cmdStart(args) {
|
|
5925
|
+
const targetMode = resolveStartMode(args);
|
|
6074
5926
|
if (!hasKernel()) {
|
|
6075
5927
|
throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
|
|
6076
5928
|
}
|
|
@@ -6085,8 +5937,15 @@ async function cmdStart(args) {
|
|
|
6085
5937
|
if (!skipUpdate) {
|
|
6086
5938
|
await autoUpdateStaleSubscription({ timeout: updateTimeout });
|
|
6087
5939
|
}
|
|
5940
|
+
let prepared;
|
|
5941
|
+
try {
|
|
5942
|
+
prepared = prepareConfigForStart(targetMode, sub.name);
|
|
5943
|
+
} catch (e) {
|
|
5944
|
+
if (e instanceof CliError) throw e;
|
|
5945
|
+
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
5946
|
+
}
|
|
6088
5947
|
if (!daemonEnabled) {
|
|
6089
|
-
if (hasRootResidue()) {
|
|
5948
|
+
if (targetMode !== "tun" && hasRootResidue()) {
|
|
6090
5949
|
throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
|
|
6091
5950
|
hint: [`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`, "\u6216\u5207\u6362\u5230 TUN \u6A21\u5F0F\u542F\u52A8\uFF08\u81EA\u52A8\u6E05\u7406\uFF09: mihomo start tun"]
|
|
6092
5951
|
});
|
|
@@ -6103,13 +5962,7 @@ async function cmdStart(args) {
|
|
|
6103
5962
|
`);
|
|
6104
5963
|
}
|
|
6105
5964
|
}
|
|
6106
|
-
|
|
6107
|
-
try {
|
|
6108
|
-
configInfo = prepareConfigForStart(targetMode, sub.name);
|
|
6109
|
-
} catch (e) {
|
|
6110
|
-
if (e instanceof CliError) throw e;
|
|
6111
|
-
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
6112
|
-
}
|
|
5965
|
+
const configInfo = commitPreparedConfig(prepared);
|
|
6113
5966
|
const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
|
|
6114
5967
|
console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
6115
5968
|
try {
|
|
@@ -6148,6 +6001,12 @@ async function confirmPrompt(question) {
|
|
|
6148
6001
|
});
|
|
6149
6002
|
return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
|
|
6150
6003
|
}
|
|
6004
|
+
async function confirmOrThrow(question, opts) {
|
|
6005
|
+
if (!process.stdin.isTTY) {
|
|
6006
|
+
throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
|
|
6007
|
+
}
|
|
6008
|
+
return confirmPrompt(question);
|
|
6009
|
+
}
|
|
6151
6010
|
async function restartToApply(args) {
|
|
6152
6011
|
if (!isRestartNeededOnChange()) return false;
|
|
6153
6012
|
const currentMode = getRuntimeMode();
|
|
@@ -6181,7 +6040,7 @@ async function daemonOn() {
|
|
|
6181
6040
|
const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
6182
6041
|
let configInfo;
|
|
6183
6042
|
try {
|
|
6184
|
-
configInfo = prepareConfigForStart("mixed", sub.name);
|
|
6043
|
+
configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
|
|
6185
6044
|
} catch (e) {
|
|
6186
6045
|
if (e instanceof CliError) throw e;
|
|
6187
6046
|
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
@@ -6219,29 +6078,76 @@ function daemonOff() {
|
|
|
6219
6078
|
console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
|
|
6220
6079
|
console.log("");
|
|
6221
6080
|
}
|
|
6222
|
-
function printStatusView() {
|
|
6223
|
-
console.log("");
|
|
6224
|
-
printDaemonStatus();
|
|
6225
|
-
}
|
|
6226
6081
|
var SUBCOMMANDS = [
|
|
6227
6082
|
{ name: "on", aliases: ["enable"], handler: daemonOn },
|
|
6228
|
-
{ name: "off", aliases: ["disable"], handler: daemonOff }
|
|
6229
|
-
{ name: "status", handler: printStatusView }
|
|
6083
|
+
{ name: "off", aliases: ["disable"], handler: daemonOff }
|
|
6230
6084
|
];
|
|
6231
6085
|
async function cmdDaemon(args) {
|
|
6232
6086
|
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
6233
6087
|
// 无 action → 显示状态;未知 action → 报错
|
|
6234
|
-
fallback:
|
|
6088
|
+
fallback: () => {
|
|
6089
|
+
console.log("");
|
|
6090
|
+
printDaemonStatus();
|
|
6091
|
+
},
|
|
6235
6092
|
onUnknown: (action) => {
|
|
6236
6093
|
const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6237
6094
|
const suggestion = suggestSimilar(action, names);
|
|
6238
6095
|
throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
|
|
6239
|
-
hint: [
|
|
6096
|
+
hint: [
|
|
6097
|
+
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
6098
|
+
"",
|
|
6099
|
+
"\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
|
|
6100
|
+
"\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
|
|
6101
|
+
]
|
|
6240
6102
|
});
|
|
6241
6103
|
}
|
|
6242
6104
|
});
|
|
6243
6105
|
}
|
|
6244
6106
|
|
|
6107
|
+
// src/open.ts
|
|
6108
|
+
import { spawn as spawn3 } from "child_process";
|
|
6109
|
+
function openUrl(url) {
|
|
6110
|
+
try {
|
|
6111
|
+
const child = spawn3("open", ["--", url], { stdio: "ignore", detached: true });
|
|
6112
|
+
child.unref();
|
|
6113
|
+
child.on("error", () => {
|
|
6114
|
+
});
|
|
6115
|
+
return true;
|
|
6116
|
+
} catch {
|
|
6117
|
+
return false;
|
|
6118
|
+
}
|
|
6119
|
+
}
|
|
6120
|
+
function openLogFile(logPath, label) {
|
|
6121
|
+
const displayLabel = label || logPath;
|
|
6122
|
+
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
|
|
6123
|
+
const success = openUrl(logPath);
|
|
6124
|
+
if (!success) {
|
|
6125
|
+
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
6126
|
+
}
|
|
6127
|
+
}
|
|
6128
|
+
function viewLogWithTail(logPath, options) {
|
|
6129
|
+
const follow = options?.follow;
|
|
6130
|
+
const lines = options?.lines || 100;
|
|
6131
|
+
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
6132
|
+
if (follow) {
|
|
6133
|
+
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
6134
|
+
} else {
|
|
6135
|
+
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
6136
|
+
`);
|
|
6137
|
+
}
|
|
6138
|
+
const tailArgs = [];
|
|
6139
|
+
if (follow) tailArgs.push("-f");
|
|
6140
|
+
tailArgs.push("-n", lines.toString());
|
|
6141
|
+
tailArgs.push(logPath);
|
|
6142
|
+
const tail = spawn3("tail", tailArgs, { stdio: "inherit" });
|
|
6143
|
+
if (follow) setSilentSigint(true);
|
|
6144
|
+
tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
|
|
6145
|
+
tail.on("error", (e) => {
|
|
6146
|
+
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
6147
|
+
process.exit(1);
|
|
6148
|
+
});
|
|
6149
|
+
}
|
|
6150
|
+
|
|
6245
6151
|
// src/commands/directory.ts
|
|
6246
6152
|
function openDirectory(args) {
|
|
6247
6153
|
const target = args[2];
|
|
@@ -6302,8 +6208,8 @@ async function cmdDirectory(args) {
|
|
|
6302
6208
|
}
|
|
6303
6209
|
|
|
6304
6210
|
// src/kernel.ts
|
|
6305
|
-
import { spawnSync as
|
|
6306
|
-
import
|
|
6211
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
6212
|
+
import fs12 from "fs";
|
|
6307
6213
|
import path8 from "path";
|
|
6308
6214
|
|
|
6309
6215
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
@@ -6447,10 +6353,10 @@ async function checkUpdate() {
|
|
|
6447
6353
|
}
|
|
6448
6354
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
6449
6355
|
if (maxDepth <= 0) return null;
|
|
6450
|
-
const files =
|
|
6356
|
+
const files = fs12.readdirSync(dir);
|
|
6451
6357
|
for (const f of files) {
|
|
6452
6358
|
const fullPath = path8.join(dir, f);
|
|
6453
|
-
const stat =
|
|
6359
|
+
const stat = fs12.lstatSync(fullPath);
|
|
6454
6360
|
if (stat.isDirectory()) {
|
|
6455
6361
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
6456
6362
|
if (found) return found;
|
|
@@ -6487,7 +6393,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6487
6393
|
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
6488
6394
|
}
|
|
6489
6395
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
6490
|
-
const curlResult =
|
|
6396
|
+
const curlResult = spawnSync5(
|
|
6491
6397
|
"curl",
|
|
6492
6398
|
[
|
|
6493
6399
|
"-L",
|
|
@@ -6516,19 +6422,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6516
6422
|
}
|
|
6517
6423
|
if (curlResult.status !== 0) {
|
|
6518
6424
|
try {
|
|
6519
|
-
|
|
6425
|
+
fs12.unlinkSync(tempPath);
|
|
6520
6426
|
} catch {
|
|
6521
6427
|
}
|
|
6522
6428
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
6523
6429
|
}
|
|
6524
|
-
if (!
|
|
6430
|
+
if (!fs12.existsSync(tempPath)) {
|
|
6525
6431
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
6526
6432
|
}
|
|
6527
6433
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
6528
|
-
const actual =
|
|
6434
|
+
const actual = fs12.statSync(tempPath).size;
|
|
6529
6435
|
if (actual !== asset.size) {
|
|
6530
6436
|
try {
|
|
6531
|
-
|
|
6437
|
+
fs12.unlinkSync(tempPath);
|
|
6532
6438
|
} catch {
|
|
6533
6439
|
}
|
|
6534
6440
|
throw new Error(
|
|
@@ -6544,7 +6450,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6544
6450
|
let extractedBinary = null;
|
|
6545
6451
|
try {
|
|
6546
6452
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
6547
|
-
const listResult =
|
|
6453
|
+
const listResult = spawnSync5("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6548
6454
|
if (listResult.error) throw listResult.error;
|
|
6549
6455
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
6550
6456
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6552,7 +6458,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6552
6458
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
6553
6459
|
}
|
|
6554
6460
|
}
|
|
6555
|
-
const typeResult =
|
|
6461
|
+
const typeResult = spawnSync5("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6556
6462
|
if (typeResult.error) throw typeResult.error;
|
|
6557
6463
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
6558
6464
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6561,7 +6467,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6561
6467
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
6562
6468
|
}
|
|
6563
6469
|
}
|
|
6564
|
-
const tarResult =
|
|
6470
|
+
const tarResult = spawnSync5("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
|
|
6565
6471
|
stdio: ["ignore", "ignore", "inherit"],
|
|
6566
6472
|
timeout: 6e4
|
|
6567
6473
|
});
|
|
@@ -6570,15 +6476,15 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6570
6476
|
} else if (tempPath.endsWith(".gz")) {
|
|
6571
6477
|
const baseName = path8.basename(tempPath, ".gz");
|
|
6572
6478
|
const outputPath = path8.join(extractPath, baseName);
|
|
6573
|
-
const gzipResult =
|
|
6479
|
+
const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
6574
6480
|
if (gzipResult.error) throw gzipResult.error;
|
|
6575
6481
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
6576
|
-
|
|
6482
|
+
fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
6577
6483
|
extractedBinary = outputPath;
|
|
6578
6484
|
}
|
|
6579
6485
|
} catch (e) {
|
|
6580
6486
|
try {
|
|
6581
|
-
|
|
6487
|
+
fs12.unlinkSync(tempPath);
|
|
6582
6488
|
} catch {
|
|
6583
6489
|
}
|
|
6584
6490
|
throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
|
|
@@ -6586,35 +6492,35 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6586
6492
|
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
6587
6493
|
if (!foundBinary) {
|
|
6588
6494
|
try {
|
|
6589
|
-
|
|
6495
|
+
fs12.unlinkSync(tempPath);
|
|
6590
6496
|
} catch {
|
|
6591
6497
|
}
|
|
6592
6498
|
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
6593
6499
|
}
|
|
6594
6500
|
const targetPath = PATHS.mihomoBinary;
|
|
6595
6501
|
if (foundBinary !== targetPath) {
|
|
6596
|
-
if (
|
|
6597
|
-
|
|
6502
|
+
if (fs12.existsSync(targetPath)) {
|
|
6503
|
+
fs12.chmodSync(targetPath, 493);
|
|
6598
6504
|
try {
|
|
6599
|
-
|
|
6505
|
+
fs12.unlinkSync(targetPath);
|
|
6600
6506
|
} catch {
|
|
6601
6507
|
}
|
|
6602
6508
|
}
|
|
6603
|
-
|
|
6509
|
+
fs12.renameSync(foundBinary, targetPath);
|
|
6604
6510
|
}
|
|
6605
|
-
|
|
6511
|
+
fs12.chmodSync(targetPath, 493);
|
|
6606
6512
|
if (progressCallback) {
|
|
6607
6513
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
6608
6514
|
}
|
|
6609
|
-
const check =
|
|
6515
|
+
const check = spawnSync5(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6610
6516
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
6611
6517
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
6612
6518
|
try {
|
|
6613
|
-
|
|
6519
|
+
fs12.unlinkSync(targetPath);
|
|
6614
6520
|
} catch {
|
|
6615
6521
|
}
|
|
6616
6522
|
try {
|
|
6617
|
-
|
|
6523
|
+
fs12.unlinkSync(tempPath);
|
|
6618
6524
|
} catch {
|
|
6619
6525
|
}
|
|
6620
6526
|
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
|
|
@@ -6622,7 +6528,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6622
6528
|
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
6623
6529
|
}
|
|
6624
6530
|
try {
|
|
6625
|
-
|
|
6531
|
+
fs12.unlinkSync(tempPath);
|
|
6626
6532
|
} catch {
|
|
6627
6533
|
}
|
|
6628
6534
|
clearKernelVersionCache();
|
|
@@ -6630,7 +6536,25 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6630
6536
|
}
|
|
6631
6537
|
|
|
6632
6538
|
// src/commands/kernel.ts
|
|
6539
|
+
function assertKnownKernelFlags(args) {
|
|
6540
|
+
const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror", "--no-mirror", "--direct"]);
|
|
6541
|
+
const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all="));
|
|
6542
|
+
if (unknown.length > 0) {
|
|
6543
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
|
|
6544
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6545
|
+
hint: [
|
|
6546
|
+
"",
|
|
6547
|
+
"\u53EF\u7528\u9009\u9879:",
|
|
6548
|
+
" --mirror [\u955C\u50CF] \u4E0B\u8F7D\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4 v6.gh-proxy.org\uFF09",
|
|
6549
|
+
" --no-mirror \u663E\u5F0F\u76F4\u8FDE\uFF08\u9ED8\u8BA4\u884C\u4E3A\uFF09",
|
|
6550
|
+
"",
|
|
6551
|
+
`\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
|
|
6552
|
+
]
|
|
6553
|
+
});
|
|
6554
|
+
}
|
|
6555
|
+
}
|
|
6633
6556
|
async function cmdKernel(args) {
|
|
6557
|
+
assertKnownKernelFlags(args);
|
|
6634
6558
|
const mirrorInfo = parseMirrorArg(args);
|
|
6635
6559
|
const effectiveMirror = mirrorInfo.mirror;
|
|
6636
6560
|
if (effectiveMirror) {
|
|
@@ -6676,18 +6600,12 @@ async function cmdKernel(args) {
|
|
|
6676
6600
|
}
|
|
6677
6601
|
|
|
6678
6602
|
// src/commands/log.ts
|
|
6679
|
-
function cmdLog(args) {
|
|
6680
|
-
const logPath = getLogPath();
|
|
6681
|
-
if (hasFlag(args, "-o", "--open")) {
|
|
6682
|
-
openLogFile(logPath);
|
|
6683
|
-
return;
|
|
6684
|
-
}
|
|
6685
|
-
viewLogWithTail(logPath, { follow: true, lines: 50 });
|
|
6686
|
-
}
|
|
6687
6603
|
function cmdLogs(args) {
|
|
6688
|
-
const targetName = getNonFlagArg(args, 1);
|
|
6689
6604
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
6690
6605
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
6606
|
+
const follow = hasFlag(args, "-f", "--follow");
|
|
6607
|
+
const hasLinesFlag = args.some((a) => a === "-n" || a === "--lines" || a.startsWith("--lines="));
|
|
6608
|
+
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
6691
6609
|
if (targetName) {
|
|
6692
6610
|
let logPath;
|
|
6693
6611
|
if (targetName === "0") {
|
|
@@ -6707,7 +6625,7 @@ function cmdLogs(args) {
|
|
|
6707
6625
|
openLogFile(logPath);
|
|
6708
6626
|
return;
|
|
6709
6627
|
}
|
|
6710
|
-
viewLogWithTail(logPath, { follow
|
|
6628
|
+
viewLogWithTail(logPath, { follow, lines });
|
|
6711
6629
|
return;
|
|
6712
6630
|
}
|
|
6713
6631
|
const logs = listLogs();
|
|
@@ -6742,6 +6660,7 @@ function cmdLogs(args) {
|
|
|
6742
6660
|
}
|
|
6743
6661
|
console.log("\u7528\u6CD5:");
|
|
6744
6662
|
console.log(" mihomo logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
|
|
6663
|
+
console.log(" mihomo logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
|
|
6745
6664
|
console.log(" mihomo logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7\uFF08\u6700\u65B0\uFF09");
|
|
6746
6665
|
console.log(" mihomo logs 1 -n 200 # \u67E5\u770B 200 \u884C");
|
|
6747
6666
|
console.log(" mihomo logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
|
|
@@ -6816,7 +6735,7 @@ async function cmdOverwrite(args) {
|
|
|
6816
6735
|
}
|
|
6817
6736
|
|
|
6818
6737
|
// src/commands/reset.ts
|
|
6819
|
-
import
|
|
6738
|
+
import fs13 from "fs";
|
|
6820
6739
|
var RESET_TARGETS = [
|
|
6821
6740
|
{
|
|
6822
6741
|
id: "subs",
|
|
@@ -6857,13 +6776,9 @@ var RESET_TARGETS = [
|
|
|
6857
6776
|
id: "ssh",
|
|
6858
6777
|
aliases: ["ssh"],
|
|
6859
6778
|
label: "\u96A7\u9053",
|
|
6860
|
-
//
|
|
6861
|
-
//
|
|
6862
|
-
|
|
6863
|
-
paths: () => {
|
|
6864
|
-
const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
|
|
6865
|
-
return [DIRS.ssh, ...files];
|
|
6866
|
-
},
|
|
6779
|
+
// 只删运行态:v3.12.0 起 CLI 不再生成任何 ssh 配置文件,节点/规则都在用户自己
|
|
6780
|
+
// 维护的 overwrite.yaml 里(归 overwrites 目标管),这里没有额外文件要清
|
|
6781
|
+
paths: () => [DIRS.ssh],
|
|
6867
6782
|
needsStop: false,
|
|
6868
6783
|
onBefore: () => stopAllSshTunnels(),
|
|
6869
6784
|
// 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
|
|
@@ -6896,8 +6811,8 @@ var RESET_TARGETS = [
|
|
|
6896
6811
|
label: "\u8986\u5199",
|
|
6897
6812
|
paths: () => {
|
|
6898
6813
|
const dir = USER_DATA_DIR;
|
|
6899
|
-
if (!
|
|
6900
|
-
return
|
|
6814
|
+
if (!fs13.existsSync(dir)) return [];
|
|
6815
|
+
return fs13.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
6901
6816
|
},
|
|
6902
6817
|
needsStop: false
|
|
6903
6818
|
},
|
|
@@ -6984,10 +6899,10 @@ async function cmdReset(args) {
|
|
|
6984
6899
|
}
|
|
6985
6900
|
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
6986
6901
|
if (!skipConfirm) {
|
|
6987
|
-
if (!
|
|
6988
|
-
|
|
6989
|
-
|
|
6990
|
-
|
|
6902
|
+
if (!await confirmOrThrow("\u786E\u8BA4?", {
|
|
6903
|
+
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
6904
|
+
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
6905
|
+
})) {
|
|
6991
6906
|
console.log("\u5DF2\u53D6\u6D88");
|
|
6992
6907
|
return;
|
|
6993
6908
|
}
|
|
@@ -7022,7 +6937,7 @@ async function cmdReset(args) {
|
|
|
7022
6937
|
for (const t of targets) {
|
|
7023
6938
|
t.onBefore?.();
|
|
7024
6939
|
for (const p of t.paths()) {
|
|
7025
|
-
if (
|
|
6940
|
+
if (fs13.existsSync(p)) {
|
|
7026
6941
|
try {
|
|
7027
6942
|
rmrf(p);
|
|
7028
6943
|
} catch (e) {
|
|
@@ -7040,6 +6955,26 @@ async function cmdReset(args) {
|
|
|
7040
6955
|
}
|
|
7041
6956
|
|
|
7042
6957
|
// src/commands/ssh.ts
|
|
6958
|
+
import fs14 from "fs";
|
|
6959
|
+
function warnLegacySshConfigFiles() {
|
|
6960
|
+
if (!fs14.existsSync(USER_DATA_DIR)) return;
|
|
6961
|
+
const legacy = fs14.readdirSync(USER_DATA_DIR).filter((f) => /^ssh\..+\.ya?ml$/.test(f));
|
|
6962
|
+
if (legacy.length === 0) return;
|
|
6963
|
+
console.log(colors.yellow(`\u8B66\u544A: \u53D1\u73B0 ${legacy.length} \u4E2A\u5DF2\u5931\u6548\u7684 ssh \u914D\u7F6E\u6587\u4EF6`));
|
|
6964
|
+
for (const f of legacy) {
|
|
6965
|
+
console.log(colors.gray(` ${f}`));
|
|
6966
|
+
}
|
|
6967
|
+
console.log(colors.gray(" v3.12.0 \u8D77 CLI \u4E0D\u518D\u52A0\u8F7D\u5B83\u4EEC\uFF0C\u5176\u4E2D\u7684\u5206\u7EC4\u4E0E\u89C4\u5219\u5DF2\u4E0D\u751F\u6548"));
|
|
6968
|
+
console.log(colors.gray(" \u9700\u8981\u7684\u8BDD\u628A\u5185\u5BB9\u5E76\u5165 overwrite.yaml\uFF08\u542B socks5 \u8282\u70B9\u5B9A\u4E49\uFF09\uFF0C\u7136\u540E\u81EA\u884C\u5220\u9664"));
|
|
6969
|
+
console.log("");
|
|
6970
|
+
}
|
|
6971
|
+
function printOverwriteSnippet(config) {
|
|
6972
|
+
console.log(colors.gray("\u628A\u96A7\u9053\u63A5\u5165\u5206\u6D41\uFF1A\u5728 overwrite.yaml \u91CC\u52A0\u4E0A\uFF08\u6539\u6210\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
|
|
6973
|
+
console.log(colors.gray(` ~proxies:`));
|
|
6974
|
+
console.log(colors.gray(` - {name: SSH-${config.name}, type: socks5, server: 127.0.0.1, port: ${config.port}}`));
|
|
6975
|
+
console.log(colors.gray(` +rules:`));
|
|
6976
|
+
console.log(colors.gray(` - DOMAIN-SUFFIX,example.internal,SSH-${config.name}`));
|
|
6977
|
+
}
|
|
7043
6978
|
function formatState(status) {
|
|
7044
6979
|
switch (status.state) {
|
|
7045
6980
|
case "running":
|
|
@@ -7066,12 +7001,13 @@ function requireSshNameArg(args, usage) {
|
|
|
7066
7001
|
async function printSshList() {
|
|
7067
7002
|
const tunnels = getSshTunnels();
|
|
7068
7003
|
console.log("");
|
|
7004
|
+
warnLegacySshConfigFiles();
|
|
7069
7005
|
if (tunnels.length === 0) {
|
|
7070
7006
|
console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
7071
7007
|
console.log("");
|
|
7072
7008
|
console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
|
|
7073
7009
|
console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
|
|
7074
|
-
console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\
|
|
7010
|
+
console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u8FDB overwrite.yaml"));
|
|
7075
7011
|
console.log("");
|
|
7076
7012
|
return;
|
|
7077
7013
|
}
|
|
@@ -7084,7 +7020,6 @@ async function printSshList() {
|
|
|
7084
7020
|
console.log(` ${colors.bold(config.name)}${autoLabel}`);
|
|
7085
7021
|
console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
7086
7022
|
console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
7087
|
-
console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
|
|
7088
7023
|
if (status.started_by) {
|
|
7089
7024
|
console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
7090
7025
|
}
|
|
@@ -7094,7 +7029,7 @@ async function printSshList() {
|
|
|
7094
7029
|
console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
|
|
7095
7030
|
console.log("");
|
|
7096
7031
|
}
|
|
7097
|
-
|
|
7032
|
+
function sshAdd(args) {
|
|
7098
7033
|
const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
|
|
7099
7034
|
const host = parseStringArg(args, "--host");
|
|
7100
7035
|
if (!host) {
|
|
@@ -7113,20 +7048,11 @@ async function sshAdd(args) {
|
|
|
7113
7048
|
const auto = !hasFlag(args, "--no-auto");
|
|
7114
7049
|
const config = { name, host, port, auto };
|
|
7115
7050
|
addSshTunnel(config);
|
|
7116
|
-
const created = ensureSshConfigFile(config);
|
|
7117
|
-
const configPath = getSshConfigPath(name);
|
|
7118
7051
|
console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
|
|
7119
7052
|
console.log("");
|
|
7120
|
-
|
|
7121
|
-
console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
|
|
7122
|
-
console.log(colors.gray(" socks5 \u8282\u70B9\u7531 CLI \u81EA\u52A8\u6CE8\u5165\uFF0C\u6A21\u677F\u53EA\u5EFA\u597D\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
|
|
7123
|
-
console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
|
|
7124
|
-
} else {
|
|
7125
|
-
console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
|
|
7126
|
-
}
|
|
7053
|
+
printOverwriteSnippet(config);
|
|
7127
7054
|
console.log("");
|
|
7128
7055
|
console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
|
|
7129
|
-
await restartToApply(args);
|
|
7130
7056
|
}
|
|
7131
7057
|
async function sshUp(args) {
|
|
7132
7058
|
const name = getSshNameArg(args);
|
|
@@ -7135,9 +7061,6 @@ async function sshUp(args) {
|
|
|
7135
7061
|
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
7136
7062
|
}
|
|
7137
7063
|
for (const config of targets) {
|
|
7138
|
-
if (ensureSshConfigFile(config)) {
|
|
7139
|
-
console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
|
|
7140
|
-
}
|
|
7141
7064
|
const result = await startSshTunnel(config.name, { startedBy: "manual" });
|
|
7142
7065
|
if (result.alreadyRunning) {
|
|
7143
7066
|
console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
|
|
@@ -7164,7 +7087,7 @@ function sshDown(args) {
|
|
|
7164
7087
|
}
|
|
7165
7088
|
if (stopped > 0) {
|
|
7166
7089
|
console.log("");
|
|
7167
|
-
console.log(colors.gray("\u6CE8\u610F: \
|
|
7090
|
+
console.log(colors.gray("\u6CE8\u610F: overwrite.yaml \u91CC\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\u73B0\u5728\u8FDE\u4E0D\u901A"));
|
|
7168
7091
|
}
|
|
7169
7092
|
}
|
|
7170
7093
|
async function sshStatus(args) {
|
|
@@ -7198,14 +7121,10 @@ async function sshRemove(args) {
|
|
|
7198
7121
|
const config = resolveSshTunnel(name);
|
|
7199
7122
|
const skipConfirm = hasFlag(args, "-y", "--yes");
|
|
7200
7123
|
if (!skipConfirm) {
|
|
7201
|
-
if (!
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
});
|
|
7206
|
-
}
|
|
7207
|
-
const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
|
|
7208
|
-
if (!confirmed) {
|
|
7124
|
+
if (!await confirmOrThrow(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`, {
|
|
7125
|
+
nonTtyMessage: "\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4",
|
|
7126
|
+
hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
|
|
7127
|
+
})) {
|
|
7209
7128
|
console.log("\u5DF2\u53D6\u6D88");
|
|
7210
7129
|
return;
|
|
7211
7130
|
}
|
|
@@ -7214,8 +7133,7 @@ async function sshRemove(args) {
|
|
|
7214
7133
|
removeSshTunnel(config.name);
|
|
7215
7134
|
console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
|
|
7216
7135
|
console.log("");
|
|
7217
|
-
console.log(`\
|
|
7218
|
-
console.log(colors.gray(" \u5176\u4E2D\u7684\u5206\u7EC4\u5DF2\u5F15\u7528\u4E0D\u5230\u8282\u70B9\uFF0C\u4E0B\u6B21 start \u4F1A\u88AB\u81EA\u52A8\u79FB\u9664\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664\u8BE5\u6587\u4EF6"));
|
|
7136
|
+
console.log(colors.gray(`\u5982 overwrite.yaml \u91CC\u5199\u8FC7\u6307\u5411 127.0.0.1:${config.port} \u7684\u8282\u70B9\uFF0C\u8BF7\u81EA\u884C\u79FB\u9664`));
|
|
7219
7137
|
}
|
|
7220
7138
|
function resolveSshTunnel(name) {
|
|
7221
7139
|
const config = findSshTunnel(name);
|
|
@@ -7235,7 +7153,6 @@ function resolveSshTunnel(name) {
|
|
|
7235
7153
|
return config;
|
|
7236
7154
|
}
|
|
7237
7155
|
var SUBCOMMANDS4 = [
|
|
7238
|
-
{ name: "list", handler: printSshList },
|
|
7239
7156
|
{ name: "add", handler: sshAdd },
|
|
7240
7157
|
{ name: "up", aliases: ["start"], handler: sshUp },
|
|
7241
7158
|
{ name: "down", aliases: ["stop"], handler: sshDown },
|
|
@@ -7250,7 +7167,7 @@ async function cmdSsh(args) {
|
|
|
7250
7167
|
const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7251
7168
|
const suggestion = suggestSimilar(action, names);
|
|
7252
7169
|
throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
|
|
7253
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4:
|
|
7170
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: add, up, down, status, rm\uFF08\u88F8 ssh \u5373\u5217\u8868\uFF09"]
|
|
7254
7171
|
});
|
|
7255
7172
|
}
|
|
7256
7173
|
});
|
|
@@ -7283,16 +7200,9 @@ function printSubscriptionList() {
|
|
|
7283
7200
|
if (s.username) {
|
|
7284
7201
|
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
7285
7202
|
}
|
|
7286
|
-
|
|
7287
|
-
|
|
7288
|
-
|
|
7289
|
-
const totalStr = formatBytes(s.total);
|
|
7290
|
-
let percentStr = "";
|
|
7291
|
-
if (s.total && s.total > 0) {
|
|
7292
|
-
const percent = Math.min(used / s.total * 100, 100);
|
|
7293
|
-
percentStr = ` (${percent.toFixed(1)}%)`;
|
|
7294
|
-
}
|
|
7295
|
-
console.log(` ${colors.gray("\u6D41\u91CF: ")}${usedStr} / ${totalStr}${percentStr}`);
|
|
7203
|
+
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
7204
|
+
if (traffic) {
|
|
7205
|
+
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
7296
7206
|
}
|
|
7297
7207
|
if (s.expire !== void 0) {
|
|
7298
7208
|
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
@@ -7308,6 +7218,14 @@ function printSubscriptionList() {
|
|
|
7308
7218
|
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
7309
7219
|
console.log("");
|
|
7310
7220
|
}
|
|
7221
|
+
function assertNotFlagLike(name, usage) {
|
|
7222
|
+
if (name.startsWith("-")) {
|
|
7223
|
+
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
7224
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
7225
|
+
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
7226
|
+
});
|
|
7227
|
+
}
|
|
7228
|
+
}
|
|
7311
7229
|
async function subAdd(args) {
|
|
7312
7230
|
const url = args[2]?.trim();
|
|
7313
7231
|
const name = args[3] || "default";
|
|
@@ -7317,6 +7235,7 @@ async function subAdd(args) {
|
|
|
7317
7235
|
if (!isValidHttpUrl(url)) {
|
|
7318
7236
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
7319
7237
|
}
|
|
7238
|
+
assertNotFlagLike(name, "mihomo sub add <url> [name]");
|
|
7320
7239
|
console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
|
|
7321
7240
|
addSubscription(url, name);
|
|
7322
7241
|
try {
|
|
@@ -7400,14 +7319,11 @@ async function subRemove(args) {
|
|
|
7400
7319
|
const isExact = target.name === name;
|
|
7401
7320
|
const skipConfirm = hasFlag(args, "-y", "--yes");
|
|
7402
7321
|
if (!isExact && !skipConfirm) {
|
|
7403
|
-
if (!process.stdin.isTTY) {
|
|
7404
|
-
throw new CliError(`\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`, {
|
|
7405
|
-
label: "\u5DF2\u53D6\u6D88",
|
|
7406
|
-
hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
|
|
7407
|
-
});
|
|
7408
|
-
}
|
|
7409
7322
|
console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
|
|
7410
|
-
if (!await
|
|
7323
|
+
if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
|
|
7324
|
+
nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
|
|
7325
|
+
hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
|
|
7326
|
+
})) {
|
|
7411
7327
|
console.log("\u5DF2\u53D6\u6D88");
|
|
7412
7328
|
return;
|
|
7413
7329
|
}
|
|
@@ -7421,7 +7337,6 @@ async function subRemove(args) {
|
|
|
7421
7337
|
printSubscriptionList();
|
|
7422
7338
|
}
|
|
7423
7339
|
var SUBCOMMANDS5 = [
|
|
7424
|
-
{ name: "list", handler: printSubscriptionList },
|
|
7425
7340
|
{ name: "add", handler: subAdd },
|
|
7426
7341
|
{ name: "update", handler: subUpdate },
|
|
7427
7342
|
{ name: "use", handler: subUse },
|
|
@@ -7435,7 +7350,7 @@ async function cmdSubscription(args) {
|
|
|
7435
7350
|
const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7436
7351
|
const suggestion = suggestSimilar(action, names);
|
|
7437
7352
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
7438
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [
|
|
7353
|
+
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"]
|
|
7439
7354
|
});
|
|
7440
7355
|
}
|
|
7441
7356
|
});
|
|
@@ -7465,7 +7380,7 @@ function cmdUI(args) {
|
|
|
7465
7380
|
}
|
|
7466
7381
|
|
|
7467
7382
|
// src/commands/update.ts
|
|
7468
|
-
import { execFile, spawn as
|
|
7383
|
+
import { execFile, spawn as spawn4 } from "child_process";
|
|
7469
7384
|
import { promisify } from "util";
|
|
7470
7385
|
var execFileAsync = promisify(execFile);
|
|
7471
7386
|
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
@@ -7496,7 +7411,7 @@ async function cmdUpdate() {
|
|
|
7496
7411
|
console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
|
|
7497
7412
|
console.log("");
|
|
7498
7413
|
await new Promise((resolve, reject) => {
|
|
7499
|
-
const npm =
|
|
7414
|
+
const npm = spawn4("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
|
|
7500
7415
|
npm.on("close", (code) => {
|
|
7501
7416
|
if (code === 0) {
|
|
7502
7417
|
resolve();
|
|
@@ -7548,7 +7463,7 @@ var COMMANDS = [
|
|
|
7548
7463
|
aliases: ["down"],
|
|
7549
7464
|
handler: cmdStop,
|
|
7550
7465
|
group: "control",
|
|
7551
|
-
usage: ["stop
|
|
7466
|
+
usage: ["stop [--no-ssh] \u505C\u6B62\u4EE3\u7406\uFF08--no-ssh \u4FDD\u7559 ssh \u96A7\u9053\uFF09"]
|
|
7552
7467
|
},
|
|
7553
7468
|
{
|
|
7554
7469
|
name: "status",
|
|
@@ -7566,18 +7481,20 @@ var COMMANDS = [
|
|
|
7566
7481
|
usage: ["ui [zash|dash|yacd] \u6253\u5F00 Web UI (\u9ED8\u8BA4 zash)"]
|
|
7567
7482
|
},
|
|
7568
7483
|
{
|
|
7484
|
+
// 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
|
|
7569
7485
|
name: "log",
|
|
7570
7486
|
aliases: [],
|
|
7571
|
-
handler:
|
|
7487
|
+
handler: cmdLogs,
|
|
7488
|
+
rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
|
|
7572
7489
|
group: "interface",
|
|
7573
|
-
usage: [
|
|
7490
|
+
usage: []
|
|
7574
7491
|
},
|
|
7575
7492
|
{
|
|
7576
7493
|
name: "logs",
|
|
7577
7494
|
aliases: [],
|
|
7578
7495
|
handler: cmdLogs,
|
|
7579
7496
|
group: "interface",
|
|
7580
|
-
usage: ["logs [
|
|
7497
|
+
usage: ["logs [-f] [-n N] [\u7F16\u53F7] [-o] \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"]
|
|
7581
7498
|
},
|
|
7582
7499
|
// === 订阅 ===
|
|
7583
7500
|
{
|
|
@@ -7621,7 +7538,7 @@ var COMMANDS = [
|
|
|
7621
7538
|
aliases: [],
|
|
7622
7539
|
handler: cmdDaemon,
|
|
7623
7540
|
group: "system",
|
|
7624
|
-
usage: ["daemon on|off
|
|
7541
|
+
usage: ["daemon [on|off] \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09\uFF1B\u65E0\u53C2\u770B\u72B6\u6001"]
|
|
7625
7542
|
},
|
|
7626
7543
|
{
|
|
7627
7544
|
// 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
|
|
@@ -7631,11 +7548,11 @@ var COMMANDS = [
|
|
|
7631
7548
|
handler: cmdSsh,
|
|
7632
7549
|
group: "system",
|
|
7633
7550
|
usage: [
|
|
7634
|
-
"ssh \u5217\u51FA ssh \u96A7\u9053",
|
|
7551
|
+
"ssh \u5217\u51FA ssh \u96A7\u9053\uFF08\u672C\u5730 SOCKS5 \u7AEF\u53E3\uFF09",
|
|
7635
7552
|
"ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
|
|
7636
7553
|
"ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
|
|
7637
7554
|
"ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
|
|
7638
|
-
"ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053
|
|
7555
|
+
"ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053"
|
|
7639
7556
|
]
|
|
7640
7557
|
},
|
|
7641
7558
|
{
|