mihomo-cli 26.10.114 → 26.11.116
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 +18 -18
- package/README.md +6 -6
- package/SECURITY.md +1 -1
- package/dist/index.js +434 -546
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import
|
|
4
|
+
import fs17 from "fs";
|
|
5
5
|
|
|
6
6
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
7
7
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
@@ -196,6 +196,9 @@ var CONTROLLER_PORT = 9090;
|
|
|
196
196
|
function isValidPortNumber(value) {
|
|
197
197
|
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
198
198
|
}
|
|
199
|
+
function isPlainObject(value) {
|
|
200
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
201
|
+
}
|
|
199
202
|
var TUN_CONFIG = {
|
|
200
203
|
tun: {
|
|
201
204
|
enable: true,
|
|
@@ -334,6 +337,22 @@ function matchValueFlagToken(token) {
|
|
|
334
337
|
}
|
|
335
338
|
return null;
|
|
336
339
|
}
|
|
340
|
+
function collectFlagValues(args, forms) {
|
|
341
|
+
const hits = [];
|
|
342
|
+
for (let i = 0; i < args.length; i++) {
|
|
343
|
+
const match = matchValueFlagToken(args[i]);
|
|
344
|
+
if (!match || !forms.some((f) => match.spec.forms.includes(f))) continue;
|
|
345
|
+
if (match.form !== "exact") {
|
|
346
|
+
hits.push({ flag: match.baseForm, value: match.inlineValue });
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
const next = args[i + 1];
|
|
350
|
+
const takesNext = next !== void 0 && (match.spec.takesValue === "required" || !next.startsWith("-"));
|
|
351
|
+
hits.push({ flag: match.baseForm, value: takesNext ? next : null });
|
|
352
|
+
if (takesNext) i++;
|
|
353
|
+
}
|
|
354
|
+
return hits;
|
|
355
|
+
}
|
|
337
356
|
|
|
338
357
|
// src/argv.ts
|
|
339
358
|
function hasFlag(args, short, long) {
|
|
@@ -358,68 +377,48 @@ function assertKnownFlags(args, known, command) {
|
|
|
358
377
|
});
|
|
359
378
|
}
|
|
360
379
|
}
|
|
361
|
-
function
|
|
362
|
-
|
|
363
|
-
let count = 0;
|
|
380
|
+
function positionalArgs(args, startIdx) {
|
|
381
|
+
const out = [];
|
|
364
382
|
for (let i = startIdx; i < args.length; i++) {
|
|
365
383
|
const a = args[i];
|
|
366
|
-
if (a.startsWith("-")) {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
count++;
|
|
371
|
-
if (count > max) {
|
|
372
|
-
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
|
|
373
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
374
|
-
hint: [`\u7528\u6CD5: ${usage}`]
|
|
375
|
-
});
|
|
384
|
+
if (!a.startsWith("-")) {
|
|
385
|
+
out.push(a);
|
|
386
|
+
} else if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) {
|
|
387
|
+
i++;
|
|
376
388
|
}
|
|
377
389
|
}
|
|
390
|
+
return out;
|
|
391
|
+
}
|
|
392
|
+
function assertPositionalCount(args, max, startIdx, usage) {
|
|
393
|
+
if (!args) return;
|
|
394
|
+
const extra = positionalArgs(args, startIdx)[max];
|
|
395
|
+
if (extra !== void 0) {
|
|
396
|
+
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${extra}`, {
|
|
397
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
398
|
+
hint: [`\u7528\u6CD5: ${usage}`]
|
|
399
|
+
});
|
|
400
|
+
}
|
|
378
401
|
}
|
|
379
402
|
function parseIntArg(args, short, long, defaultValue) {
|
|
380
403
|
if (!args) return defaultValue;
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${raw}"`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
|
|
388
|
-
}
|
|
389
|
-
return val;
|
|
390
|
-
};
|
|
391
|
-
let first = null;
|
|
392
|
-
let count = 0;
|
|
393
|
-
for (let i = 0; i < args.length; i++) {
|
|
394
|
-
if (args[i] === short || args[i] === long) {
|
|
395
|
-
if (first === null && count === 0) {
|
|
396
|
-
if (i + 1 >= args.length) {
|
|
397
|
-
throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
|
|
398
|
-
}
|
|
399
|
-
first = { value: args[i + 1], flag: args[i] };
|
|
400
|
-
i++;
|
|
401
|
-
count++;
|
|
402
|
-
continue;
|
|
403
|
-
}
|
|
404
|
-
count++;
|
|
405
|
-
continue;
|
|
406
|
-
}
|
|
407
|
-
const match = matchValueFlagToken(args[i]);
|
|
408
|
-
if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
|
|
409
|
-
if (first === null && count === 0) {
|
|
410
|
-
first = { value: match.inlineValue ?? "", flag: match.baseForm };
|
|
411
|
-
}
|
|
412
|
-
count++;
|
|
413
|
-
}
|
|
404
|
+
const hits = collectFlagValues(args, [short, long]);
|
|
405
|
+
if (hits.length === 0) return defaultValue;
|
|
406
|
+
const { flag, value } = hits[0];
|
|
407
|
+
const hint = [`\u4F8B\u5982: ${flag} ${defaultValue}`];
|
|
408
|
+
if (hits.length > 1) {
|
|
409
|
+
throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${hits.length} \u6B21\uFF09`, { hint });
|
|
414
410
|
}
|
|
415
|
-
if (
|
|
416
|
-
|
|
417
|
-
throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${count} \u6B21\uFF09`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
|
|
411
|
+
if (value === null) {
|
|
412
|
+
throw new CliError(`\u9009\u9879 ${flag} \u7F3A\u5C11\u503C`, { hint });
|
|
418
413
|
}
|
|
419
|
-
if (
|
|
420
|
-
|
|
414
|
+
if (!/^\d+$/.test(value.trim())) {
|
|
415
|
+
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981\u6B63\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
|
|
421
416
|
}
|
|
422
|
-
|
|
417
|
+
const val = Number(value);
|
|
418
|
+
if (!Number.isSafeInteger(val) || val < 1) {
|
|
419
|
+
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
|
|
420
|
+
}
|
|
421
|
+
return val;
|
|
423
422
|
}
|
|
424
423
|
function extractStartOptions(args) {
|
|
425
424
|
if (!args) return [];
|
|
@@ -445,15 +444,7 @@ function assertRestartOptionValues(args) {
|
|
|
445
444
|
}
|
|
446
445
|
function getNonFlagArg(args, startIdx) {
|
|
447
446
|
if (!args) return null;
|
|
448
|
-
|
|
449
|
-
const a = args[i];
|
|
450
|
-
if (a.startsWith("-")) {
|
|
451
|
-
if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
|
|
452
|
-
continue;
|
|
453
|
-
}
|
|
454
|
-
return a;
|
|
455
|
-
}
|
|
456
|
-
return null;
|
|
447
|
+
return positionalArgs(args, startIdx)[0] ?? null;
|
|
457
448
|
}
|
|
458
449
|
|
|
459
450
|
// src/colors.ts
|
|
@@ -954,7 +945,7 @@ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
|
|
|
954
945
|
},
|
|
955
946
|
identify: Array.isArray
|
|
956
947
|
});
|
|
957
|
-
function
|
|
948
|
+
function isPlainObject2(data) {
|
|
958
949
|
if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
|
|
959
950
|
const prototype = Object.getPrototypeOf(data);
|
|
960
951
|
return prototype === null || prototype === Object.prototype;
|
|
@@ -974,7 +965,7 @@ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
|
|
|
974
965
|
if (item instanceof Map) {
|
|
975
966
|
if (item.size !== 1) return "cannot resolve an ordered map item";
|
|
976
967
|
key = item.keys().next().value;
|
|
977
|
-
} else if (
|
|
968
|
+
} else if (isPlainObject2(item)) {
|
|
978
969
|
const itemKeys = Object.keys(item);
|
|
979
970
|
if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
|
|
980
971
|
key = itemKeys[0];
|
|
@@ -1006,7 +997,7 @@ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
|
|
|
1006
997
|
});
|
|
1007
998
|
var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
1008
999
|
create: () => ({}),
|
|
1009
|
-
identify:
|
|
1000
|
+
identify: isPlainObject2,
|
|
1010
1001
|
represent: (o) => {
|
|
1011
1002
|
const map = /* @__PURE__ */ new Map();
|
|
1012
1003
|
for (const key of Object.keys(o)) map.set(key, o[key]);
|
|
@@ -1263,7 +1254,7 @@ var realMapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
|
1263
1254
|
has: (container, key) => container.has(key),
|
|
1264
1255
|
keys: (container) => container.keys(),
|
|
1265
1256
|
get: (container, key) => container.get(key),
|
|
1266
|
-
identify: (data) => data instanceof Map ||
|
|
1257
|
+
identify: (data) => data instanceof Map || isPlainObject2(data),
|
|
1267
1258
|
represent: (data) => {
|
|
1268
1259
|
if (data instanceof Map) return data;
|
|
1269
1260
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -1286,7 +1277,7 @@ function normalizeKey(key) {
|
|
|
1286
1277
|
}
|
|
1287
1278
|
var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
1288
1279
|
create: () => ({}),
|
|
1289
|
-
identify:
|
|
1280
|
+
identify: isPlainObject2,
|
|
1290
1281
|
represent: (o) => {
|
|
1291
1282
|
const map = /* @__PURE__ */ new Map();
|
|
1292
1283
|
for (const key of Object.keys(o)) map.set(key, o[key]);
|
|
@@ -3888,7 +3879,7 @@ function readSettings() {
|
|
|
3888
3879
|
if (!fs2.existsSync(PATHS.settingsFile)) return {};
|
|
3889
3880
|
try {
|
|
3890
3881
|
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3891
|
-
if (
|
|
3882
|
+
if (isPlainObject(parsed)) return parsed;
|
|
3892
3883
|
return backupCorruptSettings(nonObjectReason(parsed));
|
|
3893
3884
|
} catch (e) {
|
|
3894
3885
|
if (e.code === "ENOENT") return {};
|
|
@@ -3898,7 +3889,7 @@ function readSettings() {
|
|
|
3898
3889
|
function isValidSettingsContent(content) {
|
|
3899
3890
|
try {
|
|
3900
3891
|
const parsed = JSON.parse(content);
|
|
3901
|
-
return
|
|
3892
|
+
return isPlainObject(parsed);
|
|
3902
3893
|
} catch {
|
|
3903
3894
|
return false;
|
|
3904
3895
|
}
|
|
@@ -3934,7 +3925,7 @@ function validatePort(value, key) {
|
|
|
3934
3925
|
function getPorts(settings = readSettings()) {
|
|
3935
3926
|
const ports = settings.ports;
|
|
3936
3927
|
if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
|
|
3937
|
-
if (
|
|
3928
|
+
if (!isPlainObject(ports)) {
|
|
3938
3929
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3939
3930
|
}
|
|
3940
3931
|
const configuredMixed = validatePort(ports.mixed, "ports.mixed");
|
|
@@ -3971,7 +3962,7 @@ function readSubscriptionCache() {
|
|
|
3971
3962
|
try {
|
|
3972
3963
|
const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
|
|
3973
3964
|
const parsed = JSON.parse(content);
|
|
3974
|
-
if (
|
|
3965
|
+
if (!isPlainObject(parsed)) {
|
|
3975
3966
|
return backupCorruptSubscriptionCache(nonObjectReason(parsed));
|
|
3976
3967
|
}
|
|
3977
3968
|
return Object.assign(empty(), parsed);
|
|
@@ -3995,7 +3986,7 @@ function saveSubscriptionCache(subName, data) {
|
|
|
3995
3986
|
withFileLock(PATHS.subscriptionCacheLock, () => {
|
|
3996
3987
|
const cache = readSubscriptionCache();
|
|
3997
3988
|
const old = cache[subName];
|
|
3998
|
-
cache[subName] = { ...
|
|
3989
|
+
cache[subName] = { ...isPlainObject(old) ? old : {}, ...data };
|
|
3999
3990
|
writeSubscriptionCache(cache);
|
|
4000
3991
|
});
|
|
4001
3992
|
}
|
|
@@ -4034,7 +4025,7 @@ function getSubscriptionsWithCache() {
|
|
|
4034
4025
|
const cache = readSubscriptionCache();
|
|
4035
4026
|
return subs.map((s) => {
|
|
4036
4027
|
const entry = cache[s.name];
|
|
4037
|
-
const safe =
|
|
4028
|
+
const safe = isPlainObject(entry) ? entry : {};
|
|
4038
4029
|
return { ...s, ...safe };
|
|
4039
4030
|
});
|
|
4040
4031
|
}
|
|
@@ -4714,7 +4705,7 @@ function parseConfigContent(content, errorMsg) {
|
|
|
4714
4705
|
} catch (e) {
|
|
4715
4706
|
throw new CliError(`${label}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790: ${firstLine(e.message)}`, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
4716
4707
|
}
|
|
4717
|
-
if (
|
|
4708
|
+
if (!isPlainObject(result)) {
|
|
4718
4709
|
throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
4719
4710
|
}
|
|
4720
4711
|
assertConfigGraphSafe(result, label);
|
|
@@ -4725,7 +4716,7 @@ function dumpYaml(obj) {
|
|
|
4725
4716
|
}
|
|
4726
4717
|
function assertDnsShape(dnsRaw) {
|
|
4727
4718
|
if (dnsRaw === void 0 || dnsRaw === null) return;
|
|
4728
|
-
if (
|
|
4719
|
+
if (!isPlainObject(dnsRaw)) {
|
|
4729
4720
|
throw new CliError(`dns \u914D\u7F6E\u5FC5\u987B\u662F\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(dnsRaw) ? "\u6570\u7EC4" : `\u6807\u91CF\uFF08${typeof dnsRaw}\uFF09`}`, {
|
|
4730
4721
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4731
4722
|
hint: ["dns \u662F\u8BA2\u9605/\u8986\u5199\u91CC\u7684\u5BF9\u8C61\u914D\u7F6E\u5757\uFF08enable\u3001nameserver \u7B49\uFF09\uFF0C\u4E0D\u652F\u6301\u6807\u91CF\u6216\u6570\u7EC4\u3002"]
|
|
@@ -4761,7 +4752,7 @@ function assertConfigShape(config) {
|
|
|
4761
4752
|
});
|
|
4762
4753
|
}
|
|
4763
4754
|
if (needsName) {
|
|
4764
|
-
if (
|
|
4755
|
+
if (!isPlainObject(item)) {
|
|
4765
4756
|
throw new CliError(`${key}[${i}] \u5FC5\u987B\u662F\u6620\u5C04`, {
|
|
4766
4757
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4767
4758
|
hint: [`${label}\u6BB5\uFF08${key}\uFF09\u7B2C ${i + 1} \u9879\u5E94\u4E3A {name: ..., ...} \u5F62\u5F0F\uFF0C\u5F53\u524D\u662F ${Array.isArray(item) ? "\u5217\u8868" : typeof item}\u3002`]
|
|
@@ -4885,9 +4876,8 @@ function countConfigNodes(config) {
|
|
|
4885
4876
|
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
4886
4877
|
};
|
|
4887
4878
|
}
|
|
4888
|
-
function writeMihomoConfig(
|
|
4879
|
+
function writeMihomoConfig(content) {
|
|
4889
4880
|
ensureDirs();
|
|
4890
|
-
const content = dumpYaml(configObj);
|
|
4891
4881
|
atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
|
|
4892
4882
|
}
|
|
4893
4883
|
var HINT_INDENT = " ";
|
|
@@ -4910,13 +4900,13 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
|
|
|
4910
4900
|
);
|
|
4911
4901
|
return hint;
|
|
4912
4902
|
}
|
|
4913
|
-
async function validateConfigWithKernel(
|
|
4903
|
+
async function validateConfigWithKernel(configContent, overwriteSummaries) {
|
|
4914
4904
|
assertKernelInstalled();
|
|
4915
4905
|
ensureDirs();
|
|
4916
4906
|
const stageDir = fs4.mkdtempSync(path4.join(USER_DATA_DIR, "check-"));
|
|
4917
4907
|
const stageFile = path4.join(stageDir, "config.yaml");
|
|
4918
4908
|
try {
|
|
4919
|
-
fs4.writeFileSync(stageFile,
|
|
4909
|
+
fs4.writeFileSync(stageFile, configContent, { mode: 384 });
|
|
4920
4910
|
try {
|
|
4921
4911
|
await promisify(execFile)(PATHS.mihomoBinary, ["-t", "-d", DIRS.data, "-f", stageFile], {
|
|
4922
4912
|
encoding: "utf8",
|
|
@@ -5084,13 +5074,7 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
|
5084
5074
|
// src/launchctl.ts
|
|
5085
5075
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
5086
5076
|
import fs5 from "fs";
|
|
5087
|
-
|
|
5088
|
-
// src/utils.ts
|
|
5089
|
-
function sleep(ms) {
|
|
5090
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
5091
|
-
}
|
|
5092
|
-
|
|
5093
|
-
// src/launchctl.ts
|
|
5077
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
5094
5078
|
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
5095
5079
|
var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
|
|
5096
5080
|
function serviceTarget() {
|
|
@@ -5709,6 +5693,7 @@ async function downloadSubscription(url, subName, signal) {
|
|
|
5709
5693
|
}
|
|
5710
5694
|
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5711
5695
|
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5696
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5712
5697
|
const meta = extractSubscriptionMeta(response.headers);
|
|
5713
5698
|
withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5714
5699
|
const previousContent = readSubscriptionRawConfig(subName);
|
|
@@ -5736,7 +5721,6 @@ async function downloadSubscription(url, subName, signal) {
|
|
|
5736
5721
|
});
|
|
5737
5722
|
}
|
|
5738
5723
|
});
|
|
5739
|
-
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5740
5724
|
return { proxies, proxyGroups };
|
|
5741
5725
|
}
|
|
5742
5726
|
async function prepareConfigForStart(mode, subName) {
|
|
@@ -5753,11 +5737,9 @@ async function prepareConfigForStart(mode, subName) {
|
|
|
5753
5737
|
}
|
|
5754
5738
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5755
5739
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
info: countConfigNodes(buildResult.config)
|
|
5760
|
-
};
|
|
5740
|
+
const candidateContent = dumpYaml(buildResult.config);
|
|
5741
|
+
await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
|
|
5742
|
+
return { buildResult, candidateContent, info: countConfigNodes(buildResult.config) };
|
|
5761
5743
|
}
|
|
5762
5744
|
function commitPreparedConfig(prepared) {
|
|
5763
5745
|
const { buildResult } = prepared;
|
|
@@ -5767,7 +5749,7 @@ function commitPreparedConfig(prepared) {
|
|
|
5767
5749
|
}
|
|
5768
5750
|
console.log("");
|
|
5769
5751
|
}
|
|
5770
|
-
writeMihomoConfig(
|
|
5752
|
+
writeMihomoConfig(prepared.candidateContent);
|
|
5771
5753
|
return prepared.info;
|
|
5772
5754
|
}
|
|
5773
5755
|
function needsAutoUpdate(sub) {
|
|
@@ -5799,9 +5781,7 @@ function printUpdateResult(r) {
|
|
|
5799
5781
|
async function autoUpdateStaleSubscription(options = {}) {
|
|
5800
5782
|
const allSubs = getSubscriptionsWithCache();
|
|
5801
5783
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
5802
|
-
if (staleSubs.length === 0)
|
|
5803
|
-
return;
|
|
5804
|
-
}
|
|
5784
|
+
if (staleSubs.length === 0) return;
|
|
5805
5785
|
if (staleSubs.length === 1) {
|
|
5806
5786
|
const sub = staleSubs[0];
|
|
5807
5787
|
const interval = resolveUpdateInterval(sub.update_interval);
|
|
@@ -5829,9 +5809,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5829
5809
|
});
|
|
5830
5810
|
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`));
|
|
5831
5811
|
}
|
|
5832
|
-
for (const r of results)
|
|
5833
|
-
printUpdateResult(r);
|
|
5834
|
-
}
|
|
5812
|
+
for (const r of results) printUpdateResult(r);
|
|
5835
5813
|
}
|
|
5836
5814
|
|
|
5837
5815
|
// src/commands/config.ts
|
|
@@ -5944,6 +5922,10 @@ function viewLogWithTail(logPath, options) {
|
|
|
5944
5922
|
// src/commands/shared.ts
|
|
5945
5923
|
import readline from "readline";
|
|
5946
5924
|
|
|
5925
|
+
// src/runtime.ts
|
|
5926
|
+
import fs12 from "fs";
|
|
5927
|
+
import { setTimeout as sleep4 } from "timers/promises";
|
|
5928
|
+
|
|
5947
5929
|
// src/log-files.ts
|
|
5948
5930
|
import fs6 from "fs";
|
|
5949
5931
|
import path5 from "path";
|
|
@@ -6005,10 +5987,9 @@ function allocateArchivePath() {
|
|
|
6005
5987
|
});
|
|
6006
5988
|
}
|
|
6007
5989
|
function rotateLog() {
|
|
6008
|
-
const logFile = PATHS.logFile;
|
|
6009
5990
|
let stat;
|
|
6010
5991
|
try {
|
|
6011
|
-
stat = fs6.statSync(logFile);
|
|
5992
|
+
stat = fs6.statSync(PATHS.logFile);
|
|
6012
5993
|
} catch (e) {
|
|
6013
5994
|
if (e.code === "ENOENT") return;
|
|
6014
5995
|
throw e;
|
|
@@ -6016,7 +5997,7 @@ function rotateLog() {
|
|
|
6016
5997
|
if (stat.size === 0) return;
|
|
6017
5998
|
const rotatedPath = allocateArchivePath();
|
|
6018
5999
|
try {
|
|
6019
|
-
fs6.renameSync(logFile, rotatedPath);
|
|
6000
|
+
fs6.renameSync(PATHS.logFile, rotatedPath);
|
|
6020
6001
|
} catch (e) {
|
|
6021
6002
|
try {
|
|
6022
6003
|
fs6.unlinkSync(rotatedPath);
|
|
@@ -6159,123 +6140,14 @@ function getStatus() {
|
|
|
6159
6140
|
};
|
|
6160
6141
|
}
|
|
6161
6142
|
|
|
6162
|
-
// src/process-start.ts
|
|
6163
|
-
import fs13 from "fs";
|
|
6164
|
-
|
|
6165
|
-
// src/service.ts
|
|
6166
|
-
import { spawnSync as spawnSync7 } from "child_process";
|
|
6167
|
-
import fs12 from "fs";
|
|
6168
|
-
import path7 from "path";
|
|
6169
|
-
|
|
6170
|
-
// src/hot-reload.ts
|
|
6171
|
-
import fs8 from "fs";
|
|
6172
|
-
|
|
6173
|
-
// src/proxy-probe.ts
|
|
6174
|
-
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
6175
|
-
import { promisify as promisify2 } from "util";
|
|
6176
|
-
|
|
6177
|
-
// src/curl-spawn.ts
|
|
6178
|
-
function buildCurlSpawnEnv() {
|
|
6179
|
-
const env = { ...process.env };
|
|
6180
|
-
env.no_proxy = "";
|
|
6181
|
-
env.NO_PROXY = "";
|
|
6182
|
-
return env;
|
|
6183
|
-
}
|
|
6184
|
-
|
|
6185
|
-
// src/proxy-probe.ts
|
|
6186
|
-
var execFileAsync = promisify2(execFile2);
|
|
6187
|
-
function lsofListenPids(port) {
|
|
6188
|
-
try {
|
|
6189
|
-
const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
6190
|
-
if (r.status !== 0) return null;
|
|
6191
|
-
return parsePidList(r.stdout);
|
|
6192
|
-
} catch {
|
|
6193
|
-
return null;
|
|
6194
|
-
}
|
|
6195
|
-
}
|
|
6196
|
-
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
6197
|
-
function isProbeSuccessStatus(code) {
|
|
6198
|
-
return code !== null && code >= 200 && code < 300;
|
|
6199
|
-
}
|
|
6200
|
-
var PROBE_TIMEOUT_MS = 2e3;
|
|
6201
|
-
async function probeProxyConnectivity(port) {
|
|
6202
|
-
const start = Date.now();
|
|
6203
|
-
try {
|
|
6204
|
-
const { stdout } = await execFileAsync(
|
|
6205
|
-
"curl",
|
|
6206
|
-
["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6207
|
-
{
|
|
6208
|
-
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6209
|
-
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
6210
|
-
env: buildCurlSpawnEnv()
|
|
6211
|
-
}
|
|
6212
|
-
);
|
|
6213
|
-
const code = Number.parseInt(stdout.trim(), 10);
|
|
6214
|
-
const statusCode = Number.isFinite(code) ? code : null;
|
|
6215
|
-
const ok = isProbeSuccessStatus(statusCode);
|
|
6216
|
-
return {
|
|
6217
|
-
ok,
|
|
6218
|
-
statusCode,
|
|
6219
|
-
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6220
|
-
durationMs: Date.now() - start
|
|
6221
|
-
};
|
|
6222
|
-
} catch (e) {
|
|
6223
|
-
const err = e;
|
|
6224
|
-
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6225
|
-
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
6226
|
-
}
|
|
6227
|
-
}
|
|
6228
|
-
|
|
6229
|
-
// src/hot-reload.ts
|
|
6230
|
-
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
6231
|
-
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6232
|
-
function logOversized() {
|
|
6233
|
-
try {
|
|
6234
|
-
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6235
|
-
} catch {
|
|
6236
|
-
return false;
|
|
6237
|
-
}
|
|
6238
|
-
}
|
|
6239
|
-
async function tryHotReload(prefetched) {
|
|
6240
|
-
const controller = new AbortController();
|
|
6241
|
-
try {
|
|
6242
|
-
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6243
|
-
if (!status.running || status.pid === null) return false;
|
|
6244
|
-
const endpoint = getControllerEndpoint();
|
|
6245
|
-
if (endpoint.port === null) return false;
|
|
6246
|
-
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6247
|
-
const headers = { "Content-Type": "application/json" };
|
|
6248
|
-
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6249
|
-
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6250
|
-
try {
|
|
6251
|
-
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6252
|
-
if (!probe.ok) return false;
|
|
6253
|
-
const info = await probe.json();
|
|
6254
|
-
if (typeof info?.version !== "string") return false;
|
|
6255
|
-
const listenerPids = lsofListenPids(endpoint.port);
|
|
6256
|
-
if (listenerPids === null || listenerPids[0] !== status.pid) return false;
|
|
6257
|
-
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6258
|
-
method: "PUT",
|
|
6259
|
-
headers,
|
|
6260
|
-
body: "{}",
|
|
6261
|
-
signal: controller.signal
|
|
6262
|
-
});
|
|
6263
|
-
return res.ok;
|
|
6264
|
-
} finally {
|
|
6265
|
-
clearTimeout(timer);
|
|
6266
|
-
}
|
|
6267
|
-
} catch {
|
|
6268
|
-
return false;
|
|
6269
|
-
}
|
|
6270
|
-
}
|
|
6271
|
-
|
|
6272
6143
|
// src/process-stop.ts
|
|
6273
|
-
import { spawnSync as spawnSync6 } from "child_process";
|
|
6274
|
-
import fs10 from "fs";
|
|
6275
|
-
|
|
6276
|
-
// src/sudo.ts
|
|
6277
6144
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6278
6145
|
import fs9 from "fs";
|
|
6146
|
+
import { setTimeout as sleep2 } from "timers/promises";
|
|
6147
|
+
|
|
6148
|
+
// src/sudo.ts
|
|
6149
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
6150
|
+
import fs8 from "fs";
|
|
6279
6151
|
import path6 from "path";
|
|
6280
6152
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
6281
6153
|
var SudoAuthError = class extends Error {
|
|
@@ -6287,9 +6159,15 @@ var SudoAuthError = class extends Error {
|
|
|
6287
6159
|
function describeSudoFailure(e) {
|
|
6288
6160
|
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
6289
6161
|
}
|
|
6290
|
-
function
|
|
6162
|
+
function sudoResultToError(action, result, codeMessages) {
|
|
6163
|
+
if (result.error) {
|
|
6164
|
+
if (result.error.code === "ETIMEDOUT") return sudoTimeoutError(action);
|
|
6165
|
+
return result.error;
|
|
6166
|
+
}
|
|
6167
|
+
const { status } = result;
|
|
6168
|
+
if (status === 0) return null;
|
|
6291
6169
|
if (status === 1) return new SudoAuthError();
|
|
6292
|
-
if (status
|
|
6170
|
+
if (status === null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
6293
6171
|
const custom = codeMessages?.[status];
|
|
6294
6172
|
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
6295
6173
|
}
|
|
@@ -6302,18 +6180,15 @@ function runSudoScript(scriptBody, opts) {
|
|
|
6302
6180
|
}
|
|
6303
6181
|
ensureDirs();
|
|
6304
6182
|
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
6305
|
-
|
|
6306
|
-
|
|
6183
|
+
fs8.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
6184
|
+
fs8.chmodSync(scriptPath, 448);
|
|
6307
6185
|
try {
|
|
6308
|
-
const result =
|
|
6309
|
-
|
|
6310
|
-
|
|
6311
|
-
throw result.error;
|
|
6312
|
-
}
|
|
6313
|
-
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
6186
|
+
const result = spawnSync4("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
6187
|
+
const error = sudoResultToError(opts.action, result, opts.codeMessages);
|
|
6188
|
+
if (error) throw error;
|
|
6314
6189
|
} finally {
|
|
6315
6190
|
try {
|
|
6316
|
-
|
|
6191
|
+
fs8.unlinkSync(scriptPath);
|
|
6317
6192
|
} catch {
|
|
6318
6193
|
}
|
|
6319
6194
|
}
|
|
@@ -6324,7 +6199,7 @@ var PROCESS_WAIT_ATTEMPTS = 50;
|
|
|
6324
6199
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
6325
6200
|
var BATCH_KILL_THRESHOLD = 3;
|
|
6326
6201
|
function clearRuntime() {
|
|
6327
|
-
if (
|
|
6202
|
+
if (fs9.existsSync(DIRS.runtime)) {
|
|
6328
6203
|
rmrf(DIRS.runtime);
|
|
6329
6204
|
}
|
|
6330
6205
|
ensureDirs();
|
|
@@ -6336,7 +6211,7 @@ function printResidueWarning(remaining) {
|
|
|
6336
6211
|
}
|
|
6337
6212
|
function clearPid() {
|
|
6338
6213
|
try {
|
|
6339
|
-
|
|
6214
|
+
fs9.unlinkSync(PATHS.pidFile);
|
|
6340
6215
|
return null;
|
|
6341
6216
|
} catch (e) {
|
|
6342
6217
|
if (e.code === "ENOENT") return null;
|
|
@@ -6354,7 +6229,7 @@ function pidAlive(pid) {
|
|
|
6354
6229
|
async function waitUntilNoMihomo(pids) {
|
|
6355
6230
|
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6356
6231
|
if (!pids.some(pidAlive)) return;
|
|
6357
|
-
await
|
|
6232
|
+
await sleep2(PROCESS_WAIT_INTERVAL);
|
|
6358
6233
|
}
|
|
6359
6234
|
}
|
|
6360
6235
|
function killProcess(pid) {
|
|
@@ -6364,7 +6239,7 @@ function killProcess(pid) {
|
|
|
6364
6239
|
}
|
|
6365
6240
|
}
|
|
6366
6241
|
function killAllMihomo() {
|
|
6367
|
-
|
|
6242
|
+
spawnSync5("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
|
|
6368
6243
|
}
|
|
6369
6244
|
function buildKernelCleanupScript() {
|
|
6370
6245
|
return [
|
|
@@ -6450,11 +6325,73 @@ async function stop() {
|
|
|
6450
6325
|
return {};
|
|
6451
6326
|
}
|
|
6452
6327
|
|
|
6453
|
-
// src/
|
|
6328
|
+
// src/service.ts
|
|
6329
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
6454
6330
|
import fs11 from "fs";
|
|
6331
|
+
import path7 from "path";
|
|
6332
|
+
import { setTimeout as sleep3 } from "timers/promises";
|
|
6333
|
+
|
|
6334
|
+
// src/proxy-probe.ts
|
|
6335
|
+
import { execFile as execFile2, spawnSync as spawnSync6 } from "child_process";
|
|
6336
|
+
import { promisify as promisify2 } from "util";
|
|
6337
|
+
|
|
6338
|
+
// src/curl-spawn.ts
|
|
6339
|
+
function buildCurlSpawnEnv() {
|
|
6340
|
+
const env = { ...process.env };
|
|
6341
|
+
env.no_proxy = "";
|
|
6342
|
+
env.NO_PROXY = "";
|
|
6343
|
+
return env;
|
|
6344
|
+
}
|
|
6345
|
+
|
|
6346
|
+
// src/proxy-probe.ts
|
|
6347
|
+
var execFileAsync = promisify2(execFile2);
|
|
6348
|
+
function lsofListenPids(port) {
|
|
6349
|
+
try {
|
|
6350
|
+
const r = spawnSync6("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
6351
|
+
if (r.status !== 0) return null;
|
|
6352
|
+
return parsePidList(r.stdout);
|
|
6353
|
+
} catch {
|
|
6354
|
+
return null;
|
|
6355
|
+
}
|
|
6356
|
+
}
|
|
6357
|
+
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
6358
|
+
function isProbeSuccessStatus(code) {
|
|
6359
|
+
return code !== null && code >= 200 && code < 300;
|
|
6360
|
+
}
|
|
6361
|
+
var PROBE_TIMEOUT_MS = 2e3;
|
|
6362
|
+
async function probeProxyConnectivity(port) {
|
|
6363
|
+
const start = Date.now();
|
|
6364
|
+
try {
|
|
6365
|
+
const { stdout } = await execFileAsync(
|
|
6366
|
+
"curl",
|
|
6367
|
+
["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6368
|
+
{
|
|
6369
|
+
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6370
|
+
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
6371
|
+
env: buildCurlSpawnEnv()
|
|
6372
|
+
}
|
|
6373
|
+
);
|
|
6374
|
+
const code = Number.parseInt(stdout.trim(), 10);
|
|
6375
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
6376
|
+
const ok = isProbeSuccessStatus(statusCode);
|
|
6377
|
+
return {
|
|
6378
|
+
ok,
|
|
6379
|
+
statusCode,
|
|
6380
|
+
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6381
|
+
durationMs: Date.now() - start
|
|
6382
|
+
};
|
|
6383
|
+
} catch (e) {
|
|
6384
|
+
const err = e;
|
|
6385
|
+
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6386
|
+
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
6387
|
+
}
|
|
6388
|
+
}
|
|
6389
|
+
|
|
6390
|
+
// src/stop-epoch.ts
|
|
6391
|
+
import fs10 from "fs";
|
|
6455
6392
|
function readStopEpoch() {
|
|
6456
6393
|
try {
|
|
6457
|
-
const n = Number.parseInt(
|
|
6394
|
+
const n = Number.parseInt(fs10.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
6458
6395
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
6459
6396
|
} catch {
|
|
6460
6397
|
return 0;
|
|
@@ -6498,7 +6435,7 @@ async function waitServiceHealthy() {
|
|
|
6498
6435
|
terminatingSignal: state.lastTerminatingSignal
|
|
6499
6436
|
});
|
|
6500
6437
|
do {
|
|
6501
|
-
await
|
|
6438
|
+
await sleep3(SERVICE_HEALTH_INTERVAL_MS);
|
|
6502
6439
|
try {
|
|
6503
6440
|
last = getServiceStatus({ withDisabled: false });
|
|
6504
6441
|
} catch {
|
|
@@ -6515,7 +6452,7 @@ async function waitServiceHealthy() {
|
|
|
6515
6452
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
6516
6453
|
let graceQueried = false;
|
|
6517
6454
|
while (Date.now() < graceDeadline) {
|
|
6518
|
-
await
|
|
6455
|
+
await sleep3(SERVICE_HEALTH_INTERVAL_MS);
|
|
6519
6456
|
try {
|
|
6520
6457
|
last = getServiceStatus({ withDisabled: false });
|
|
6521
6458
|
} catch {
|
|
@@ -6567,14 +6504,14 @@ function tunBlockedByConcurrentStart() {
|
|
|
6567
6504
|
function ensureServiceSymlink() {
|
|
6568
6505
|
assertKernelInstalled();
|
|
6569
6506
|
try {
|
|
6570
|
-
const current =
|
|
6507
|
+
const current = fs11.readlinkSync(PATHS.serviceBinary);
|
|
6571
6508
|
if (current === "mihomo") return;
|
|
6572
|
-
|
|
6509
|
+
fs11.unlinkSync(PATHS.serviceBinary);
|
|
6573
6510
|
} catch (e) {
|
|
6574
6511
|
const code = e.code;
|
|
6575
6512
|
if (code === "EINVAL") {
|
|
6576
6513
|
try {
|
|
6577
|
-
|
|
6514
|
+
fs11.unlinkSync(PATHS.serviceBinary);
|
|
6578
6515
|
} catch {
|
|
6579
6516
|
}
|
|
6580
6517
|
} else if (code !== "ENOENT") {
|
|
@@ -6582,12 +6519,12 @@ function ensureServiceSymlink() {
|
|
|
6582
6519
|
}
|
|
6583
6520
|
}
|
|
6584
6521
|
try {
|
|
6585
|
-
|
|
6522
|
+
fs11.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
6586
6523
|
} catch (e) {
|
|
6587
6524
|
if (e.code !== "EEXIST") throw e;
|
|
6588
6525
|
let existing;
|
|
6589
6526
|
try {
|
|
6590
|
-
existing =
|
|
6527
|
+
existing = fs11.readlinkSync(PATHS.serviceBinary);
|
|
6591
6528
|
} catch {
|
|
6592
6529
|
throw e;
|
|
6593
6530
|
}
|
|
@@ -6627,8 +6564,8 @@ async function installService(wasRunning) {
|
|
|
6627
6564
|
}
|
|
6628
6565
|
bootoutService();
|
|
6629
6566
|
await waitUntilUnloaded();
|
|
6630
|
-
|
|
6631
|
-
atomicWriteFileSync(PATHS.userAgentPlist,
|
|
6567
|
+
fs11.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
6568
|
+
atomicWriteFileSync(PATHS.userAgentPlist, fs11.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
6632
6569
|
if (wasRunning) {
|
|
6633
6570
|
withFileLock(PATHS.serviceLock, () => {
|
|
6634
6571
|
if (startAbortedByConcurrentStop()) {
|
|
@@ -6641,7 +6578,7 @@ async function installService(wasRunning) {
|
|
|
6641
6578
|
}
|
|
6642
6579
|
} finally {
|
|
6643
6580
|
try {
|
|
6644
|
-
|
|
6581
|
+
fs11.unlinkSync(stagePath);
|
|
6645
6582
|
} catch {
|
|
6646
6583
|
}
|
|
6647
6584
|
}
|
|
@@ -6713,32 +6650,73 @@ async function uninstallService() {
|
|
|
6713
6650
|
assertServiceLabelSafe();
|
|
6714
6651
|
await bootoutAndDisableInLock();
|
|
6715
6652
|
try {
|
|
6716
|
-
|
|
6653
|
+
fs11.rmSync(PATHS.userAgentPlist, { force: true });
|
|
6717
6654
|
} catch (e) {
|
|
6718
6655
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
6719
6656
|
}
|
|
6720
6657
|
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6721
6658
|
try {
|
|
6722
|
-
|
|
6659
|
+
fs11.rmSync(PATHS.serviceBinary, { force: true });
|
|
6723
6660
|
} catch {
|
|
6724
6661
|
}
|
|
6725
6662
|
return cleanup;
|
|
6726
6663
|
}
|
|
6727
|
-
|
|
6728
|
-
|
|
6729
|
-
|
|
6730
|
-
|
|
6731
|
-
|
|
6732
|
-
|
|
6733
|
-
|
|
6734
|
-
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6664
|
+
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
6665
|
+
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6666
|
+
function logOversized() {
|
|
6667
|
+
try {
|
|
6668
|
+
return fs11.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6669
|
+
} catch {
|
|
6670
|
+
return false;
|
|
6735
6671
|
}
|
|
6736
|
-
|
|
6737
|
-
|
|
6672
|
+
}
|
|
6673
|
+
async function tryHotReload(prefetched) {
|
|
6674
|
+
try {
|
|
6675
|
+
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6676
|
+
if (!status.running || status.pid === null) return false;
|
|
6677
|
+
const endpoint = getControllerEndpoint();
|
|
6678
|
+
if (endpoint.port === null) return false;
|
|
6679
|
+
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6680
|
+
const headers = { "Content-Type": "application/json" };
|
|
6681
|
+
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6682
|
+
const controller = new AbortController();
|
|
6683
|
+
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6738
6684
|
try {
|
|
6739
|
-
|
|
6740
|
-
|
|
6741
|
-
|
|
6685
|
+
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6686
|
+
if (!probe.ok) return false;
|
|
6687
|
+
const info = await probe.json();
|
|
6688
|
+
if (typeof info?.version !== "string") return false;
|
|
6689
|
+
if (lsofListenPids(endpoint.port)?.[0] !== status.pid) return false;
|
|
6690
|
+
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6691
|
+
method: "PUT",
|
|
6692
|
+
headers,
|
|
6693
|
+
body: "{}",
|
|
6694
|
+
signal: controller.signal
|
|
6695
|
+
});
|
|
6696
|
+
return res.ok;
|
|
6697
|
+
} finally {
|
|
6698
|
+
clearTimeout(timer);
|
|
6699
|
+
}
|
|
6700
|
+
} catch {
|
|
6701
|
+
return false;
|
|
6702
|
+
}
|
|
6703
|
+
}
|
|
6704
|
+
async function restartService(prefetched) {
|
|
6705
|
+
assertServiceLabelSafe();
|
|
6706
|
+
if (!isServiceInstalled()) {
|
|
6707
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
6708
|
+
}
|
|
6709
|
+
const oversized = logOversized();
|
|
6710
|
+
const hotReloaded = !oversized && await tryHotReload(prefetched);
|
|
6711
|
+
if (hotReloaded) {
|
|
6712
|
+
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6713
|
+
}
|
|
6714
|
+
if (oversized) {
|
|
6715
|
+
const archiveFile = allocateArchivePath();
|
|
6716
|
+
try {
|
|
6717
|
+
fs11.copyFileSync(PATHS.logFile, archiveFile);
|
|
6718
|
+
fs11.writeFileSync(PATHS.logFile, "");
|
|
6719
|
+
} catch {
|
|
6742
6720
|
}
|
|
6743
6721
|
}
|
|
6744
6722
|
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
@@ -6760,114 +6738,6 @@ async function restartService(prefetched) {
|
|
|
6760
6738
|
return { hotReloaded: false, started: true };
|
|
6761
6739
|
}
|
|
6762
6740
|
|
|
6763
|
-
// src/process-start.ts
|
|
6764
|
-
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6765
|
-
function buildTunLaunchScript() {
|
|
6766
|
-
const binary = shellQuote(PATHS.mihomoBinary);
|
|
6767
|
-
const configFile = shellQuote(PATHS.configFile);
|
|
6768
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
6769
|
-
const pidFile = shellQuote(PATHS.pidFile);
|
|
6770
|
-
const dataDir = shellQuote(DIRS.data);
|
|
6771
|
-
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
6772
|
-
return `#!/bin/bash
|
|
6773
|
-
BINARY=${binary}
|
|
6774
|
-
CONFIG_FILE=${configFile}
|
|
6775
|
-
LOG_FILE=${logFile}
|
|
6776
|
-
PID_FILE=${pidFile}
|
|
6777
|
-
DATA_DIR=${dataDir}
|
|
6778
|
-
KILL_PATTERN=${killPattern}
|
|
6779
|
-
|
|
6780
|
-
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
6781
|
-
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
6782
|
-
sleep 0.2
|
|
6783
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6784
|
-
|
|
6785
|
-
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
6786
|
-
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
6787
|
-
|
|
6788
|
-
# \u542F\u52A8
|
|
6789
|
-
cd /tmp
|
|
6790
|
-
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
6791
|
-
NEW_PID=$!
|
|
6792
|
-
echo \${NEW_PID} > "\${PID_FILE}"
|
|
6793
|
-
|
|
6794
|
-
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
6795
|
-
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
6796
|
-
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
6797
|
-
is_alive() {
|
|
6798
|
-
local stat
|
|
6799
|
-
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
6800
|
-
case "\${stat}" in
|
|
6801
|
-
Z*|'') return 1 ;;
|
|
6802
|
-
*) return 0 ;;
|
|
6803
|
-
esac
|
|
6804
|
-
}
|
|
6805
|
-
|
|
6806
|
-
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
6807
|
-
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
6808
|
-
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
6809
|
-
i=0
|
|
6810
|
-
while [ $i -lt 12 ]; do
|
|
6811
|
-
sleep 0.1
|
|
6812
|
-
is_alive \${NEW_PID} || break
|
|
6813
|
-
i=$((i+1))
|
|
6814
|
-
done
|
|
6815
|
-
if is_alive \${NEW_PID}; then
|
|
6816
|
-
exit 0
|
|
6817
|
-
fi
|
|
6818
|
-
|
|
6819
|
-
# \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
|
|
6820
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6821
|
-
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
6822
|
-
echo ""
|
|
6823
|
-
echo "--- \u65E5\u5FD7 ---"
|
|
6824
|
-
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
6825
|
-
exit 2
|
|
6826
|
-
`;
|
|
6827
|
-
}
|
|
6828
|
-
async function startTun(prefetched) {
|
|
6829
|
-
ensureDirs();
|
|
6830
|
-
assertKernelInstalled();
|
|
6831
|
-
assertRuntimeConfigPresent();
|
|
6832
|
-
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
6833
|
-
if (serviceLoaded) {
|
|
6834
|
-
throw tunBlockedByConcurrentStart();
|
|
6835
|
-
}
|
|
6836
|
-
rotateAndCleanupLogs();
|
|
6837
|
-
const logFile = PATHS.logFile;
|
|
6838
|
-
if (fs13.existsSync(logFile)) {
|
|
6839
|
-
try {
|
|
6840
|
-
fs13.accessSync(logFile, fs13.constants.W_OK);
|
|
6841
|
-
} catch {
|
|
6842
|
-
try {
|
|
6843
|
-
fs13.unlinkSync(logFile);
|
|
6844
|
-
} catch {
|
|
6845
|
-
}
|
|
6846
|
-
}
|
|
6847
|
-
}
|
|
6848
|
-
const stalePids = getMihomoPids();
|
|
6849
|
-
if (stalePids.length > 0) {
|
|
6850
|
-
console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
6851
|
-
} else if (isPidFileOwnedByRoot()) {
|
|
6852
|
-
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
6853
|
-
}
|
|
6854
|
-
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
6855
|
-
runSudoScript(buildTunLaunchScript(), {
|
|
6856
|
-
action: "TUN \u542F\u52A8",
|
|
6857
|
-
file: "launch-tun.sh",
|
|
6858
|
-
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
6859
|
-
});
|
|
6860
|
-
await sleep(TUN_MODE_POST_WAIT_MS);
|
|
6861
|
-
const finalPid = getPid();
|
|
6862
|
-
if (!finalPid || !isRunning()) {
|
|
6863
|
-
const tail = readLogTail();
|
|
6864
|
-
throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
|
|
6865
|
-
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
|
|
6866
|
-
});
|
|
6867
|
-
}
|
|
6868
|
-
return finalPid;
|
|
6869
|
-
}
|
|
6870
|
-
|
|
6871
6741
|
// src/runtime.ts
|
|
6872
6742
|
function getRuntimeMode() {
|
|
6873
6743
|
if (isServiceInstalled()) return "mixed";
|
|
@@ -6976,117 +6846,111 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
6976
6846
|
]
|
|
6977
6847
|
});
|
|
6978
6848
|
}
|
|
6849
|
+
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6850
|
+
function buildTunLaunchScript() {
|
|
6851
|
+
const binary = shellQuote(PATHS.mihomoBinary);
|
|
6852
|
+
const configFile = shellQuote(PATHS.configFile);
|
|
6853
|
+
const logFile = shellQuote(PATHS.logFile);
|
|
6854
|
+
const pidFile = shellQuote(PATHS.pidFile);
|
|
6855
|
+
const dataDir = shellQuote(DIRS.data);
|
|
6856
|
+
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
6857
|
+
return `#!/bin/bash
|
|
6858
|
+
BINARY=${binary}
|
|
6859
|
+
CONFIG_FILE=${configFile}
|
|
6860
|
+
LOG_FILE=${logFile}
|
|
6861
|
+
PID_FILE=${pidFile}
|
|
6862
|
+
DATA_DIR=${dataDir}
|
|
6863
|
+
KILL_PATTERN=${killPattern}
|
|
6979
6864
|
|
|
6980
|
-
|
|
6981
|
-
|
|
6982
|
-
|
|
6983
|
-
|
|
6984
|
-
|
|
6865
|
+
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
6866
|
+
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
6867
|
+
sleep 0.2
|
|
6868
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6869
|
+
|
|
6870
|
+
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
6871
|
+
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
6872
|
+
|
|
6873
|
+
# \u542F\u52A8
|
|
6874
|
+
cd /tmp
|
|
6875
|
+
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
6876
|
+
NEW_PID=$!
|
|
6877
|
+
echo \${NEW_PID} > "\${PID_FILE}"
|
|
6878
|
+
|
|
6879
|
+
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
6880
|
+
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
6881
|
+
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
6882
|
+
is_alive() {
|
|
6883
|
+
local stat
|
|
6884
|
+
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
6885
|
+
case "\${stat}" in
|
|
6886
|
+
Z*|'') return 1 ;;
|
|
6887
|
+
*) return 0 ;;
|
|
6888
|
+
esac
|
|
6985
6889
|
}
|
|
6986
|
-
|
|
6987
|
-
|
|
6988
|
-
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
|
|
6890
|
+
|
|
6891
|
+
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
6892
|
+
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
6893
|
+
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
6894
|
+
i=0
|
|
6895
|
+
while [ $i -lt 12 ]; do
|
|
6896
|
+
sleep 0.1
|
|
6897
|
+
is_alive \${NEW_PID} || break
|
|
6898
|
+
i=$((i+1))
|
|
6899
|
+
done
|
|
6900
|
+
if is_alive \${NEW_PID}; then
|
|
6901
|
+
exit 0
|
|
6902
|
+
fi
|
|
6903
|
+
|
|
6904
|
+
# \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
|
|
6905
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6906
|
+
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
6907
|
+
echo ""
|
|
6908
|
+
echo "--- \u65E5\u5FD7 ---"
|
|
6909
|
+
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
6910
|
+
exit 2
|
|
6911
|
+
`;
|
|
6912
|
+
}
|
|
6913
|
+
async function startTun(prefetched) {
|
|
6914
|
+
ensureDirs();
|
|
6915
|
+
assertKernelInstalled();
|
|
6916
|
+
assertRuntimeConfigPresent();
|
|
6917
|
+
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
6918
|
+
if (serviceLoaded) {
|
|
6919
|
+
throw tunBlockedByConcurrentStart();
|
|
6920
|
+
}
|
|
6921
|
+
rotateAndCleanupLogs();
|
|
6922
|
+
const logFile = PATHS.logFile;
|
|
6923
|
+
if (fs12.existsSync(logFile)) {
|
|
6992
6924
|
try {
|
|
6993
|
-
|
|
6925
|
+
fs12.accessSync(logFile, fs12.constants.W_OK);
|
|
6994
6926
|
} catch {
|
|
6995
|
-
|
|
6927
|
+
try {
|
|
6928
|
+
fs12.unlinkSync(logFile);
|
|
6929
|
+
} catch {
|
|
6930
|
+
}
|
|
6996
6931
|
}
|
|
6997
6932
|
}
|
|
6998
|
-
const
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
function proxyEnvPointsAtSelf(value, selfPort) {
|
|
7004
|
-
const endpoint = parseProxyEndpoint(value);
|
|
7005
|
-
if (!endpoint) return false;
|
|
7006
|
-
return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
|
|
7007
|
-
}
|
|
7008
|
-
var clearedSelfProxyEnv = null;
|
|
7009
|
-
function recordClearedProxyEnv(cleared) {
|
|
7010
|
-
clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
|
|
7011
|
-
}
|
|
7012
|
-
function getClearedProxyEnv() {
|
|
7013
|
-
return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
|
|
7014
|
-
}
|
|
7015
|
-
function parseScutilProxy(stdout) {
|
|
7016
|
-
const values = /* @__PURE__ */ new Map();
|
|
7017
|
-
for (const line of stdout.split("\n")) {
|
|
7018
|
-
const m = line.match(/^ {2}([A-Za-z]+) : (.+)$/);
|
|
7019
|
-
if (m) values.set(m[1], m[2].trim());
|
|
7020
|
-
}
|
|
7021
|
-
const read = (prefix) => {
|
|
7022
|
-
if (values.get(`${prefix}Enable`) !== "1") return void 0;
|
|
7023
|
-
const host = values.get(`${prefix}Proxy`);
|
|
7024
|
-
const port = Number.parseInt(values.get(`${prefix}Port`) ?? "", 10);
|
|
7025
|
-
if (!host || !Number.isFinite(port)) return void 0;
|
|
7026
|
-
return { host, port };
|
|
7027
|
-
};
|
|
7028
|
-
const readPac = () => {
|
|
7029
|
-
if (values.get("ProxyAutoConfigEnable") === "1") {
|
|
7030
|
-
const url = values.get("ProxyAutoConfigURLString") ?? "";
|
|
7031
|
-
const host = values.get("ProxyAutoConfigHost");
|
|
7032
|
-
const port = values.get("ProxyAutoConfigPort");
|
|
7033
|
-
const legacy = host ? `${host}${port ? `:${port}` : ""}` : "";
|
|
7034
|
-
return { source: url || legacy, wpad: false };
|
|
7035
|
-
}
|
|
7036
|
-
if (values.get("ProxyAutoDiscoveryEnable") === "1") {
|
|
7037
|
-
return { source: "", wpad: true };
|
|
7038
|
-
}
|
|
7039
|
-
return void 0;
|
|
7040
|
-
};
|
|
7041
|
-
return { http: read("HTTP"), https: read("HTTPS"), socks: read("SOCKS"), pac: readPac() };
|
|
7042
|
-
}
|
|
7043
|
-
var entryMatches = (e, mixedPort) => isLoopbackHost(e.host) && e.port === mixedPort;
|
|
7044
|
-
function summarizeSystemProxy(view, mixedPort) {
|
|
7045
|
-
const entries = [view.http, view.https, view.socks].filter((e) => e !== void 0);
|
|
7046
|
-
return {
|
|
7047
|
-
matched: entries.some((e) => entryMatches(e, mixedPort)),
|
|
7048
|
-
active: [...new Set(entries.map((e) => `${e.host}:${e.port}`))],
|
|
7049
|
-
diverged: [...new Set(entries.filter((e) => !entryMatches(e, mixedPort)).map((e) => `${e.host}:${e.port}`))],
|
|
7050
|
-
pac: view.pac ?? null
|
|
7051
|
-
};
|
|
7052
|
-
}
|
|
7053
|
-
function detectSystemProxy(mixedPort) {
|
|
7054
|
-
let r;
|
|
7055
|
-
try {
|
|
7056
|
-
r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
|
|
7057
|
-
} catch {
|
|
7058
|
-
return null;
|
|
7059
|
-
}
|
|
7060
|
-
if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
|
|
7061
|
-
return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
|
|
7062
|
-
}
|
|
7063
|
-
function buildSystemProxyHint(summary, mixedPort) {
|
|
7064
|
-
const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
|
|
7065
|
-
if (summary === null) {
|
|
7066
|
-
return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
|
|
7067
|
-
}
|
|
7068
|
-
if (summary.pac) {
|
|
7069
|
-
const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
|
|
7070
|
-
return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
|
|
6933
|
+
const stalePids = getMihomoPids();
|
|
6934
|
+
if (stalePids.length > 0) {
|
|
6935
|
+
console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
6936
|
+
} else if (isPidFileOwnedByRoot()) {
|
|
6937
|
+
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
7071
6938
|
}
|
|
7072
|
-
|
|
7073
|
-
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7077
|
-
|
|
7078
|
-
|
|
7079
|
-
|
|
6939
|
+
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
6940
|
+
runSudoScript(buildTunLaunchScript(), {
|
|
6941
|
+
action: "TUN \u542F\u52A8",
|
|
6942
|
+
file: "launch-tun.sh",
|
|
6943
|
+
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
6944
|
+
});
|
|
6945
|
+
await sleep4(TUN_MODE_POST_WAIT_MS);
|
|
6946
|
+
const finalPid = getPid();
|
|
6947
|
+
if (!finalPid || !isRunning()) {
|
|
6948
|
+
const tail = readLogTail();
|
|
6949
|
+
throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
|
|
6950
|
+
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
|
|
6951
|
+
});
|
|
7080
6952
|
}
|
|
7081
|
-
|
|
7082
|
-
return {
|
|
7083
|
-
text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
|
|
7084
|
-
warning: true
|
|
7085
|
-
};
|
|
7086
|
-
}
|
|
7087
|
-
function printSystemProxyHint(mixedPort) {
|
|
7088
|
-
const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
|
|
7089
|
-
console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
|
|
6953
|
+
return finalPid;
|
|
7090
6954
|
}
|
|
7091
6955
|
|
|
7092
6956
|
// src/commands/status.ts
|
|
@@ -7141,7 +7005,7 @@ function buildStatusJson(args) {
|
|
|
7141
7005
|
// 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
|
|
7142
7006
|
applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
|
|
7143
7007
|
// 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
|
|
7144
|
-
// hint
|
|
7008
|
+
// hint 必须带出:可执行的修复指引(*edu 加引号、操作符写法等)都在里面,
|
|
7145
7009
|
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
7146
7010
|
errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
|
|
7147
7011
|
},
|
|
@@ -7391,7 +7255,8 @@ async function cmdStart(args) {
|
|
|
7391
7255
|
console.log(colors.yellow(`\u72B6\u6001\u5C55\u793A\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u5DF2\u5B8C\u6210\u7684\u542F\u52A8\uFF09: ${firstLine(e.message)}`));
|
|
7392
7256
|
}
|
|
7393
7257
|
if (targetMode === "mixed") {
|
|
7394
|
-
|
|
7258
|
+
const mixedPort = getPortsOrNull()?.mixed ?? DEFAULT_MIXED_PORT;
|
|
7259
|
+
console.log(colors.gray(`\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
|
|
7395
7260
|
} else {
|
|
7396
7261
|
console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
|
|
7397
7262
|
}
|
|
@@ -7399,20 +7264,20 @@ async function cmdStart(args) {
|
|
|
7399
7264
|
}
|
|
7400
7265
|
|
|
7401
7266
|
// src/commands/shared.ts
|
|
7402
|
-
function assertUniqueTokens(
|
|
7267
|
+
function assertUniqueTokens(entries, what) {
|
|
7403
7268
|
const owner = /* @__PURE__ */ new Map();
|
|
7404
|
-
for (const
|
|
7405
|
-
for (const token of [
|
|
7269
|
+
for (const entry of entries) {
|
|
7270
|
+
for (const token of [entry.name, ...entry.aliases ?? []]) {
|
|
7406
7271
|
const prev = owner.get(token);
|
|
7407
7272
|
if (prev !== void 0) {
|
|
7408
|
-
throw new Error(
|
|
7273
|
+
throw new Error(`${what}\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${entry.name}\uFF09`);
|
|
7409
7274
|
}
|
|
7410
|
-
owner.set(token,
|
|
7275
|
+
owner.set(token, entry.name);
|
|
7411
7276
|
}
|
|
7412
7277
|
}
|
|
7413
7278
|
}
|
|
7414
7279
|
async function dispatchSubcommand(args, table, options) {
|
|
7415
|
-
assertUniqueTokens(table);
|
|
7280
|
+
assertUniqueTokens(table, "\u5B50\u547D\u4EE4\u8868");
|
|
7416
7281
|
const action = args[1]?.toLowerCase();
|
|
7417
7282
|
if (action === "") {
|
|
7418
7283
|
throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
|
|
@@ -7514,11 +7379,11 @@ async function cmdDirectory(args) {
|
|
|
7514
7379
|
}
|
|
7515
7380
|
|
|
7516
7381
|
// src/commands/doctor.ts
|
|
7517
|
-
import
|
|
7382
|
+
import fs14 from "fs";
|
|
7518
7383
|
|
|
7519
7384
|
// src/kernel.ts
|
|
7520
|
-
import { execFile as execFile3, spawn as spawn2, spawnSync as
|
|
7521
|
-
import
|
|
7385
|
+
import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync8 } from "child_process";
|
|
7386
|
+
import fs13 from "fs";
|
|
7522
7387
|
import path8 from "path";
|
|
7523
7388
|
import { promisify as promisify3 } from "util";
|
|
7524
7389
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7574,7 +7439,7 @@ function ghProbeNeeded(input) {
|
|
|
7574
7439
|
return !input.forceDirect && input.proxyOverride === null;
|
|
7575
7440
|
}
|
|
7576
7441
|
function hasGh() {
|
|
7577
|
-
const result =
|
|
7442
|
+
const result = spawnSync8("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
|
|
7578
7443
|
return !result.error && result.status === 0;
|
|
7579
7444
|
}
|
|
7580
7445
|
function getArch() {
|
|
@@ -7773,6 +7638,8 @@ function buildGhReleaseDownloadArgs(tag, assetName, dir) {
|
|
|
7773
7638
|
function buildGhDownloadEnv(proxy) {
|
|
7774
7639
|
const env = { ...process.env };
|
|
7775
7640
|
if (proxy) {
|
|
7641
|
+
delete env.no_proxy;
|
|
7642
|
+
delete env.NO_PROXY;
|
|
7776
7643
|
env.HTTPS_PROXY = proxy;
|
|
7777
7644
|
env.https_proxy = proxy;
|
|
7778
7645
|
}
|
|
@@ -7866,7 +7733,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7866
7733
|
if (mirrorIneffective) {
|
|
7867
7734
|
console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
|
|
7868
7735
|
}
|
|
7869
|
-
const tempDir =
|
|
7736
|
+
const tempDir = fs13.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
7870
7737
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
7871
7738
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7872
7739
|
try {
|
|
@@ -7920,11 +7787,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7920
7787
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
|
|
7921
7788
|
}
|
|
7922
7789
|
}
|
|
7923
|
-
if (!
|
|
7790
|
+
if (!fs13.existsSync(tempPath)) {
|
|
7924
7791
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7925
7792
|
}
|
|
7926
7793
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7927
|
-
const actual =
|
|
7794
|
+
const actual = fs13.statSync(tempPath).size;
|
|
7928
7795
|
if (actual !== asset.size) {
|
|
7929
7796
|
throw new Error(
|
|
7930
7797
|
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
@@ -7937,11 +7804,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7937
7804
|
}
|
|
7938
7805
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
7939
7806
|
const gzipStdout = await decompressGzip(tempPath);
|
|
7940
|
-
|
|
7807
|
+
fs13.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
|
|
7941
7808
|
if (progressCallback) {
|
|
7942
7809
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7943
7810
|
}
|
|
7944
|
-
|
|
7811
|
+
fs13.chmodSync(foundBinary, 493);
|
|
7945
7812
|
const probe = probeKernelVersion(foundBinary);
|
|
7946
7813
|
if (probe.spawnError || probe.status !== 0 || probe.version === null) {
|
|
7947
7814
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
|
|
@@ -7954,11 +7821,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7954
7821
|
throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
|
|
7955
7822
|
}
|
|
7956
7823
|
const targetPath = PATHS.mihomoBinary;
|
|
7957
|
-
|
|
7824
|
+
fs13.renameSync(foundBinary, targetPath);
|
|
7958
7825
|
return { version: latest.tag_name };
|
|
7959
7826
|
} finally {
|
|
7960
7827
|
try {
|
|
7961
|
-
|
|
7828
|
+
fs13.rmSync(tempDir, { recursive: true, force: true });
|
|
7962
7829
|
} catch {
|
|
7963
7830
|
}
|
|
7964
7831
|
}
|
|
@@ -7968,6 +7835,56 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7968
7835
|
import { execFile as execFile4, spawn as spawn3 } from "child_process";
|
|
7969
7836
|
import net from "net";
|
|
7970
7837
|
import { promisify as promisify4 } from "util";
|
|
7838
|
+
|
|
7839
|
+
// src/proxy-env.ts
|
|
7840
|
+
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
7841
|
+
function isLoopbackHost(host) {
|
|
7842
|
+
const h = host.toLowerCase();
|
|
7843
|
+
return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
|
|
7844
|
+
}
|
|
7845
|
+
function parseProxyEndpoint(value) {
|
|
7846
|
+
let parsed;
|
|
7847
|
+
try {
|
|
7848
|
+
parsed = new URL(value);
|
|
7849
|
+
if (parsed.hostname === "") parsed = new URL(`http://${value}`);
|
|
7850
|
+
} catch {
|
|
7851
|
+
try {
|
|
7852
|
+
parsed = new URL(`http://${value}`);
|
|
7853
|
+
} catch {
|
|
7854
|
+
return null;
|
|
7855
|
+
}
|
|
7856
|
+
}
|
|
7857
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
7858
|
+
const defaultPort = parsed.protocol === "http:" ? 80 : parsed.protocol === "https:" ? 443 : null;
|
|
7859
|
+
const port = parsed.port === "" ? defaultPort : Number.parseInt(parsed.port, 10);
|
|
7860
|
+
if (!host || port === null || !Number.isInteger(port)) return null;
|
|
7861
|
+
return { host, port };
|
|
7862
|
+
}
|
|
7863
|
+
function proxyEnvPointsAtSelf(value, selfPort) {
|
|
7864
|
+
const endpoint = parseProxyEndpoint(value);
|
|
7865
|
+
if (!endpoint) return false;
|
|
7866
|
+
return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
|
|
7867
|
+
}
|
|
7868
|
+
function clearSelfProxyEnv(source, selfPort) {
|
|
7869
|
+
const cleared = {};
|
|
7870
|
+
for (const key of PROXY_ENV_KEYS) {
|
|
7871
|
+
const value = source[key];
|
|
7872
|
+
if (value && proxyEnvPointsAtSelf(value, selfPort)) {
|
|
7873
|
+
cleared[key] = value;
|
|
7874
|
+
delete source[key];
|
|
7875
|
+
}
|
|
7876
|
+
}
|
|
7877
|
+
return cleared;
|
|
7878
|
+
}
|
|
7879
|
+
var clearedSelfProxyEnv = null;
|
|
7880
|
+
function recordClearedProxyEnv(cleared) {
|
|
7881
|
+
clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
|
|
7882
|
+
}
|
|
7883
|
+
function getClearedProxyEnv() {
|
|
7884
|
+
return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
|
|
7885
|
+
}
|
|
7886
|
+
|
|
7887
|
+
// src/commands/update.ts
|
|
7971
7888
|
var execFileAsync3 = promisify4(execFile4);
|
|
7972
7889
|
function restoreProxyEnvForNpm(cleared, listening) {
|
|
7973
7890
|
return cleared !== null && listening ? cleared : {};
|
|
@@ -8120,20 +8037,20 @@ async function collectChecks() {
|
|
|
8120
8037
|
} else {
|
|
8121
8038
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
8122
8039
|
}
|
|
8123
|
-
if (
|
|
8040
|
+
if (fs14.existsSync(KERNEL_SELF_UPDATE_DIR)) {
|
|
8124
8041
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
|
|
8125
8042
|
}
|
|
8126
|
-
if (
|
|
8043
|
+
if (fs14.existsSync(KERNEL_SELF_BACKUP_DIR)) {
|
|
8127
8044
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
|
|
8128
8045
|
}
|
|
8129
8046
|
try {
|
|
8130
|
-
|
|
8047
|
+
fs14.accessSync(USER_DATA_DIR, fs14.constants.W_OK);
|
|
8131
8048
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
8132
8049
|
} catch {
|
|
8133
8050
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
8134
8051
|
}
|
|
8135
|
-
if (
|
|
8136
|
-
if (isValidSettingsContent(
|
|
8052
|
+
if (fs14.existsSync(PATHS.settingsFile)) {
|
|
8053
|
+
if (isValidSettingsContent(fs14.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
8137
8054
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
8138
8055
|
} else {
|
|
8139
8056
|
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
@@ -8336,12 +8253,7 @@ function parseMirrorArg(args) {
|
|
|
8336
8253
|
return { mirror: null, isOverride: false };
|
|
8337
8254
|
}
|
|
8338
8255
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8339
|
-
const hits = [];
|
|
8340
|
-
for (let i = 0; i < args.length; i++) {
|
|
8341
|
-
const match = matchValueFlagToken(args[i]);
|
|
8342
|
-
if (!match?.spec.forms.includes("--mirror")) continue;
|
|
8343
|
-
hits.push({ value: match.form === "exact" ? args[i + 1] ?? null : match.inlineValue });
|
|
8344
|
-
}
|
|
8256
|
+
const hits = collectFlagValues(args, ["--mirror"]);
|
|
8345
8257
|
if (hits.length === 0) {
|
|
8346
8258
|
return { mirror: null, isOverride: false };
|
|
8347
8259
|
}
|
|
@@ -8399,17 +8311,7 @@ function parseProxyArg(args) {
|
|
|
8399
8311
|
return { proxy: null };
|
|
8400
8312
|
}
|
|
8401
8313
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8402
|
-
const hits = [];
|
|
8403
|
-
for (let i = 0; i < args.length; i++) {
|
|
8404
|
-
const match = matchValueFlagToken(args[i]);
|
|
8405
|
-
if (!match?.spec.forms.includes("--proxy")) continue;
|
|
8406
|
-
if (match.form === "exact") {
|
|
8407
|
-
hits.push(args[i + 1] ?? "");
|
|
8408
|
-
i++;
|
|
8409
|
-
} else {
|
|
8410
|
-
hits.push(match.inlineValue ?? "");
|
|
8411
|
-
}
|
|
8412
|
-
}
|
|
8314
|
+
const hits = collectFlagValues(args, ["--proxy"]);
|
|
8413
8315
|
if (hits.length === 0) {
|
|
8414
8316
|
return { proxy: null };
|
|
8415
8317
|
}
|
|
@@ -8419,7 +8321,7 @@ function parseProxyArg(args) {
|
|
|
8419
8321
|
hint: ["\u7528\u6CD5: mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>", "\u4F8B\u5982: mihomo-cli kernel --proxy 7897"]
|
|
8420
8322
|
});
|
|
8421
8323
|
}
|
|
8422
|
-
const raw = hits[0].trim();
|
|
8324
|
+
const raw = (hits[0].value ?? "").trim();
|
|
8423
8325
|
if (!raw || raw.startsWith("-")) {
|
|
8424
8326
|
throw new CliError("--proxy \u9700\u8981\u4E00\u4E2A\u7AEF\u53E3\u6216\u4EE3\u7406\u5730\u5740", {
|
|
8425
8327
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8636,7 +8538,7 @@ function cmdLogs(args) {
|
|
|
8636
8538
|
if (logs.current) all.push(logs.current);
|
|
8637
8539
|
all.push(...logs.archives);
|
|
8638
8540
|
if (all.length === 0) {
|
|
8639
|
-
console.log("\u6682\u65E0\u65E5\u5FD7");
|
|
8541
|
+
console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
|
|
8640
8542
|
return;
|
|
8641
8543
|
}
|
|
8642
8544
|
console.log("");
|
|
@@ -8754,7 +8656,7 @@ async function cmdOverwrite(args) {
|
|
|
8754
8656
|
}
|
|
8755
8657
|
|
|
8756
8658
|
// src/commands/reset.ts
|
|
8757
|
-
import
|
|
8659
|
+
import fs15 from "fs";
|
|
8758
8660
|
var RESET_TARGETS = [
|
|
8759
8661
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
8760
8662
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -8766,7 +8668,7 @@ var RESET_TARGETS = [
|
|
|
8766
8668
|
label: "\u8986\u5199",
|
|
8767
8669
|
needsStop: false,
|
|
8768
8670
|
preserveOnBare: true,
|
|
8769
|
-
paths: () =>
|
|
8671
|
+
paths: () => fs15.existsSync(USER_DATA_DIR) ? fs15.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
8770
8672
|
},
|
|
8771
8673
|
{
|
|
8772
8674
|
// 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
|
|
@@ -8866,7 +8768,7 @@ async function cmdReset(args) {
|
|
|
8866
8768
|
for (const target of targets) {
|
|
8867
8769
|
let hadContent = target.id === "service" && serviceActive;
|
|
8868
8770
|
for (const filePath of target.paths()) {
|
|
8869
|
-
if (!
|
|
8771
|
+
if (!fs15.existsSync(filePath)) continue;
|
|
8870
8772
|
try {
|
|
8871
8773
|
rmrf(filePath);
|
|
8872
8774
|
} catch (e) {
|
|
@@ -8904,7 +8806,7 @@ async function cmdReset(args) {
|
|
|
8904
8806
|
}
|
|
8905
8807
|
|
|
8906
8808
|
// src/commands/service.ts
|
|
8907
|
-
import
|
|
8809
|
+
import fs16 from "fs";
|
|
8908
8810
|
function printRestoreSkipped() {
|
|
8909
8811
|
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
8910
8812
|
console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
|
|
@@ -8941,7 +8843,7 @@ async function cmdInstall(args) {
|
|
|
8941
8843
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
8942
8844
|
} else {
|
|
8943
8845
|
console.log("\u542F\u52A8: mihomo-cli start");
|
|
8944
|
-
if (!
|
|
8846
|
+
if (!fs16.existsSync(PATHS.configFile)) {
|
|
8945
8847
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
8946
8848
|
}
|
|
8947
8849
|
}
|
|
@@ -9009,7 +8911,7 @@ async function cmdStop(args) {
|
|
|
9009
8911
|
}
|
|
9010
8912
|
|
|
9011
8913
|
// src/commands/subscription.ts
|
|
9012
|
-
import { spawnSync as
|
|
8914
|
+
import { spawnSync as spawnSync9 } from "child_process";
|
|
9013
8915
|
function printRestartHintIfRunning(variant = "update") {
|
|
9014
8916
|
const state = getRunningState();
|
|
9015
8917
|
if (!state.running) return;
|
|
@@ -9064,7 +8966,7 @@ function printSubscriptionList() {
|
|
|
9064
8966
|
function readUrlFromClipboard() {
|
|
9065
8967
|
if (!process.stdin.isTTY) return null;
|
|
9066
8968
|
try {
|
|
9067
|
-
const r =
|
|
8969
|
+
const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
9068
8970
|
if (r.status !== 0) return null;
|
|
9069
8971
|
const text = (r.stdout || "").trim();
|
|
9070
8972
|
return isValidHttpUrl(text) ? text : null;
|
|
@@ -9255,7 +9157,7 @@ async function cmdSubscription(args) {
|
|
|
9255
9157
|
}
|
|
9256
9158
|
|
|
9257
9159
|
// src/commands/ui.ts
|
|
9258
|
-
import { spawnSync as
|
|
9160
|
+
import { spawnSync as spawnSync10 } from "child_process";
|
|
9259
9161
|
function resolveUiName(args) {
|
|
9260
9162
|
const raw = getNonFlagArg(args, 1);
|
|
9261
9163
|
const name = (raw ?? "zash").toLowerCase();
|
|
@@ -9266,7 +9168,7 @@ function resolveUiName(args) {
|
|
|
9266
9168
|
}
|
|
9267
9169
|
function copyToClipboard(text) {
|
|
9268
9170
|
try {
|
|
9269
|
-
return
|
|
9171
|
+
return spawnSync10("pbcopy", [], { input: text, timeout: 3e3 }).status === 0;
|
|
9270
9172
|
} catch {
|
|
9271
9173
|
return false;
|
|
9272
9174
|
}
|
|
@@ -9358,7 +9260,12 @@ var COMMANDS = [
|
|
|
9358
9260
|
aliases: [],
|
|
9359
9261
|
handler: cmdLogs,
|
|
9360
9262
|
group: "interface",
|
|
9361
|
-
usage: [
|
|
9263
|
+
usage: [
|
|
9264
|
+
{
|
|
9265
|
+
signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]",
|
|
9266
|
+
description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7"
|
|
9267
|
+
}
|
|
9268
|
+
]
|
|
9362
9269
|
},
|
|
9363
9270
|
// === 订阅 ===
|
|
9364
9271
|
{
|
|
@@ -9458,18 +9365,8 @@ var COMMANDS = [
|
|
|
9458
9365
|
usage: [{ signature: "version", description: "\u663E\u793A\u7248\u672C" }]
|
|
9459
9366
|
}
|
|
9460
9367
|
];
|
|
9461
|
-
|
|
9462
|
-
|
|
9463
|
-
for (const cmd of COMMANDS) {
|
|
9464
|
-
for (const token of [cmd.name, ...cmd.aliases]) {
|
|
9465
|
-
if (index.has(token)) {
|
|
9466
|
-
throw new Error(`\u547D\u4EE4\u6CE8\u518C\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${index.get(token)?.name} \u4E0E ${cmd.name}\uFF09`);
|
|
9467
|
-
}
|
|
9468
|
-
index.set(token, cmd);
|
|
9469
|
-
}
|
|
9470
|
-
}
|
|
9471
|
-
return index;
|
|
9472
|
-
})();
|
|
9368
|
+
assertUniqueTokens(COMMANDS, "\u547D\u4EE4\u6CE8\u518C\u8868");
|
|
9369
|
+
var COMMAND_INDEX = new Map(COMMANDS.flatMap((cmd) => [cmd.name, ...cmd.aliases].map((token) => [token, cmd])));
|
|
9473
9370
|
function findCommand(token) {
|
|
9474
9371
|
return COMMAND_INDEX.get(token);
|
|
9475
9372
|
}
|
|
@@ -9502,10 +9399,9 @@ process.on("unhandledRejection", (reason) => {
|
|
|
9502
9399
|
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
|
|
9503
9400
|
process.exit(1);
|
|
9504
9401
|
});
|
|
9505
|
-
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
9506
9402
|
function readSelfMixedPortEarly() {
|
|
9507
9403
|
try {
|
|
9508
|
-
const raw = JSON.parse(
|
|
9404
|
+
const raw = JSON.parse(fs17.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9509
9405
|
const mixed = raw?.ports?.mixed;
|
|
9510
9406
|
if (isValidPortNumber(mixed)) return mixed;
|
|
9511
9407
|
} catch {
|
|
@@ -9513,15 +9409,7 @@ function readSelfMixedPortEarly() {
|
|
|
9513
9409
|
return DEFAULT_MIXED_PORT;
|
|
9514
9410
|
}
|
|
9515
9411
|
function clearProxyEnv() {
|
|
9516
|
-
const
|
|
9517
|
-
const cleared = {};
|
|
9518
|
-
for (const key of PROXY_ENV_KEYS) {
|
|
9519
|
-
const value = process.env[key];
|
|
9520
|
-
if (value && proxyEnvPointsAtSelf(value, selfPort)) {
|
|
9521
|
-
cleared[key] = value;
|
|
9522
|
-
delete process.env[key];
|
|
9523
|
-
}
|
|
9524
|
-
}
|
|
9412
|
+
const cleared = clearSelfProxyEnv(process.env, readSelfMixedPortEarly());
|
|
9525
9413
|
if (Object.keys(cleared).length > 0) recordClearedProxyEnv(cleared);
|
|
9526
9414
|
}
|
|
9527
9415
|
var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
|