mihomo-cli 26.10.114 → 26.10.115
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -10
- package/README.md +21 -6
- package/dist/index.js +566 -275
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import
|
|
4
|
+
import fs20 from "fs";
|
|
5
5
|
|
|
6
6
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
7
7
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
@@ -3684,6 +3684,8 @@ var PATHS = {
|
|
|
3684
3684
|
subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
|
|
3685
3685
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
3686
3686
|
logFile: path.join(DIRS.logs, "mihomo.log"),
|
|
3687
|
+
/** CLI 结构化操作事件;独立于内核文本日志及其归档编号,由 diagnostic-events.ts 自管轮转 */
|
|
3688
|
+
diagnosticEventsFile: path.join(DIRS.logs, "diagnostic.jsonl"),
|
|
3687
3689
|
pidFile: path.join(DIRS.runtime, "pid"),
|
|
3688
3690
|
/**
|
|
3689
3691
|
* installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
|
|
@@ -4910,13 +4912,13 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
|
|
|
4910
4912
|
);
|
|
4911
4913
|
return hint;
|
|
4912
4914
|
}
|
|
4913
|
-
async function validateConfigWithKernel(
|
|
4915
|
+
async function validateConfigWithKernel(configContent, overwriteSummaries) {
|
|
4914
4916
|
assertKernelInstalled();
|
|
4915
4917
|
ensureDirs();
|
|
4916
4918
|
const stageDir = fs4.mkdtempSync(path4.join(USER_DATA_DIR, "check-"));
|
|
4917
4919
|
const stageFile = path4.join(stageDir, "config.yaml");
|
|
4918
4920
|
try {
|
|
4919
|
-
fs4.writeFileSync(stageFile,
|
|
4921
|
+
fs4.writeFileSync(stageFile, configContent, { mode: 384 });
|
|
4920
4922
|
try {
|
|
4921
4923
|
await promisify(execFile)(PATHS.mihomoBinary, ["-t", "-d", DIRS.data, "-f", stageFile], {
|
|
4922
4924
|
encoding: "utf8",
|
|
@@ -5413,6 +5415,237 @@ function redactConfigSecrets(config) {
|
|
|
5413
5415
|
return { config: walk(config, false, state), changed: state.changed };
|
|
5414
5416
|
}
|
|
5415
5417
|
|
|
5418
|
+
// src/diagnostic-events.ts
|
|
5419
|
+
import { createHash, randomUUID } from "crypto";
|
|
5420
|
+
import fs7 from "fs";
|
|
5421
|
+
|
|
5422
|
+
// src/log-files.ts
|
|
5423
|
+
import fs6 from "fs";
|
|
5424
|
+
import path5 from "path";
|
|
5425
|
+
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5426
|
+
var LOG_TAIL_LINES = 15;
|
|
5427
|
+
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5428
|
+
function isArchiveLogFilename(filename) {
|
|
5429
|
+
return ARCHIVE_LOG_RE.test(filename);
|
|
5430
|
+
}
|
|
5431
|
+
function rotateAndCleanupLogs() {
|
|
5432
|
+
rotateLog();
|
|
5433
|
+
cleanupOldLogs();
|
|
5434
|
+
}
|
|
5435
|
+
function readLogTail() {
|
|
5436
|
+
const TAIL_BYTES = 64 * 1024;
|
|
5437
|
+
let fd = null;
|
|
5438
|
+
try {
|
|
5439
|
+
const size = fs6.statSync(PATHS.logFile).size;
|
|
5440
|
+
if (size === 0) return [];
|
|
5441
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
5442
|
+
const length = size - start;
|
|
5443
|
+
const buf = Buffer.alloc(length);
|
|
5444
|
+
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5445
|
+
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5446
|
+
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5447
|
+
} catch {
|
|
5448
|
+
return [];
|
|
5449
|
+
} finally {
|
|
5450
|
+
if (fd !== null) {
|
|
5451
|
+
try {
|
|
5452
|
+
fs6.closeSync(fd);
|
|
5453
|
+
} catch {
|
|
5454
|
+
}
|
|
5455
|
+
}
|
|
5456
|
+
}
|
|
5457
|
+
}
|
|
5458
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5459
|
+
function allocateArchivePath(prefix = "mihomo", extension = "log") {
|
|
5460
|
+
const timestamp = formatLocalTimestamp();
|
|
5461
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5462
|
+
const name = seq === 0 ? `${prefix}.${timestamp}.${extension}` : `${prefix}.${timestamp}.${seq}.${extension}`;
|
|
5463
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
5464
|
+
let fd = null;
|
|
5465
|
+
try {
|
|
5466
|
+
fd = fs6.openSync(archivePath, "wx");
|
|
5467
|
+
} catch (e) {
|
|
5468
|
+
if (e.code === "EEXIST") continue;
|
|
5469
|
+
throw e;
|
|
5470
|
+
}
|
|
5471
|
+
try {
|
|
5472
|
+
fs6.closeSync(fd);
|
|
5473
|
+
} catch {
|
|
5474
|
+
}
|
|
5475
|
+
return archivePath;
|
|
5476
|
+
}
|
|
5477
|
+
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
5478
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
5479
|
+
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
5480
|
+
});
|
|
5481
|
+
}
|
|
5482
|
+
function rotateFile(filePath, minBytes, prefix = "mihomo", extension = "log") {
|
|
5483
|
+
let stat;
|
|
5484
|
+
try {
|
|
5485
|
+
stat = fs6.statSync(filePath);
|
|
5486
|
+
} catch (e) {
|
|
5487
|
+
if (e.code === "ENOENT") return false;
|
|
5488
|
+
throw e;
|
|
5489
|
+
}
|
|
5490
|
+
if (stat.size < minBytes) return false;
|
|
5491
|
+
const rotatedPath = allocateArchivePath(prefix, extension);
|
|
5492
|
+
try {
|
|
5493
|
+
fs6.renameSync(filePath, rotatedPath);
|
|
5494
|
+
return true;
|
|
5495
|
+
} catch (e) {
|
|
5496
|
+
try {
|
|
5497
|
+
fs6.unlinkSync(rotatedPath);
|
|
5498
|
+
} catch {
|
|
5499
|
+
}
|
|
5500
|
+
if (e.code === "ENOENT") return false;
|
|
5501
|
+
throw e;
|
|
5502
|
+
}
|
|
5503
|
+
}
|
|
5504
|
+
function rotateLog() {
|
|
5505
|
+
rotateFile(PATHS.logFile, 1);
|
|
5506
|
+
}
|
|
5507
|
+
function cleanupOldArchives(isArchive) {
|
|
5508
|
+
const logsDir = DIRS.logs;
|
|
5509
|
+
if (!fs6.existsSync(logsDir)) return;
|
|
5510
|
+
const files = fs6.readdirSync(logsDir);
|
|
5511
|
+
const now = Date.now();
|
|
5512
|
+
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5513
|
+
for (const file of files) {
|
|
5514
|
+
if (!isArchive(file)) continue;
|
|
5515
|
+
try {
|
|
5516
|
+
const filePath = path5.join(logsDir, file);
|
|
5517
|
+
const stat = fs6.statSync(filePath);
|
|
5518
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5519
|
+
fs6.unlinkSync(filePath);
|
|
5520
|
+
}
|
|
5521
|
+
} catch {
|
|
5522
|
+
}
|
|
5523
|
+
}
|
|
5524
|
+
}
|
|
5525
|
+
function cleanupOldLogs() {
|
|
5526
|
+
cleanupOldArchives(isArchiveLogFilename);
|
|
5527
|
+
}
|
|
5528
|
+
function listLogs() {
|
|
5529
|
+
const logsDir = DIRS.logs;
|
|
5530
|
+
const result = { current: null, archives: [] };
|
|
5531
|
+
if (fs6.existsSync(PATHS.logFile)) {
|
|
5532
|
+
const stat = fs6.statSync(PATHS.logFile);
|
|
5533
|
+
result.current = {
|
|
5534
|
+
name: "mihomo.log (\u5F53\u524D)",
|
|
5535
|
+
path: PATHS.logFile,
|
|
5536
|
+
size: stat.size,
|
|
5537
|
+
mtime: stat.mtime,
|
|
5538
|
+
isCurrent: true
|
|
5539
|
+
};
|
|
5540
|
+
}
|
|
5541
|
+
if (!fs6.existsSync(logsDir)) return result;
|
|
5542
|
+
const files = fs6.readdirSync(logsDir);
|
|
5543
|
+
for (const file of files) {
|
|
5544
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
5545
|
+
try {
|
|
5546
|
+
const filePath = path5.join(logsDir, file);
|
|
5547
|
+
const stat = fs6.statSync(filePath);
|
|
5548
|
+
result.archives.push({
|
|
5549
|
+
name: file,
|
|
5550
|
+
path: filePath,
|
|
5551
|
+
size: stat.size,
|
|
5552
|
+
mtime: stat.mtime,
|
|
5553
|
+
isCurrent: false
|
|
5554
|
+
});
|
|
5555
|
+
} catch {
|
|
5556
|
+
}
|
|
5557
|
+
}
|
|
5558
|
+
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
5559
|
+
return result;
|
|
5560
|
+
}
|
|
5561
|
+
|
|
5562
|
+
// src/diagnostic-events.ts
|
|
5563
|
+
var context = null;
|
|
5564
|
+
var exitHookRegistered = false;
|
|
5565
|
+
var DIAGNOSTIC_LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
5566
|
+
var DIAGNOSTIC_ARCHIVE_RE = /^diagnostic\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/;
|
|
5567
|
+
function beginDiagnosticOperation(command) {
|
|
5568
|
+
context = { operationId: randomUUID(), command, startedAt: Date.now() };
|
|
5569
|
+
if (exitHookRegistered) return;
|
|
5570
|
+
exitHookRegistered = true;
|
|
5571
|
+
process.once("exit", (exitCode) => {
|
|
5572
|
+
if (!context) return;
|
|
5573
|
+
recordDiagnosticEvent("cli.command", exitCode === 0 ? "success" : "failure", {
|
|
5574
|
+
exitCode,
|
|
5575
|
+
durationMs: Date.now() - context.startedAt
|
|
5576
|
+
});
|
|
5577
|
+
});
|
|
5578
|
+
}
|
|
5579
|
+
function setDiagnosticCommand(command) {
|
|
5580
|
+
if (context) context.command = command;
|
|
5581
|
+
}
|
|
5582
|
+
function hashDiagnosticContent(content) {
|
|
5583
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
5584
|
+
}
|
|
5585
|
+
function hashDiagnosticFile(filePath) {
|
|
5586
|
+
try {
|
|
5587
|
+
return hashDiagnosticContent(fs7.readFileSync(filePath, "utf8"));
|
|
5588
|
+
} catch {
|
|
5589
|
+
return null;
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
5592
|
+
var KNOWN_ERROR_NAMES = /* @__PURE__ */ new Set(["Error", "TypeError", "RangeError", "SyntaxError", "CliError", "AbortError", "TimeoutError", "SudoAuthError"]);
|
|
5593
|
+
function safeErrorCode(value) {
|
|
5594
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
5595
|
+
if (typeof value === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(value)) return value;
|
|
5596
|
+
return void 0;
|
|
5597
|
+
}
|
|
5598
|
+
function safeHttpStatus(value) {
|
|
5599
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : void 0;
|
|
5600
|
+
}
|
|
5601
|
+
function diagnosticErrorDetails(error) {
|
|
5602
|
+
if (!(error instanceof Error)) return { errorType: "NonError" };
|
|
5603
|
+
const details = {};
|
|
5604
|
+
let current = error;
|
|
5605
|
+
for (let depth = 0; depth < 6 && current instanceof Error; depth++) {
|
|
5606
|
+
details.errorType = KNOWN_ERROR_NAMES.has(current.name) ? current.name : "Error";
|
|
5607
|
+
if (current instanceof CliError) details.errorLabel = current.label;
|
|
5608
|
+
if (current.name === "AbortError") details.aborted = true;
|
|
5609
|
+
const withMetadata = current;
|
|
5610
|
+
const errorCode = safeErrorCode(withMetadata.code);
|
|
5611
|
+
const httpStatus = safeHttpStatus(withMetadata.response?.status);
|
|
5612
|
+
if (details.errorCode === void 0 && errorCode !== void 0) details.errorCode = errorCode;
|
|
5613
|
+
if (details.httpStatus === void 0 && httpStatus !== void 0) details.httpStatus = httpStatus;
|
|
5614
|
+
current = withMetadata.cause;
|
|
5615
|
+
}
|
|
5616
|
+
return details;
|
|
5617
|
+
}
|
|
5618
|
+
function rotateDiagnosticLogIfNeeded() {
|
|
5619
|
+
if (rotateFile(PATHS.diagnosticEventsFile, DIAGNOSTIC_LOG_MAX_BYTES, "diagnostic", "jsonl")) {
|
|
5620
|
+
cleanupOldArchives((file) => DIAGNOSTIC_ARCHIVE_RE.test(file));
|
|
5621
|
+
}
|
|
5622
|
+
}
|
|
5623
|
+
function recordDiagnosticEvent(event, result, details = {}) {
|
|
5624
|
+
if (!context) return;
|
|
5625
|
+
try {
|
|
5626
|
+
const line = `${JSON.stringify({
|
|
5627
|
+
v: 1,
|
|
5628
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5629
|
+
event,
|
|
5630
|
+
result,
|
|
5631
|
+
operationId: context.operationId,
|
|
5632
|
+
command: context.command,
|
|
5633
|
+
pid: process.pid,
|
|
5634
|
+
...details
|
|
5635
|
+
})}
|
|
5636
|
+
`;
|
|
5637
|
+
rotateDiagnosticLogIfNeeded();
|
|
5638
|
+
try {
|
|
5639
|
+
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5640
|
+
} catch (e) {
|
|
5641
|
+
if (e.code !== "ENOENT") throw e;
|
|
5642
|
+
fs7.mkdirSync(DIRS.logs, { recursive: true, mode: 448 });
|
|
5643
|
+
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5644
|
+
}
|
|
5645
|
+
} catch {
|
|
5646
|
+
}
|
|
5647
|
+
}
|
|
5648
|
+
|
|
5416
5649
|
// src/http.ts
|
|
5417
5650
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5418
5651
|
var MAX_REDIRECTS = 20;
|
|
@@ -5689,77 +5922,145 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
5689
5922
|
});
|
|
5690
5923
|
}
|
|
5691
5924
|
async function downloadSubscription(url, subName, signal) {
|
|
5692
|
-
|
|
5925
|
+
const startedAt = Date.now();
|
|
5926
|
+
let stage = "http";
|
|
5927
|
+
let rollback;
|
|
5693
5928
|
try {
|
|
5694
|
-
response
|
|
5695
|
-
} catch (e) {
|
|
5696
|
-
const maskedUrl = maskUrl(url);
|
|
5697
|
-
let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
|
|
5698
|
-
const err = e;
|
|
5699
|
-
if (err.response) {
|
|
5700
|
-
errorMsg += ` (HTTP ${err.response.status})`;
|
|
5701
|
-
}
|
|
5702
|
-
errorMsg += `
|
|
5703
|
-
URL: ${maskedUrl}`;
|
|
5704
|
-
throw new Error(errorMsg);
|
|
5705
|
-
}
|
|
5706
|
-
const content = response.data;
|
|
5707
|
-
if (!content?.trim()) {
|
|
5708
|
-
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5709
|
-
}
|
|
5710
|
-
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5711
|
-
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5712
|
-
const meta = extractSubscriptionMeta(response.headers);
|
|
5713
|
-
withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5714
|
-
const previousContent = readSubscriptionRawConfig(subName);
|
|
5715
|
-
saveSubscriptionRawConfig(subName, content);
|
|
5929
|
+
let response;
|
|
5716
5930
|
try {
|
|
5717
|
-
|
|
5931
|
+
response = await HTTP_CLIENT.get(url, { signal });
|
|
5718
5932
|
} catch (e) {
|
|
5719
|
-
|
|
5933
|
+
const maskedUrl = maskUrl(url);
|
|
5934
|
+
let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
|
|
5935
|
+
const err = e;
|
|
5936
|
+
if (err.response) {
|
|
5937
|
+
errorMsg += ` (HTTP ${err.response.status})`;
|
|
5938
|
+
}
|
|
5939
|
+
errorMsg += `
|
|
5940
|
+
URL: ${maskedUrl}`;
|
|
5941
|
+
throw new Error(errorMsg, { cause: e });
|
|
5942
|
+
}
|
|
5943
|
+
stage = "empty-response";
|
|
5944
|
+
const content = response.data;
|
|
5945
|
+
if (!content?.trim()) {
|
|
5946
|
+
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5947
|
+
}
|
|
5948
|
+
stage = "parse";
|
|
5949
|
+
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5950
|
+
stage = "content-validation";
|
|
5951
|
+
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5952
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5953
|
+
const rawAfterSha256 = hashDiagnosticContent(content);
|
|
5954
|
+
const meta = extractSubscriptionMeta(response.headers);
|
|
5955
|
+
stage = "raw-commit";
|
|
5956
|
+
const previousContent = withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5957
|
+
const previousContent2 = readSubscriptionRawConfig(subName);
|
|
5958
|
+
saveSubscriptionRawConfig(subName, content);
|
|
5959
|
+
stage = "cache-commit";
|
|
5720
5960
|
try {
|
|
5721
|
-
|
|
5722
|
-
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
|
|
5726
|
-
|
|
5961
|
+
saveSubscriptionMeta(subName, meta);
|
|
5962
|
+
} catch (e) {
|
|
5963
|
+
let rollbackHint;
|
|
5964
|
+
try {
|
|
5965
|
+
if (previousContent2 === null) {
|
|
5966
|
+
removeSubscriptionRawConfig(subName);
|
|
5967
|
+
rollback = "deleted";
|
|
5968
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
|
|
5969
|
+
} else {
|
|
5970
|
+
saveSubscriptionRawConfig(subName, previousContent2);
|
|
5971
|
+
rollback = "restored";
|
|
5972
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
|
|
5973
|
+
}
|
|
5974
|
+
} catch (rollbackError) {
|
|
5975
|
+
rollback = "failed";
|
|
5976
|
+
rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
|
|
5727
5977
|
}
|
|
5728
|
-
|
|
5729
|
-
|
|
5978
|
+
throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
|
|
5979
|
+
label: "\u66F4\u65B0\u5931\u8D25",
|
|
5980
|
+
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5981
|
+
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5982
|
+
hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
5983
|
+
});
|
|
5730
5984
|
}
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5985
|
+
return previousContent2;
|
|
5986
|
+
});
|
|
5987
|
+
const changed = previousContent !== content;
|
|
5988
|
+
const rawBeforeSha256 = previousContent === null ? null : changed ? hashDiagnosticContent(previousContent) : rawAfterSha256;
|
|
5989
|
+
recordDiagnosticEvent("subscription.download", "success", {
|
|
5990
|
+
stage: "commit",
|
|
5991
|
+
durationMs: Date.now() - startedAt,
|
|
5992
|
+
rawBeforeSha256,
|
|
5993
|
+
rawAfterSha256,
|
|
5994
|
+
changed,
|
|
5995
|
+
proxies,
|
|
5996
|
+
proxyGroups
|
|
5997
|
+
});
|
|
5998
|
+
return { proxies, proxyGroups };
|
|
5999
|
+
} catch (e) {
|
|
6000
|
+
recordDiagnosticEvent("subscription.download", signal?.aborted === true ? "aborted" : "failure", {
|
|
6001
|
+
stage,
|
|
6002
|
+
durationMs: Date.now() - startedAt,
|
|
6003
|
+
rollback,
|
|
6004
|
+
...diagnosticErrorDetails(e)
|
|
6005
|
+
});
|
|
6006
|
+
throw e;
|
|
6007
|
+
}
|
|
5741
6008
|
}
|
|
5742
|
-
async function prepareConfigForStart(mode, subName) {
|
|
5743
|
-
|
|
6009
|
+
async function prepareConfigForStart(mode, subName, purpose = "start") {
|
|
6010
|
+
const startedAt = Date.now();
|
|
6011
|
+
let stage = "read";
|
|
6012
|
+
let sourceRawSha256;
|
|
6013
|
+
let candidateSha256;
|
|
5744
6014
|
try {
|
|
5745
|
-
rawContent
|
|
5746
|
-
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
6015
|
+
let rawContent;
|
|
6016
|
+
try {
|
|
6017
|
+
rawContent = requireSubscriptionRawConfig(subName);
|
|
6018
|
+
} catch (e) {
|
|
6019
|
+
if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
|
|
6020
|
+
throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
|
|
6021
|
+
hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
|
|
6022
|
+
});
|
|
6023
|
+
}
|
|
6024
|
+
throw e;
|
|
5751
6025
|
}
|
|
6026
|
+
sourceRawSha256 = hashDiagnosticContent(rawContent);
|
|
6027
|
+
stage = "build";
|
|
6028
|
+
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
6029
|
+
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
6030
|
+
const candidateContent = dumpYaml(buildResult.config);
|
|
6031
|
+
candidateSha256 = hashDiagnosticContent(candidateContent);
|
|
6032
|
+
stage = "validate";
|
|
6033
|
+
await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
|
|
6034
|
+
const info = countConfigNodes(buildResult.config);
|
|
6035
|
+
recordDiagnosticEvent("config.prepare", "success", {
|
|
6036
|
+
stage,
|
|
6037
|
+
purpose,
|
|
6038
|
+
mode,
|
|
6039
|
+
durationMs: Date.now() - startedAt,
|
|
6040
|
+
sourceRawSha256,
|
|
6041
|
+
candidateSha256,
|
|
6042
|
+
...info
|
|
6043
|
+
});
|
|
6044
|
+
return {
|
|
6045
|
+
buildResult,
|
|
6046
|
+
info,
|
|
6047
|
+
diagnostic: { sourceRawSha256, candidateSha256 }
|
|
6048
|
+
};
|
|
6049
|
+
} catch (e) {
|
|
6050
|
+
recordDiagnosticEvent("config.prepare", "failure", {
|
|
6051
|
+
stage,
|
|
6052
|
+
purpose,
|
|
6053
|
+
mode,
|
|
6054
|
+
durationMs: Date.now() - startedAt,
|
|
6055
|
+
sourceRawSha256,
|
|
6056
|
+
candidateSha256,
|
|
6057
|
+
...diagnosticErrorDetails(e)
|
|
6058
|
+
});
|
|
5752
6059
|
throw e;
|
|
5753
6060
|
}
|
|
5754
|
-
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5755
|
-
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5756
|
-
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
5757
|
-
return {
|
|
5758
|
-
buildResult,
|
|
5759
|
-
info: countConfigNodes(buildResult.config)
|
|
5760
|
-
};
|
|
5761
6061
|
}
|
|
5762
6062
|
function commitPreparedConfig(prepared) {
|
|
6063
|
+
const startedAt = Date.now();
|
|
5763
6064
|
const { buildResult } = prepared;
|
|
5764
6065
|
if (buildResult.warnings.length > 0) {
|
|
5765
6066
|
for (const warning of buildResult.warnings) {
|
|
@@ -5767,7 +6068,30 @@ function commitPreparedConfig(prepared) {
|
|
|
5767
6068
|
}
|
|
5768
6069
|
console.log("");
|
|
5769
6070
|
}
|
|
5770
|
-
|
|
6071
|
+
const runtimeBeforeSha256 = hashDiagnosticFile(PATHS.configFile);
|
|
6072
|
+
try {
|
|
6073
|
+
writeMihomoConfig(buildResult.config);
|
|
6074
|
+
} catch (e) {
|
|
6075
|
+
recordDiagnosticEvent("config.commit", "failure", {
|
|
6076
|
+
stage: "write",
|
|
6077
|
+
durationMs: Date.now() - startedAt,
|
|
6078
|
+
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6079
|
+
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6080
|
+
runtimeBeforeSha256,
|
|
6081
|
+
...diagnosticErrorDetails(e)
|
|
6082
|
+
});
|
|
6083
|
+
throw e;
|
|
6084
|
+
}
|
|
6085
|
+
recordDiagnosticEvent("config.commit", "success", {
|
|
6086
|
+
stage: "write",
|
|
6087
|
+
durationMs: Date.now() - startedAt,
|
|
6088
|
+
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6089
|
+
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6090
|
+
runtimeBeforeSha256,
|
|
6091
|
+
runtimeAfterSha256: prepared.diagnostic.candidateSha256,
|
|
6092
|
+
changed: runtimeBeforeSha256 === null ? null : runtimeBeforeSha256 !== prepared.diagnostic.candidateSha256,
|
|
6093
|
+
...prepared.info
|
|
6094
|
+
});
|
|
5771
6095
|
return prepared.info;
|
|
5772
6096
|
}
|
|
5773
6097
|
function needsAutoUpdate(sub) {
|
|
@@ -5800,6 +6124,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5800
6124
|
const allSubs = getSubscriptionsWithCache();
|
|
5801
6125
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
5802
6126
|
if (staleSubs.length === 0) {
|
|
6127
|
+
recordDiagnosticEvent("subscription.auto-update", "skipped", { reason: "fresh", staleCount: 0 });
|
|
5803
6128
|
return;
|
|
5804
6129
|
}
|
|
5805
6130
|
if (staleSubs.length === 1) {
|
|
@@ -5829,9 +6154,24 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5829
6154
|
});
|
|
5830
6155
|
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
5831
6156
|
}
|
|
6157
|
+
const timedOut = controller.signal.aborted;
|
|
6158
|
+
let succeeded = 0;
|
|
6159
|
+
let abortedCount = 0;
|
|
6160
|
+
let failed = 0;
|
|
5832
6161
|
for (const r of results) {
|
|
5833
6162
|
printUpdateResult(r);
|
|
5834
|
-
|
|
6163
|
+
if (r.success) succeeded++;
|
|
6164
|
+
else if (r.aborted === true) abortedCount++;
|
|
6165
|
+
else failed++;
|
|
6166
|
+
}
|
|
6167
|
+
recordDiagnosticEvent("subscription.auto-update", timedOut ? "timeout" : failed > 0 ? "failure" : "success", {
|
|
6168
|
+
staleCount: staleSubs.length,
|
|
6169
|
+
timeoutMs,
|
|
6170
|
+
timedOut,
|
|
6171
|
+
succeeded,
|
|
6172
|
+
failed,
|
|
6173
|
+
abortedCount
|
|
6174
|
+
});
|
|
5835
6175
|
}
|
|
5836
6176
|
|
|
5837
6177
|
// src/commands/config.ts
|
|
@@ -5944,143 +6284,9 @@ function viewLogWithTail(logPath, options) {
|
|
|
5944
6284
|
// src/commands/shared.ts
|
|
5945
6285
|
import readline from "readline";
|
|
5946
6286
|
|
|
5947
|
-
// src/log-files.ts
|
|
5948
|
-
import fs6 from "fs";
|
|
5949
|
-
import path5 from "path";
|
|
5950
|
-
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5951
|
-
var LOG_TAIL_LINES = 15;
|
|
5952
|
-
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5953
|
-
function isArchiveLogFilename(filename) {
|
|
5954
|
-
return ARCHIVE_LOG_RE.test(filename);
|
|
5955
|
-
}
|
|
5956
|
-
function rotateAndCleanupLogs() {
|
|
5957
|
-
rotateLog();
|
|
5958
|
-
cleanupOldLogs();
|
|
5959
|
-
}
|
|
5960
|
-
function readLogTail() {
|
|
5961
|
-
const TAIL_BYTES = 64 * 1024;
|
|
5962
|
-
let fd = null;
|
|
5963
|
-
try {
|
|
5964
|
-
const size = fs6.statSync(PATHS.logFile).size;
|
|
5965
|
-
if (size === 0) return [];
|
|
5966
|
-
const start = Math.max(0, size - TAIL_BYTES);
|
|
5967
|
-
const length = size - start;
|
|
5968
|
-
const buf = Buffer.alloc(length);
|
|
5969
|
-
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5970
|
-
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5971
|
-
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5972
|
-
} catch {
|
|
5973
|
-
return [];
|
|
5974
|
-
} finally {
|
|
5975
|
-
if (fd !== null) {
|
|
5976
|
-
try {
|
|
5977
|
-
fs6.closeSync(fd);
|
|
5978
|
-
} catch {
|
|
5979
|
-
}
|
|
5980
|
-
}
|
|
5981
|
-
}
|
|
5982
|
-
}
|
|
5983
|
-
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5984
|
-
function allocateArchivePath() {
|
|
5985
|
-
const timestamp = formatLocalTimestamp();
|
|
5986
|
-
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5987
|
-
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
5988
|
-
const archivePath = path5.join(DIRS.logs, name);
|
|
5989
|
-
let fd = null;
|
|
5990
|
-
try {
|
|
5991
|
-
fd = fs6.openSync(archivePath, "wx");
|
|
5992
|
-
} catch (e) {
|
|
5993
|
-
if (e.code === "EEXIST") continue;
|
|
5994
|
-
throw e;
|
|
5995
|
-
}
|
|
5996
|
-
try {
|
|
5997
|
-
fs6.closeSync(fd);
|
|
5998
|
-
} catch {
|
|
5999
|
-
}
|
|
6000
|
-
return archivePath;
|
|
6001
|
-
}
|
|
6002
|
-
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
6003
|
-
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
6004
|
-
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
6005
|
-
});
|
|
6006
|
-
}
|
|
6007
|
-
function rotateLog() {
|
|
6008
|
-
const logFile = PATHS.logFile;
|
|
6009
|
-
let stat;
|
|
6010
|
-
try {
|
|
6011
|
-
stat = fs6.statSync(logFile);
|
|
6012
|
-
} catch (e) {
|
|
6013
|
-
if (e.code === "ENOENT") return;
|
|
6014
|
-
throw e;
|
|
6015
|
-
}
|
|
6016
|
-
if (stat.size === 0) return;
|
|
6017
|
-
const rotatedPath = allocateArchivePath();
|
|
6018
|
-
try {
|
|
6019
|
-
fs6.renameSync(logFile, rotatedPath);
|
|
6020
|
-
} catch (e) {
|
|
6021
|
-
try {
|
|
6022
|
-
fs6.unlinkSync(rotatedPath);
|
|
6023
|
-
} catch {
|
|
6024
|
-
}
|
|
6025
|
-
if (e.code === "ENOENT") return;
|
|
6026
|
-
throw e;
|
|
6027
|
-
}
|
|
6028
|
-
}
|
|
6029
|
-
function cleanupOldLogs() {
|
|
6030
|
-
const logsDir = DIRS.logs;
|
|
6031
|
-
if (!fs6.existsSync(logsDir)) return;
|
|
6032
|
-
const files = fs6.readdirSync(logsDir);
|
|
6033
|
-
const now = Date.now();
|
|
6034
|
-
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
6035
|
-
for (const file of files) {
|
|
6036
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
6037
|
-
try {
|
|
6038
|
-
const filePath = path5.join(logsDir, file);
|
|
6039
|
-
const stat = fs6.statSync(filePath);
|
|
6040
|
-
if (now - stat.mtimeMs > maxAgeMs) {
|
|
6041
|
-
fs6.unlinkSync(filePath);
|
|
6042
|
-
}
|
|
6043
|
-
} catch {
|
|
6044
|
-
}
|
|
6045
|
-
}
|
|
6046
|
-
}
|
|
6047
|
-
function listLogs() {
|
|
6048
|
-
const logsDir = DIRS.logs;
|
|
6049
|
-
const result = { current: null, archives: [] };
|
|
6050
|
-
if (fs6.existsSync(PATHS.logFile)) {
|
|
6051
|
-
const stat = fs6.statSync(PATHS.logFile);
|
|
6052
|
-
result.current = {
|
|
6053
|
-
name: "mihomo.log (\u5F53\u524D)",
|
|
6054
|
-
path: PATHS.logFile,
|
|
6055
|
-
size: stat.size,
|
|
6056
|
-
mtime: stat.mtime,
|
|
6057
|
-
isCurrent: true
|
|
6058
|
-
};
|
|
6059
|
-
}
|
|
6060
|
-
if (!fs6.existsSync(logsDir)) return result;
|
|
6061
|
-
const files = fs6.readdirSync(logsDir);
|
|
6062
|
-
for (const file of files) {
|
|
6063
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
6064
|
-
try {
|
|
6065
|
-
const filePath = path5.join(logsDir, file);
|
|
6066
|
-
const stat = fs6.statSync(filePath);
|
|
6067
|
-
result.archives.push({
|
|
6068
|
-
name: file,
|
|
6069
|
-
path: filePath,
|
|
6070
|
-
size: stat.size,
|
|
6071
|
-
mtime: stat.mtime,
|
|
6072
|
-
isCurrent: false
|
|
6073
|
-
});
|
|
6074
|
-
} catch {
|
|
6075
|
-
}
|
|
6076
|
-
}
|
|
6077
|
-
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
6078
|
-
return result;
|
|
6079
|
-
}
|
|
6080
|
-
|
|
6081
6287
|
// src/process-probe.ts
|
|
6082
6288
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
6083
|
-
import
|
|
6289
|
+
import fs8 from "fs";
|
|
6084
6290
|
var PS_TIMEOUT_MS = 5e3;
|
|
6085
6291
|
var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
|
|
6086
6292
|
function probeProcess(pid) {
|
|
@@ -6103,9 +6309,9 @@ function isProbedMihomo(p) {
|
|
|
6103
6309
|
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
6104
6310
|
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
6105
6311
|
function getPid() {
|
|
6106
|
-
if (!
|
|
6312
|
+
if (!fs8.existsSync(PATHS.pidFile)) return null;
|
|
6107
6313
|
try {
|
|
6108
|
-
const pid = parseInt(
|
|
6314
|
+
const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
6109
6315
|
return pid > 0 ? pid : null;
|
|
6110
6316
|
} catch {
|
|
6111
6317
|
return null;
|
|
@@ -6139,9 +6345,9 @@ function parsePidList(stdout) {
|
|
|
6139
6345
|
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
6140
6346
|
}
|
|
6141
6347
|
function isPidFileOwnedByRoot() {
|
|
6142
|
-
if (!
|
|
6348
|
+
if (!fs8.existsSync(PATHS.pidFile)) return false;
|
|
6143
6349
|
try {
|
|
6144
|
-
const stat =
|
|
6350
|
+
const stat = fs8.statSync(PATHS.pidFile);
|
|
6145
6351
|
return stat.uid === 0;
|
|
6146
6352
|
} catch {
|
|
6147
6353
|
return false;
|
|
@@ -6160,15 +6366,15 @@ function getStatus() {
|
|
|
6160
6366
|
}
|
|
6161
6367
|
|
|
6162
6368
|
// src/process-start.ts
|
|
6163
|
-
import
|
|
6369
|
+
import fs14 from "fs";
|
|
6164
6370
|
|
|
6165
6371
|
// src/service.ts
|
|
6166
6372
|
import { spawnSync as spawnSync7 } from "child_process";
|
|
6167
|
-
import
|
|
6373
|
+
import fs13 from "fs";
|
|
6168
6374
|
import path7 from "path";
|
|
6169
6375
|
|
|
6170
6376
|
// src/hot-reload.ts
|
|
6171
|
-
import
|
|
6377
|
+
import fs9 from "fs";
|
|
6172
6378
|
|
|
6173
6379
|
// src/proxy-probe.ts
|
|
6174
6380
|
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
@@ -6213,16 +6419,20 @@ async function probeProxyConnectivity(port) {
|
|
|
6213
6419
|
const code = Number.parseInt(stdout.trim(), 10);
|
|
6214
6420
|
const statusCode = Number.isFinite(code) ? code : null;
|
|
6215
6421
|
const ok = isProbeSuccessStatus(statusCode);
|
|
6422
|
+
const durationMs = Date.now() - start;
|
|
6423
|
+
recordDiagnosticEvent("proxy.probe", ok ? "success" : "failure", { port, httpStatus: statusCode, durationMs });
|
|
6216
6424
|
return {
|
|
6217
6425
|
ok,
|
|
6218
6426
|
statusCode,
|
|
6219
6427
|
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6220
|
-
durationMs
|
|
6428
|
+
durationMs
|
|
6221
6429
|
};
|
|
6222
6430
|
} catch (e) {
|
|
6223
6431
|
const err = e;
|
|
6224
6432
|
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6225
|
-
|
|
6433
|
+
const durationMs = Date.now() - start;
|
|
6434
|
+
recordDiagnosticEvent("proxy.probe", "failure", { port, httpStatus: null, durationMs, ...diagnosticErrorDetails(e) });
|
|
6435
|
+
return { ok: false, statusCode: null, error: detail, durationMs };
|
|
6226
6436
|
}
|
|
6227
6437
|
}
|
|
6228
6438
|
|
|
@@ -6231,51 +6441,65 @@ var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
|
6231
6441
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6232
6442
|
function logOversized() {
|
|
6233
6443
|
try {
|
|
6234
|
-
return
|
|
6444
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6235
6445
|
} catch {
|
|
6236
6446
|
return false;
|
|
6237
6447
|
}
|
|
6238
6448
|
}
|
|
6239
6449
|
async function tryHotReload(prefetched) {
|
|
6240
6450
|
const controller = new AbortController();
|
|
6451
|
+
let stage = "status";
|
|
6241
6452
|
try {
|
|
6242
6453
|
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6243
|
-
if (!status.running || status.pid === null) return false;
|
|
6454
|
+
if (!status.running || status.pid === null) return { ok: false, stage, reason: "service-not-running" };
|
|
6455
|
+
stage = "controller";
|
|
6244
6456
|
const endpoint = getControllerEndpoint();
|
|
6245
|
-
if (endpoint.port === null) return false;
|
|
6457
|
+
if (endpoint.port === null) return { ok: false, stage, reason: "controller-unavailable" };
|
|
6246
6458
|
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6247
6459
|
const headers = { "Content-Type": "application/json" };
|
|
6248
6460
|
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6249
6461
|
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6250
6462
|
try {
|
|
6463
|
+
stage = "version";
|
|
6251
6464
|
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6252
|
-
if (!probe.ok) return false;
|
|
6465
|
+
if (!probe.ok) return { ok: false, stage, reason: "http-status", httpStatus: probe.status };
|
|
6253
6466
|
const info = await probe.json();
|
|
6254
|
-
if (typeof info?.version !== "string") return false;
|
|
6467
|
+
if (typeof info?.version !== "string") return { ok: false, stage, reason: "invalid-response" };
|
|
6468
|
+
stage = "identity";
|
|
6255
6469
|
const listenerPids = lsofListenPids(endpoint.port);
|
|
6256
|
-
if (listenerPids === null
|
|
6470
|
+
if (listenerPids === null) return { ok: false, stage, reason: "listener-unknown" };
|
|
6471
|
+
if (listenerPids[0] !== status.pid) return { ok: false, stage, reason: "owner-mismatch" };
|
|
6472
|
+
stage = "put";
|
|
6257
6473
|
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6258
6474
|
method: "PUT",
|
|
6259
6475
|
headers,
|
|
6260
6476
|
body: "{}",
|
|
6261
6477
|
signal: controller.signal
|
|
6262
6478
|
});
|
|
6263
|
-
return res.
|
|
6479
|
+
if (!res.ok) return { ok: false, stage, reason: "http-status", httpStatus: res.status };
|
|
6480
|
+
return { ok: true };
|
|
6264
6481
|
} finally {
|
|
6265
6482
|
clearTimeout(timer);
|
|
6266
6483
|
}
|
|
6267
|
-
} catch {
|
|
6268
|
-
|
|
6484
|
+
} catch (e) {
|
|
6485
|
+
const aborted = controller.signal.aborted;
|
|
6486
|
+
return {
|
|
6487
|
+
ok: false,
|
|
6488
|
+
stage,
|
|
6489
|
+
reason: aborted ? "timeout" : "exception",
|
|
6490
|
+
errorType: e instanceof Error && e.name === "AbortError" ? "AbortError" : "Error",
|
|
6491
|
+
...aborted ? { aborted: true } : {}
|
|
6492
|
+
};
|
|
6269
6493
|
}
|
|
6270
6494
|
}
|
|
6271
6495
|
|
|
6272
6496
|
// src/process-stop.ts
|
|
6273
6497
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
6274
|
-
import
|
|
6498
|
+
import fs11 from "fs";
|
|
6275
6499
|
|
|
6276
6500
|
// src/sudo.ts
|
|
6277
6501
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6278
|
-
import
|
|
6502
|
+
import fs10 from "fs";
|
|
6279
6503
|
import path6 from "path";
|
|
6280
6504
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
6281
6505
|
var SudoAuthError = class extends Error {
|
|
@@ -6302,8 +6526,8 @@ function runSudoScript(scriptBody, opts) {
|
|
|
6302
6526
|
}
|
|
6303
6527
|
ensureDirs();
|
|
6304
6528
|
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
6305
|
-
|
|
6306
|
-
|
|
6529
|
+
fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
6530
|
+
fs10.chmodSync(scriptPath, 448);
|
|
6307
6531
|
try {
|
|
6308
6532
|
const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
6309
6533
|
if (result.error) {
|
|
@@ -6313,7 +6537,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
6313
6537
|
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
6314
6538
|
} finally {
|
|
6315
6539
|
try {
|
|
6316
|
-
|
|
6540
|
+
fs10.unlinkSync(scriptPath);
|
|
6317
6541
|
} catch {
|
|
6318
6542
|
}
|
|
6319
6543
|
}
|
|
@@ -6324,7 +6548,7 @@ var PROCESS_WAIT_ATTEMPTS = 50;
|
|
|
6324
6548
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
6325
6549
|
var BATCH_KILL_THRESHOLD = 3;
|
|
6326
6550
|
function clearRuntime() {
|
|
6327
|
-
if (
|
|
6551
|
+
if (fs11.existsSync(DIRS.runtime)) {
|
|
6328
6552
|
rmrf(DIRS.runtime);
|
|
6329
6553
|
}
|
|
6330
6554
|
ensureDirs();
|
|
@@ -6336,7 +6560,7 @@ function printResidueWarning(remaining) {
|
|
|
6336
6560
|
}
|
|
6337
6561
|
function clearPid() {
|
|
6338
6562
|
try {
|
|
6339
|
-
|
|
6563
|
+
fs11.unlinkSync(PATHS.pidFile);
|
|
6340
6564
|
return null;
|
|
6341
6565
|
} catch (e) {
|
|
6342
6566
|
if (e.code === "ENOENT") return null;
|
|
@@ -6451,10 +6675,10 @@ async function stop() {
|
|
|
6451
6675
|
}
|
|
6452
6676
|
|
|
6453
6677
|
// src/stop-epoch.ts
|
|
6454
|
-
import
|
|
6678
|
+
import fs12 from "fs";
|
|
6455
6679
|
function readStopEpoch() {
|
|
6456
6680
|
try {
|
|
6457
|
-
const n = Number.parseInt(
|
|
6681
|
+
const n = Number.parseInt(fs12.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
6458
6682
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
6459
6683
|
} catch {
|
|
6460
6684
|
return 0;
|
|
@@ -6567,14 +6791,14 @@ function tunBlockedByConcurrentStart() {
|
|
|
6567
6791
|
function ensureServiceSymlink() {
|
|
6568
6792
|
assertKernelInstalled();
|
|
6569
6793
|
try {
|
|
6570
|
-
const current =
|
|
6794
|
+
const current = fs13.readlinkSync(PATHS.serviceBinary);
|
|
6571
6795
|
if (current === "mihomo") return;
|
|
6572
|
-
|
|
6796
|
+
fs13.unlinkSync(PATHS.serviceBinary);
|
|
6573
6797
|
} catch (e) {
|
|
6574
6798
|
const code = e.code;
|
|
6575
6799
|
if (code === "EINVAL") {
|
|
6576
6800
|
try {
|
|
6577
|
-
|
|
6801
|
+
fs13.unlinkSync(PATHS.serviceBinary);
|
|
6578
6802
|
} catch {
|
|
6579
6803
|
}
|
|
6580
6804
|
} else if (code !== "ENOENT") {
|
|
@@ -6582,12 +6806,12 @@ function ensureServiceSymlink() {
|
|
|
6582
6806
|
}
|
|
6583
6807
|
}
|
|
6584
6808
|
try {
|
|
6585
|
-
|
|
6809
|
+
fs13.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
6586
6810
|
} catch (e) {
|
|
6587
6811
|
if (e.code !== "EEXIST") throw e;
|
|
6588
6812
|
let existing;
|
|
6589
6813
|
try {
|
|
6590
|
-
existing =
|
|
6814
|
+
existing = fs13.readlinkSync(PATHS.serviceBinary);
|
|
6591
6815
|
} catch {
|
|
6592
6816
|
throw e;
|
|
6593
6817
|
}
|
|
@@ -6627,8 +6851,8 @@ async function installService(wasRunning) {
|
|
|
6627
6851
|
}
|
|
6628
6852
|
bootoutService();
|
|
6629
6853
|
await waitUntilUnloaded();
|
|
6630
|
-
|
|
6631
|
-
atomicWriteFileSync(PATHS.userAgentPlist,
|
|
6854
|
+
fs13.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
6855
|
+
atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
6632
6856
|
if (wasRunning) {
|
|
6633
6857
|
withFileLock(PATHS.serviceLock, () => {
|
|
6634
6858
|
if (startAbortedByConcurrentStop()) {
|
|
@@ -6641,7 +6865,7 @@ async function installService(wasRunning) {
|
|
|
6641
6865
|
}
|
|
6642
6866
|
} finally {
|
|
6643
6867
|
try {
|
|
6644
|
-
|
|
6868
|
+
fs13.unlinkSync(stagePath);
|
|
6645
6869
|
} catch {
|
|
6646
6870
|
}
|
|
6647
6871
|
}
|
|
@@ -6713,13 +6937,13 @@ async function uninstallService() {
|
|
|
6713
6937
|
assertServiceLabelSafe();
|
|
6714
6938
|
await bootoutAndDisableInLock();
|
|
6715
6939
|
try {
|
|
6716
|
-
|
|
6940
|
+
fs13.rmSync(PATHS.userAgentPlist, { force: true });
|
|
6717
6941
|
} catch (e) {
|
|
6718
6942
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
6719
6943
|
}
|
|
6720
6944
|
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6721
6945
|
try {
|
|
6722
|
-
|
|
6946
|
+
fs13.rmSync(PATHS.serviceBinary, { force: true });
|
|
6723
6947
|
} catch {
|
|
6724
6948
|
}
|
|
6725
6949
|
return cleanup;
|
|
@@ -6730,31 +6954,52 @@ async function restartService(prefetched) {
|
|
|
6730
6954
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
6731
6955
|
}
|
|
6732
6956
|
const oversized = logOversized();
|
|
6733
|
-
|
|
6957
|
+
const hotReload = oversized ? null : await tryHotReload(prefetched);
|
|
6958
|
+
if (hotReload?.ok) {
|
|
6959
|
+
recordDiagnosticEvent("service.hot-reload", "success", { stage: "put" });
|
|
6734
6960
|
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6735
6961
|
}
|
|
6962
|
+
recordDiagnosticEvent("service.hot-reload", "fallback", {
|
|
6963
|
+
stage: hotReload?.stage ?? "log-rotation",
|
|
6964
|
+
reason: hotReload?.reason ?? "log-oversized",
|
|
6965
|
+
httpStatus: hotReload?.httpStatus,
|
|
6966
|
+
errorType: hotReload?.errorType,
|
|
6967
|
+
aborted: hotReload?.aborted
|
|
6968
|
+
});
|
|
6736
6969
|
if (oversized) {
|
|
6737
6970
|
const archiveFile = allocateArchivePath();
|
|
6738
6971
|
try {
|
|
6739
|
-
|
|
6740
|
-
|
|
6972
|
+
fs13.copyFileSync(PATHS.logFile, archiveFile);
|
|
6973
|
+
fs13.writeFileSync(PATHS.logFile, "");
|
|
6741
6974
|
} catch {
|
|
6742
6975
|
}
|
|
6743
6976
|
}
|
|
6744
6977
|
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
6978
|
+
recordDiagnosticEvent("service.kickstart", kick.status === 0 ? "success" : "failure", { exitCode: kick.status });
|
|
6745
6979
|
if (kick.status !== 0) {
|
|
6746
|
-
|
|
6747
|
-
|
|
6748
|
-
|
|
6749
|
-
|
|
6750
|
-
|
|
6751
|
-
|
|
6980
|
+
let bootstrapped;
|
|
6981
|
+
try {
|
|
6982
|
+
bootstrapped = withFileLock(PATHS.serviceLock, () => {
|
|
6983
|
+
if (startAbortedByConcurrentStop()) return null;
|
|
6984
|
+
runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6985
|
+
return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
|
|
6986
|
+
});
|
|
6987
|
+
} catch (e) {
|
|
6988
|
+
recordDiagnosticEvent("service.bootstrap", "failure", diagnosticErrorDetails(e));
|
|
6989
|
+
throw e;
|
|
6990
|
+
}
|
|
6991
|
+
if (bootstrapped === null) {
|
|
6992
|
+
recordDiagnosticEvent("service.bootstrap", "cancelled", { reason: "concurrent-stop" });
|
|
6993
|
+
return { hotReloaded: false, started: false };
|
|
6994
|
+
}
|
|
6752
6995
|
if (!bootstrapped) {
|
|
6996
|
+
recordDiagnosticEvent("service.bootstrap", "failure", { reason: "replacement-not-bootstrapped", exitCode: kick.status });
|
|
6753
6997
|
const detail = kick.stderr.trim();
|
|
6754
6998
|
throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
|
|
6755
6999
|
hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
6756
7000
|
});
|
|
6757
7001
|
}
|
|
7002
|
+
recordDiagnosticEvent("service.bootstrap", "success");
|
|
6758
7003
|
}
|
|
6759
7004
|
cleanupOldLogs();
|
|
6760
7005
|
return { hotReloaded: false, started: true };
|
|
@@ -6835,12 +7080,12 @@ async function startTun(prefetched) {
|
|
|
6835
7080
|
}
|
|
6836
7081
|
rotateAndCleanupLogs();
|
|
6837
7082
|
const logFile = PATHS.logFile;
|
|
6838
|
-
if (
|
|
7083
|
+
if (fs14.existsSync(logFile)) {
|
|
6839
7084
|
try {
|
|
6840
|
-
|
|
7085
|
+
fs14.accessSync(logFile, fs14.constants.W_OK);
|
|
6841
7086
|
} catch {
|
|
6842
7087
|
try {
|
|
6843
|
-
|
|
7088
|
+
fs14.unlinkSync(logFile);
|
|
6844
7089
|
} catch {
|
|
6845
7090
|
}
|
|
6846
7091
|
}
|
|
@@ -6892,6 +7137,17 @@ function restartModeOnChange() {
|
|
|
6892
7137
|
return state.running ? restartModeFor(state, getRuntimeMode()) : null;
|
|
6893
7138
|
}
|
|
6894
7139
|
async function launchOrRestart(mode) {
|
|
7140
|
+
const startedAt = Date.now();
|
|
7141
|
+
try {
|
|
7142
|
+
const pid = await launchOrRestartImpl(mode);
|
|
7143
|
+
recordDiagnosticEvent("runtime.launch", "success", { mode, kernelPid: pid, durationMs: Date.now() - startedAt });
|
|
7144
|
+
return pid;
|
|
7145
|
+
} catch (e) {
|
|
7146
|
+
recordDiagnosticEvent("runtime.launch", "failure", { mode, durationMs: Date.now() - startedAt, ...diagnosticErrorDetails(e) });
|
|
7147
|
+
throw e;
|
|
7148
|
+
}
|
|
7149
|
+
}
|
|
7150
|
+
async function launchOrRestartImpl(mode) {
|
|
6895
7151
|
if (mode === "tun") {
|
|
6896
7152
|
const prefetched = assertTunStartNotRaced();
|
|
6897
7153
|
let pid;
|
|
@@ -6961,7 +7217,15 @@ function startCommandForCurrentMode(state) {
|
|
|
6961
7217
|
return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
|
|
6962
7218
|
}
|
|
6963
7219
|
async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
7220
|
+
const startedAt = Date.now();
|
|
6964
7221
|
const health = await waitServiceHealthy();
|
|
7222
|
+
recordDiagnosticEvent("service.health", health.healthy ? "success" : "failure", {
|
|
7223
|
+
reason: health.healthy ? void 0 : health.crashed ? "crashed" : "not-running",
|
|
7224
|
+
kernelPid: health.pid,
|
|
7225
|
+
lastExitCode: health.exitCode,
|
|
7226
|
+
lastTerminatingSignal: health.terminatingSignal,
|
|
7227
|
+
durationMs: Date.now() - startedAt
|
|
7228
|
+
});
|
|
6965
7229
|
if (health.healthy) return health.pid;
|
|
6966
7230
|
const tail = readLogTail();
|
|
6967
7231
|
const cause = describeExitCause(health.exitCode, health.terminatingSignal);
|
|
@@ -7330,6 +7594,7 @@ async function cmdStart(args) {
|
|
|
7330
7594
|
const targetMode = resolveStartMode(args);
|
|
7331
7595
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
7332
7596
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
7597
|
+
recordDiagnosticEvent("start", "begin", { mode: targetMode, updateRequested: !skipUpdate, timeoutMs: updateTimeout });
|
|
7333
7598
|
let disabledAutoStartForTun = false;
|
|
7334
7599
|
assertKernelInstalled();
|
|
7335
7600
|
const serviceBefore = getServiceStatus();
|
|
@@ -7514,11 +7779,11 @@ async function cmdDirectory(args) {
|
|
|
7514
7779
|
}
|
|
7515
7780
|
|
|
7516
7781
|
// src/commands/doctor.ts
|
|
7517
|
-
import
|
|
7782
|
+
import fs16 from "fs";
|
|
7518
7783
|
|
|
7519
7784
|
// src/kernel.ts
|
|
7520
7785
|
import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync9 } from "child_process";
|
|
7521
|
-
import
|
|
7786
|
+
import fs15 from "fs";
|
|
7522
7787
|
import path8 from "path";
|
|
7523
7788
|
import { promisify as promisify3 } from "util";
|
|
7524
7789
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7866,7 +8131,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7866
8131
|
if (mirrorIneffective) {
|
|
7867
8132
|
console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
|
|
7868
8133
|
}
|
|
7869
|
-
const tempDir =
|
|
8134
|
+
const tempDir = fs15.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
7870
8135
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
7871
8136
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7872
8137
|
try {
|
|
@@ -7920,11 +8185,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7920
8185
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
|
|
7921
8186
|
}
|
|
7922
8187
|
}
|
|
7923
|
-
if (!
|
|
8188
|
+
if (!fs15.existsSync(tempPath)) {
|
|
7924
8189
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7925
8190
|
}
|
|
7926
8191
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7927
|
-
const actual =
|
|
8192
|
+
const actual = fs15.statSync(tempPath).size;
|
|
7928
8193
|
if (actual !== asset.size) {
|
|
7929
8194
|
throw new Error(
|
|
7930
8195
|
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
@@ -7937,11 +8202,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7937
8202
|
}
|
|
7938
8203
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
7939
8204
|
const gzipStdout = await decompressGzip(tempPath);
|
|
7940
|
-
|
|
8205
|
+
fs15.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
|
|
7941
8206
|
if (progressCallback) {
|
|
7942
8207
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7943
8208
|
}
|
|
7944
|
-
|
|
8209
|
+
fs15.chmodSync(foundBinary, 493);
|
|
7945
8210
|
const probe = probeKernelVersion(foundBinary);
|
|
7946
8211
|
if (probe.spawnError || probe.status !== 0 || probe.version === null) {
|
|
7947
8212
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
|
|
@@ -7954,11 +8219,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
7954
8219
|
throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
|
|
7955
8220
|
}
|
|
7956
8221
|
const targetPath = PATHS.mihomoBinary;
|
|
7957
|
-
|
|
8222
|
+
fs15.renameSync(foundBinary, targetPath);
|
|
7958
8223
|
return { version: latest.tag_name };
|
|
7959
8224
|
} finally {
|
|
7960
8225
|
try {
|
|
7961
|
-
|
|
8226
|
+
fs15.rmSync(tempDir, { recursive: true, force: true });
|
|
7962
8227
|
} catch {
|
|
7963
8228
|
}
|
|
7964
8229
|
}
|
|
@@ -8120,20 +8385,20 @@ async function collectChecks() {
|
|
|
8120
8385
|
} else {
|
|
8121
8386
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
8122
8387
|
}
|
|
8123
|
-
if (
|
|
8388
|
+
if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
|
|
8124
8389
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
|
|
8125
8390
|
}
|
|
8126
|
-
if (
|
|
8391
|
+
if (fs16.existsSync(KERNEL_SELF_BACKUP_DIR)) {
|
|
8127
8392
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
|
|
8128
8393
|
}
|
|
8129
8394
|
try {
|
|
8130
|
-
|
|
8395
|
+
fs16.accessSync(USER_DATA_DIR, fs16.constants.W_OK);
|
|
8131
8396
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
8132
8397
|
} catch {
|
|
8133
8398
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
8134
8399
|
}
|
|
8135
|
-
if (
|
|
8136
|
-
if (isValidSettingsContent(
|
|
8400
|
+
if (fs16.existsSync(PATHS.settingsFile)) {
|
|
8401
|
+
if (isValidSettingsContent(fs16.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
8137
8402
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
8138
8403
|
} else {
|
|
8139
8404
|
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
@@ -8208,7 +8473,7 @@ async function collectChecks() {
|
|
|
8208
8473
|
if (active && hasKernel()) {
|
|
8209
8474
|
try {
|
|
8210
8475
|
const mode = deriveRuntimeMode(info);
|
|
8211
|
-
const prepared = await prepareConfigForStart(mode, active.name);
|
|
8476
|
+
const prepared = await prepareConfigForStart(mode, active.name, "doctor");
|
|
8212
8477
|
const warnings = prepared.buildResult.warnings;
|
|
8213
8478
|
if (warnings.length > 0) {
|
|
8214
8479
|
push(
|
|
@@ -8590,22 +8855,35 @@ async function cmdKernel(args) {
|
|
|
8590
8855
|
}
|
|
8591
8856
|
|
|
8592
8857
|
// src/commands/log.ts
|
|
8858
|
+
import fs17 from "fs";
|
|
8593
8859
|
var INVALID_INDEX_HINT = "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs";
|
|
8594
8860
|
function cmdLogs(args) {
|
|
8595
|
-
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8596
|
-
assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8861
|
+
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open", "--diagnostic"], "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8862
|
+
assertPositionalCount(args, 1, 1, "mihomo-cli logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8597
8863
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
8598
8864
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
8599
8865
|
const follow = hasFlag(args, "-f", "--follow");
|
|
8600
8866
|
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
8601
8867
|
const positional = getNonFlagArg(args, 1);
|
|
8868
|
+
const diagnostic = hasFlag(args, "--diagnostic");
|
|
8869
|
+
if (diagnostic && positional !== null) {
|
|
8870
|
+
throw new CliError("--diagnostic \u4E0E\u5185\u6838\u65E5\u5FD7\u7F16\u53F7\u4E92\u65A5", {
|
|
8871
|
+
hint: ["\u67E5\u770B\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic", "\u67E5\u770B\u5185\u6838\u65E5\u5FD7: mihomo-cli logs <\u7F16\u53F7>"]
|
|
8872
|
+
});
|
|
8873
|
+
}
|
|
8602
8874
|
if (positional === "") {
|
|
8603
8875
|
throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: INVALID_INDEX_HINT });
|
|
8604
8876
|
}
|
|
8605
|
-
|
|
8877
|
+
if (diagnostic && !fs17.existsSync(PATHS.diagnosticEventsFile)) {
|
|
8878
|
+
console.log("\u6682\u65E0\u8BCA\u65AD\u4E8B\u4EF6");
|
|
8879
|
+
return;
|
|
8880
|
+
}
|
|
8881
|
+
const targetName = diagnostic ? "0" : positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
8606
8882
|
if (targetName) {
|
|
8607
8883
|
let logPath;
|
|
8608
|
-
if (
|
|
8884
|
+
if (diagnostic) {
|
|
8885
|
+
logPath = PATHS.diagnosticEventsFile;
|
|
8886
|
+
} else if (targetName === "0") {
|
|
8609
8887
|
logPath = PATHS.logFile;
|
|
8610
8888
|
} else {
|
|
8611
8889
|
const parsedIdx = parseInt(targetName, 10);
|
|
@@ -8621,7 +8899,7 @@ function cmdLogs(args) {
|
|
|
8621
8899
|
if (openInViewer) {
|
|
8622
8900
|
if (follow) {
|
|
8623
8901
|
throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
|
|
8624
|
-
hint:
|
|
8902
|
+
hint: `\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs ${diagnostic ? "--diagnostic" : "0"} -f`
|
|
8625
8903
|
});
|
|
8626
8904
|
}
|
|
8627
8905
|
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
|
|
@@ -8636,7 +8914,8 @@ function cmdLogs(args) {
|
|
|
8636
8914
|
if (logs.current) all.push(logs.current);
|
|
8637
8915
|
all.push(...logs.archives);
|
|
8638
8916
|
if (all.length === 0) {
|
|
8639
|
-
console.log("\u6682\u65E0\u65E5\u5FD7");
|
|
8917
|
+
console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
|
|
8918
|
+
console.log("\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic");
|
|
8640
8919
|
return;
|
|
8641
8920
|
}
|
|
8642
8921
|
console.log("");
|
|
@@ -8664,6 +8943,7 @@ function cmdLogs(args) {
|
|
|
8664
8943
|
console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
|
|
8665
8944
|
console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
|
|
8666
8945
|
console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
|
|
8946
|
+
console.log(" mihomo-cli logs --diagnostic # \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6 (JSONL)");
|
|
8667
8947
|
console.log("");
|
|
8668
8948
|
}
|
|
8669
8949
|
|
|
@@ -8754,7 +9034,7 @@ async function cmdOverwrite(args) {
|
|
|
8754
9034
|
}
|
|
8755
9035
|
|
|
8756
9036
|
// src/commands/reset.ts
|
|
8757
|
-
import
|
|
9037
|
+
import fs18 from "fs";
|
|
8758
9038
|
var RESET_TARGETS = [
|
|
8759
9039
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
8760
9040
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -8766,7 +9046,7 @@ var RESET_TARGETS = [
|
|
|
8766
9046
|
label: "\u8986\u5199",
|
|
8767
9047
|
needsStop: false,
|
|
8768
9048
|
preserveOnBare: true,
|
|
8769
|
-
paths: () =>
|
|
9049
|
+
paths: () => fs18.existsSync(USER_DATA_DIR) ? fs18.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
8770
9050
|
},
|
|
8771
9051
|
{
|
|
8772
9052
|
// 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
|
|
@@ -8866,7 +9146,7 @@ async function cmdReset(args) {
|
|
|
8866
9146
|
for (const target of targets) {
|
|
8867
9147
|
let hadContent = target.id === "service" && serviceActive;
|
|
8868
9148
|
for (const filePath of target.paths()) {
|
|
8869
|
-
if (!
|
|
9149
|
+
if (!fs18.existsSync(filePath)) continue;
|
|
8870
9150
|
try {
|
|
8871
9151
|
rmrf(filePath);
|
|
8872
9152
|
} catch (e) {
|
|
@@ -8904,7 +9184,7 @@ async function cmdReset(args) {
|
|
|
8904
9184
|
}
|
|
8905
9185
|
|
|
8906
9186
|
// src/commands/service.ts
|
|
8907
|
-
import
|
|
9187
|
+
import fs19 from "fs";
|
|
8908
9188
|
function printRestoreSkipped() {
|
|
8909
9189
|
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
8910
9190
|
console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
|
|
@@ -8941,7 +9221,7 @@ async function cmdInstall(args) {
|
|
|
8941
9221
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
8942
9222
|
} else {
|
|
8943
9223
|
console.log("\u542F\u52A8: mihomo-cli start");
|
|
8944
|
-
if (!
|
|
9224
|
+
if (!fs19.existsSync(PATHS.configFile)) {
|
|
8945
9225
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
8946
9226
|
}
|
|
8947
9227
|
}
|
|
@@ -9073,6 +9353,7 @@ function readUrlFromClipboard() {
|
|
|
9073
9353
|
}
|
|
9074
9354
|
}
|
|
9075
9355
|
async function subAdd(args) {
|
|
9356
|
+
setDiagnosticCommand("sub add");
|
|
9076
9357
|
assertPositionalCount(args, 2, 2, "mihomo-cli sub add <url> [name]");
|
|
9077
9358
|
let url = args[2]?.trim();
|
|
9078
9359
|
const name = args[3] === void 0 ? "default" : args[3];
|
|
@@ -9116,6 +9397,7 @@ async function subAdd(args) {
|
|
|
9116
9397
|
printSubscriptionList();
|
|
9117
9398
|
}
|
|
9118
9399
|
async function subUpdate(args) {
|
|
9400
|
+
setDiagnosticCommand("sub update");
|
|
9119
9401
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub update [name]");
|
|
9120
9402
|
const nameArg = getNonFlagArg(args, 2);
|
|
9121
9403
|
const subs = getSubscriptions();
|
|
@@ -9160,6 +9442,7 @@ async function subUpdate(args) {
|
|
|
9160
9442
|
printSubscriptionList();
|
|
9161
9443
|
}
|
|
9162
9444
|
async function subUse(args) {
|
|
9445
|
+
setDiagnosticCommand("sub use");
|
|
9163
9446
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub use <name>");
|
|
9164
9447
|
assertRestartOptionValues(args);
|
|
9165
9448
|
const name = getNonFlagArg(args, 2);
|
|
@@ -9191,6 +9474,7 @@ async function subUse(args) {
|
|
|
9191
9474
|
printSubscriptionList();
|
|
9192
9475
|
}
|
|
9193
9476
|
async function subRemove(args) {
|
|
9477
|
+
setDiagnosticCommand("sub remove");
|
|
9194
9478
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub remove <name>");
|
|
9195
9479
|
const name = getNonFlagArg(args, 2);
|
|
9196
9480
|
const subs = getSubscriptions();
|
|
@@ -9358,7 +9642,12 @@ var COMMANDS = [
|
|
|
9358
9642
|
aliases: [],
|
|
9359
9643
|
handler: cmdLogs,
|
|
9360
9644
|
group: "interface",
|
|
9361
|
-
usage: [
|
|
9645
|
+
usage: [
|
|
9646
|
+
{
|
|
9647
|
+
signature: "logs [--diagnostic] [-f] [-n N] [\u7F16\u53F7] [-o]",
|
|
9648
|
+
description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7\uFF1B--diagnostic \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6"
|
|
9649
|
+
}
|
|
9650
|
+
]
|
|
9362
9651
|
},
|
|
9363
9652
|
// === 订阅 ===
|
|
9364
9653
|
{
|
|
@@ -9505,7 +9794,7 @@ process.on("unhandledRejection", (reason) => {
|
|
|
9505
9794
|
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
9506
9795
|
function readSelfMixedPortEarly() {
|
|
9507
9796
|
try {
|
|
9508
|
-
const raw = JSON.parse(
|
|
9797
|
+
const raw = JSON.parse(fs20.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9509
9798
|
const mixed = raw?.ports?.mixed;
|
|
9510
9799
|
if (isValidPortNumber(mixed)) return mixed;
|
|
9511
9800
|
} catch {
|
|
@@ -9574,6 +9863,7 @@ async function main() {
|
|
|
9574
9863
|
assertNotRoot("status");
|
|
9575
9864
|
ensureDirs();
|
|
9576
9865
|
cleanupStaleTmpFiles();
|
|
9866
|
+
beginDiagnosticOperation("status");
|
|
9577
9867
|
await printStatus();
|
|
9578
9868
|
printShortHelp();
|
|
9579
9869
|
return;
|
|
@@ -9593,6 +9883,7 @@ async function main() {
|
|
|
9593
9883
|
ensureDirs();
|
|
9594
9884
|
cleanupStaleTmpFiles();
|
|
9595
9885
|
captureStopEpochBaseline();
|
|
9886
|
+
beginDiagnosticOperation(command.name);
|
|
9596
9887
|
}
|
|
9597
9888
|
if (command.group === "meta") {
|
|
9598
9889
|
assertKnownFlags(args.slice(1), [], command.name);
|