mihomo-cli 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/README.md +107 -32
- package/dist/index.js +1005 -801
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ var colors = {
|
|
|
19
19
|
import { spawnSync } from "child_process";
|
|
20
20
|
import fs4 from "fs";
|
|
21
21
|
|
|
22
|
-
//
|
|
22
|
+
// node_modules/js-yaml/dist/js-yaml.mjs
|
|
23
23
|
var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
|
|
24
24
|
function defineScalarTag(tagName, options) {
|
|
25
25
|
return {
|
|
@@ -1088,11 +1088,11 @@ function foldedBreaks(count) {
|
|
|
1088
1088
|
if (count === 1) return " ";
|
|
1089
1089
|
return "\n".repeat(count - 1);
|
|
1090
1090
|
}
|
|
1091
|
-
function getPlainValue(input,
|
|
1091
|
+
function getPlainValue(input, start, end) {
|
|
1092
1092
|
let result = "";
|
|
1093
|
-
let position =
|
|
1094
|
-
let captureStart =
|
|
1095
|
-
let captureEnd =
|
|
1093
|
+
let position = start;
|
|
1094
|
+
let captureStart = start;
|
|
1095
|
+
let captureEnd = start;
|
|
1096
1096
|
while (position < end) {
|
|
1097
1097
|
const ch = input.charCodeAt(position);
|
|
1098
1098
|
if (ch === 10 || ch === 13) {
|
|
@@ -1107,11 +1107,11 @@ function getPlainValue(input, start2, end) {
|
|
|
1107
1107
|
}
|
|
1108
1108
|
return result + input.slice(captureStart, captureEnd);
|
|
1109
1109
|
}
|
|
1110
|
-
function getSingleQuotedValue(input,
|
|
1110
|
+
function getSingleQuotedValue(input, start, end) {
|
|
1111
1111
|
let result = "";
|
|
1112
|
-
let position =
|
|
1113
|
-
let captureStart =
|
|
1114
|
-
let captureEnd =
|
|
1112
|
+
let position = start;
|
|
1113
|
+
let captureStart = start;
|
|
1114
|
+
let captureEnd = start;
|
|
1115
1115
|
while (position < end) {
|
|
1116
1116
|
const ch = input.charCodeAt(position);
|
|
1117
1117
|
if (ch === 39) {
|
|
@@ -1130,11 +1130,11 @@ function getSingleQuotedValue(input, start2, end) {
|
|
|
1130
1130
|
}
|
|
1131
1131
|
return result + input.slice(captureStart, end);
|
|
1132
1132
|
}
|
|
1133
|
-
function getDoubleQuotedValue(input,
|
|
1133
|
+
function getDoubleQuotedValue(input, start, end) {
|
|
1134
1134
|
let result = "";
|
|
1135
|
-
let position =
|
|
1136
|
-
let captureStart =
|
|
1137
|
-
let captureEnd =
|
|
1135
|
+
let position = start;
|
|
1136
|
+
let captureStart = start;
|
|
1137
|
+
let captureEnd = start;
|
|
1138
1138
|
while (position < end) {
|
|
1139
1139
|
const ch = input.charCodeAt(position);
|
|
1140
1140
|
if (ch === 92) {
|
|
@@ -1169,9 +1169,9 @@ function getDoubleQuotedValue(input, start2, end) {
|
|
|
1169
1169
|
}
|
|
1170
1170
|
return result + input.slice(captureStart, end);
|
|
1171
1171
|
}
|
|
1172
|
-
function getBlockValue(input,
|
|
1172
|
+
function getBlockValue(input, start, end, indent, chomping, folded) {
|
|
1173
1173
|
const textIndent = indent < 0 ? 0 : indent;
|
|
1174
|
-
const region = input.slice(
|
|
1174
|
+
const region = input.slice(start, end).replace(/\r\n?/g, "\n");
|
|
1175
1175
|
const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n");
|
|
1176
1176
|
let result = "";
|
|
1177
1177
|
let didReadContent = false;
|
|
@@ -1509,10 +1509,10 @@ function addDocumentEvent(state, explicitStart, explicitEnd) {
|
|
|
1509
1509
|
directives: state.directives
|
|
1510
1510
|
});
|
|
1511
1511
|
}
|
|
1512
|
-
function addSequenceEvent(state,
|
|
1512
|
+
function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
|
|
1513
1513
|
state.events.push({
|
|
1514
1514
|
type: EVENT_ID.SEQUENCE,
|
|
1515
|
-
start
|
|
1515
|
+
start,
|
|
1516
1516
|
anchorStart,
|
|
1517
1517
|
anchorEnd,
|
|
1518
1518
|
tagStart,
|
|
@@ -1520,10 +1520,10 @@ function addSequenceEvent(state, start2, anchorStart, anchorEnd, tagStart, tagEn
|
|
|
1520
1520
|
style
|
|
1521
1521
|
});
|
|
1522
1522
|
}
|
|
1523
|
-
function addMappingEvent(state,
|
|
1523
|
+
function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
|
|
1524
1524
|
state.events.push({
|
|
1525
1525
|
type: EVENT_ID.MAPPING,
|
|
1526
|
-
start
|
|
1526
|
+
start,
|
|
1527
1527
|
anchorStart,
|
|
1528
1528
|
anchorEnd,
|
|
1529
1529
|
tagStart,
|
|
@@ -1680,13 +1680,13 @@ function skipUntilLineEnd(state) {
|
|
|
1680
1680
|
let ch = state.input.charCodeAt(state.position);
|
|
1681
1681
|
while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
|
|
1682
1682
|
}
|
|
1683
|
-
function checkPrintable(state,
|
|
1684
|
-
if (PATTERN_NON_PRINTABLE.test(state.input.slice(
|
|
1683
|
+
function checkPrintable(state, start, end) {
|
|
1684
|
+
if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters");
|
|
1685
1685
|
}
|
|
1686
1686
|
function readTagProperty(state, props, inFlow) {
|
|
1687
1687
|
if (state.input.charCodeAt(state.position) !== 33) return false;
|
|
1688
1688
|
if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property");
|
|
1689
|
-
const
|
|
1689
|
+
const start = state.position;
|
|
1690
1690
|
let isVerbatim = false;
|
|
1691
1691
|
let isNamed = false;
|
|
1692
1692
|
let tagHandle = "!";
|
|
@@ -1721,7 +1721,7 @@ function readTagProperty(state, props, inFlow) {
|
|
|
1721
1721
|
}
|
|
1722
1722
|
if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`);
|
|
1723
1723
|
if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`);
|
|
1724
|
-
props.tagStart =
|
|
1724
|
+
props.tagStart = start;
|
|
1725
1725
|
props.tagEnd = state.position;
|
|
1726
1726
|
return true;
|
|
1727
1727
|
}
|
|
@@ -1729,10 +1729,10 @@ function readAnchorProperty(state, props) {
|
|
|
1729
1729
|
if (state.input.charCodeAt(state.position) !== 38) return false;
|
|
1730
1730
|
if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property");
|
|
1731
1731
|
state.position++;
|
|
1732
|
-
const
|
|
1732
|
+
const start = state.position;
|
|
1733
1733
|
while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
|
|
1734
|
-
if (state.position ===
|
|
1735
|
-
props.anchorStart =
|
|
1734
|
+
if (state.position === start) throwError(state, "name of an anchor node must contain at least one character");
|
|
1735
|
+
props.anchorStart = start;
|
|
1736
1736
|
props.anchorEnd = state.position;
|
|
1737
1737
|
return true;
|
|
1738
1738
|
}
|
|
@@ -1740,10 +1740,10 @@ function readAlias(state, props) {
|
|
|
1740
1740
|
if (state.input.charCodeAt(state.position) !== 42) return false;
|
|
1741
1741
|
if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties");
|
|
1742
1742
|
state.position++;
|
|
1743
|
-
const
|
|
1743
|
+
const start = state.position;
|
|
1744
1744
|
while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
|
|
1745
|
-
if (state.position ===
|
|
1746
|
-
addAliasEvent(state,
|
|
1745
|
+
if (state.position === start) throwError(state, "name of an alias node must contain at least one character");
|
|
1746
|
+
addAliasEvent(state, start, state.position);
|
|
1747
1747
|
return true;
|
|
1748
1748
|
}
|
|
1749
1749
|
function readFlowScalarBreak(state, nodeIndent) {
|
|
@@ -1753,7 +1753,7 @@ function readFlowScalarBreak(state, nodeIndent) {
|
|
|
1753
1753
|
function readSingleQuotedScalar(state, nodeIndent, props) {
|
|
1754
1754
|
if (state.input.charCodeAt(state.position) !== 39) return false;
|
|
1755
1755
|
state.position++;
|
|
1756
|
-
const
|
|
1756
|
+
const start = state.position;
|
|
1757
1757
|
let simple = true;
|
|
1758
1758
|
while (state.input.charCodeAt(state.position) !== 0) {
|
|
1759
1759
|
const ch = state.input.charCodeAt(state.position);
|
|
@@ -1765,7 +1765,7 @@ function readSingleQuotedScalar(state, nodeIndent, props) {
|
|
|
1765
1765
|
}
|
|
1766
1766
|
const end = state.position;
|
|
1767
1767
|
state.position++;
|
|
1768
|
-
addScalarEvent(state,
|
|
1768
|
+
addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
|
|
1769
1769
|
return true;
|
|
1770
1770
|
}
|
|
1771
1771
|
if (isEol(ch)) {
|
|
@@ -1780,14 +1780,14 @@ function readSingleQuotedScalar(state, nodeIndent, props) {
|
|
|
1780
1780
|
function readDoubleQuotedScalar(state, nodeIndent, props) {
|
|
1781
1781
|
if (state.input.charCodeAt(state.position) !== 34) return false;
|
|
1782
1782
|
state.position++;
|
|
1783
|
-
const
|
|
1783
|
+
const start = state.position;
|
|
1784
1784
|
let simple = true;
|
|
1785
1785
|
while (state.input.charCodeAt(state.position) !== 0) {
|
|
1786
1786
|
const ch = state.input.charCodeAt(state.position);
|
|
1787
1787
|
if (ch === 34) {
|
|
1788
1788
|
const end = state.position;
|
|
1789
1789
|
state.position++;
|
|
1790
|
-
addScalarEvent(state,
|
|
1790
|
+
addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
|
|
1791
1791
|
return true;
|
|
1792
1792
|
}
|
|
1793
1793
|
if (ch === 92) {
|
|
@@ -1906,7 +1906,7 @@ function canStartPlainScalar(state, nodeContext) {
|
|
|
1906
1906
|
}
|
|
1907
1907
|
function readPlainScalar(state, nodeIndent, nodeContext, props) {
|
|
1908
1908
|
if (!canStartPlainScalar(state, nodeContext)) return false;
|
|
1909
|
-
const
|
|
1909
|
+
const start = state.position;
|
|
1910
1910
|
let end = state.position;
|
|
1911
1911
|
let ch = state.input.charCodeAt(state.position);
|
|
1912
1912
|
const inFlow = nodeContext === CONTEXT_FLOW_IN;
|
|
@@ -1939,9 +1939,9 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
|
|
|
1939
1939
|
if (!isWhiteSpace(ch)) end = state.position + 1;
|
|
1940
1940
|
ch = state.input.charCodeAt(++state.position);
|
|
1941
1941
|
}
|
|
1942
|
-
if (end ===
|
|
1943
|
-
checkPrintable(state,
|
|
1944
|
-
addScalarEvent(state,
|
|
1942
|
+
if (end === start) return false;
|
|
1943
|
+
checkPrintable(state, start, end);
|
|
1944
|
+
addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
|
|
1945
1945
|
return true;
|
|
1946
1946
|
}
|
|
1947
1947
|
function skipFlowSeparationSpace(state, nodeIndent) {
|
|
@@ -1952,12 +1952,12 @@ function skipFlowSeparationSpace(state, nodeIndent) {
|
|
|
1952
1952
|
function readFlowCollection(state, nodeIndent, props) {
|
|
1953
1953
|
const ch = state.input.charCodeAt(state.position);
|
|
1954
1954
|
const isMapping = ch === 123;
|
|
1955
|
-
const
|
|
1955
|
+
const start = state.position;
|
|
1956
1956
|
let readNext = true;
|
|
1957
1957
|
if (ch !== 91 && ch !== 123) return false;
|
|
1958
1958
|
const terminator = isMapping ? 125 : 93;
|
|
1959
|
-
if (isMapping) addMappingEvent(state,
|
|
1960
|
-
else addSequenceEvent(state,
|
|
1959
|
+
if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
|
|
1960
|
+
else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
|
|
1961
1961
|
state.position++;
|
|
1962
1962
|
while (state.input.charCodeAt(state.position) !== 0) {
|
|
1963
1963
|
skipFlowSeparationSpace(state, nodeIndent);
|
|
@@ -2199,9 +2199,9 @@ function readDirective(state) {
|
|
|
2199
2199
|
while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {
|
|
2200
2200
|
while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++;
|
|
2201
2201
|
if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break;
|
|
2202
|
-
const
|
|
2202
|
+
const start = state.position;
|
|
2203
2203
|
while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
|
|
2204
|
-
args.push(state.input.slice(
|
|
2204
|
+
args.push(state.input.slice(start, state.position));
|
|
2205
2205
|
}
|
|
2206
2206
|
if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
|
|
2207
2207
|
if (name === "YAML") {
|
|
@@ -2776,25 +2776,25 @@ function foldLine(line, width) {
|
|
|
2776
2776
|
if (line === "" || isMoreIndented(line[0])) return line;
|
|
2777
2777
|
const breakRe = / [^ \t]/g;
|
|
2778
2778
|
let match;
|
|
2779
|
-
let
|
|
2779
|
+
let start = 0;
|
|
2780
2780
|
let end;
|
|
2781
2781
|
let curr = 0;
|
|
2782
2782
|
let next = 0;
|
|
2783
2783
|
let result = "";
|
|
2784
2784
|
while (match = breakRe.exec(line)) {
|
|
2785
2785
|
next = match.index;
|
|
2786
|
-
if (next -
|
|
2787
|
-
end = curr >
|
|
2786
|
+
if (next - start > width) {
|
|
2787
|
+
end = curr > start ? curr : next;
|
|
2788
2788
|
result += `
|
|
2789
|
-
${line.slice(
|
|
2790
|
-
|
|
2789
|
+
${line.slice(start, end)}`;
|
|
2790
|
+
start = end + 1;
|
|
2791
2791
|
}
|
|
2792
2792
|
curr = next;
|
|
2793
2793
|
}
|
|
2794
2794
|
result += "\n";
|
|
2795
|
-
if (line.length -
|
|
2795
|
+
if (line.length - start > width && curr > start) result += `${line.slice(start, curr)}
|
|
2796
2796
|
${line.slice(curr + 1)}`;
|
|
2797
|
-
else result += line.slice(
|
|
2797
|
+
else result += line.slice(start);
|
|
2798
2798
|
return result.slice(1);
|
|
2799
2799
|
}
|
|
2800
2800
|
function escapeString(string) {
|
|
@@ -3067,14 +3067,15 @@ var UI_URLS = {
|
|
|
3067
3067
|
dash: "https://metacubex.github.io/metacubexd",
|
|
3068
3068
|
yacd: "https://yacd.metacubex.one"
|
|
3069
3069
|
};
|
|
3070
|
-
var
|
|
3071
|
-
var
|
|
3072
|
-
function
|
|
3073
|
-
return
|
|
3074
|
-
}
|
|
3075
|
-
var
|
|
3076
|
-
var
|
|
3077
|
-
var
|
|
3070
|
+
var DEFAULT_SERVICE_LABEL = "com.mihomo-cli.daemon";
|
|
3071
|
+
var SERVICE_LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
3072
|
+
function isValidServiceLabel(label) {
|
|
3073
|
+
return SERVICE_LABEL_RE.test(label) && !label.includes("..");
|
|
3074
|
+
}
|
|
3075
|
+
var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
|
|
3076
|
+
var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
|
|
3077
|
+
var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
|
|
3078
|
+
var SERVICE_BINARY_NAME = "mihomo-cli-service";
|
|
3078
3079
|
var CONTROLLER_PORT = 9090;
|
|
3079
3080
|
var CONTROLLER_ADDR = `127.0.0.1:${CONTROLLER_PORT}`;
|
|
3080
3081
|
var CONTROLLER_BASE_URL = `http://${CONTROLLER_ADDR}`;
|
|
@@ -3171,6 +3172,16 @@ var DIRS = {
|
|
|
3171
3172
|
};
|
|
3172
3173
|
var PATHS = {
|
|
3173
3174
|
mihomoBinary: path.join(DIRS.kernel, "mihomo"),
|
|
3175
|
+
/**
|
|
3176
|
+
* 服务启动用的符号链(→ mihomoBinary,同目录相对链接)。
|
|
3177
|
+
* plist 的 ProgramArguments[0] 指向它而非真实二进制:「系统设置 → 通用 → 登录项与扩展」
|
|
3178
|
+
* 按 ProgramArguments[0] 的 basename 显示,直接指向内核的话用户只看到一个没有上下文的
|
|
3179
|
+
* "mihomo",无从判断这是什么、能不能关掉。
|
|
3180
|
+
*
|
|
3181
|
+
* 注意:进程命令行记录的是**符号链路径**而非真实路径(实测 ps -ww -o command= 输出符号链名,
|
|
3182
|
+
* 用真实文件名 pgrep -f 匹配不到),故 MAIN_INSTANCE_PATTERN 必须同时匹配两者。
|
|
3183
|
+
*/
|
|
3184
|
+
serviceBinary: path.join(DIRS.kernel, SERVICE_BINARY_NAME),
|
|
3174
3185
|
settingsFile: path.join(USER_DATA_DIR, "settings.json"),
|
|
3175
3186
|
subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
|
|
3176
3187
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
@@ -3179,8 +3190,11 @@ var PATHS = {
|
|
|
3179
3190
|
configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
|
|
3180
3191
|
configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
|
|
3181
3192
|
configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
|
|
3182
|
-
//
|
|
3183
|
-
|
|
3193
|
+
// 用户级 LaunchAgent(默认):gui/<uid> 域,全程免 sudo。随 homedir 走
|
|
3194
|
+
userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`),
|
|
3195
|
+
// 旧版本(v3.0–v4.0 的 daemon on)装的系统级 LaunchDaemon:root:wheel 拥有。
|
|
3196
|
+
// 本版不再往这里安装,仅用于识别并清理遗留安装(它带 KeepAlive,不清就是抢端口的幽灵)
|
|
3197
|
+
systemDaemonPlist: path.join("/Library/LaunchDaemons", `${SERVICE_LABEL}.plist`)
|
|
3184
3198
|
};
|
|
3185
3199
|
var DIRECTORY_TARGETS = {
|
|
3186
3200
|
root: { path: null, label: "\u6839\u76EE\u5F55" },
|
|
@@ -3726,7 +3740,6 @@ function listOverwriteFile() {
|
|
|
3726
3740
|
}
|
|
3727
3741
|
|
|
3728
3742
|
// src/utils.ts
|
|
3729
|
-
var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
3730
3743
|
function sleep(ms) {
|
|
3731
3744
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3732
3745
|
}
|
|
@@ -3736,6 +3749,25 @@ function escapeRegExp(s) {
|
|
|
3736
3749
|
function shellQuote(s) {
|
|
3737
3750
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
3738
3751
|
}
|
|
3752
|
+
function displayWidth(s) {
|
|
3753
|
+
let width = 0;
|
|
3754
|
+
for (const ch of s) {
|
|
3755
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
3756
|
+
const isWide = code >= 4352 && code <= 4447 || // 韩文字母
|
|
3757
|
+
code >= 11904 && code <= 42191 || // CJK 部首 … 注音、统一表意文字
|
|
3758
|
+
code >= 44032 && code <= 55203 || // 韩文音节
|
|
3759
|
+
code >= 63744 && code <= 64255 || // CJK 兼容表意文字
|
|
3760
|
+
code >= 65072 && code <= 65135 || // CJK 兼容形式
|
|
3761
|
+
code >= 65280 && code <= 65376 || // 全角字母数字与标点
|
|
3762
|
+
code >= 65504 && code <= 65510;
|
|
3763
|
+
width += isWide ? 2 : 1;
|
|
3764
|
+
}
|
|
3765
|
+
return width;
|
|
3766
|
+
}
|
|
3767
|
+
function padEndDisplay(s, width) {
|
|
3768
|
+
const pad = width - displayWidth(s);
|
|
3769
|
+
return pad > 0 ? s + " ".repeat(pad) : s;
|
|
3770
|
+
}
|
|
3739
3771
|
function formatBytes(bytes) {
|
|
3740
3772
|
if (bytes === void 0 || bytes === null) return "\u672A\u77E5";
|
|
3741
3773
|
const num = Number(bytes);
|
|
@@ -4285,7 +4317,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo help \u67E5\u770B
|
|
|
4285
4317
|
`);
|
|
4286
4318
|
console.log(
|
|
4287
4319
|
`\u5E38\u7528\u547D\u4EE4:
|
|
4288
|
-
${colors.bold("start")}
|
|
4320
|
+
${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
|
|
4289
4321
|
${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
|
|
4290
4322
|
${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
|
|
4291
4323
|
${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
|
|
@@ -4302,36 +4334,37 @@ var GROUP_TITLES = [
|
|
|
4302
4334
|
function printHelp(commands) {
|
|
4303
4335
|
const lines = [`
|
|
4304
4336
|
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mihomo, mhm, mh", "", "\u7528\u6CD5:", " mihomo <\u547D\u4EE4> [\u9009\u9879]"];
|
|
4337
|
+
const allUsage = commands.flatMap((c) => c.usage);
|
|
4338
|
+
const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
|
|
4339
|
+
const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
|
|
4305
4340
|
for (const [group, title] of GROUP_TITLES) {
|
|
4306
4341
|
const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
|
|
4307
4342
|
if (usageLines.length === 0) continue;
|
|
4308
4343
|
lines.push("", colors.cyan(title));
|
|
4309
|
-
for (const u of usageLines)
|
|
4310
|
-
lines.push(u.startsWith(" ") ? ` ${u}` : ` ${boldFirstToken(u)}`);
|
|
4311
|
-
}
|
|
4344
|
+
for (const u of usageLines) lines.push(formatUsage(u));
|
|
4312
4345
|
}
|
|
4313
4346
|
const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
|
|
4314
4347
|
if (meta.length > 0) {
|
|
4315
4348
|
lines.push("", colors.cyan("\u5143:"));
|
|
4316
|
-
for (const u of meta) lines.push(
|
|
4349
|
+
for (const u of meta) lines.push(formatUsage(u));
|
|
4317
4350
|
}
|
|
4318
4351
|
lines.push(
|
|
4319
4352
|
"",
|
|
4320
4353
|
`${colors.cyan("\u793A\u4F8B:")}`,
|
|
4321
|
-
" mihomo
|
|
4322
|
-
" mihomo start
|
|
4354
|
+
" mihomo install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
|
|
4355
|
+
" mihomo start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
|
|
4356
|
+
" mihomo stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
|
|
4357
|
+
" mihomo start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
|
|
4323
4358
|
" mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
4324
|
-
" mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
|
|
4325
|
-
" mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
|
|
4326
4359
|
" mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
4327
4360
|
" mihomo ui # \u6253\u5F00 Web UI",
|
|
4328
4361
|
"",
|
|
4329
4362
|
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
4330
|
-
" tun = start tun
|
|
4363
|
+
" tun = start tun",
|
|
4331
4364
|
"",
|
|
4332
4365
|
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
4333
|
-
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
|
|
4334
|
-
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u9700\u8981 sudo",
|
|
4366
|
+
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
|
|
4367
|
+
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
|
|
4335
4368
|
"",
|
|
4336
4369
|
`${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
|
|
4337
4370
|
" \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
|
|
@@ -4339,11 +4372,6 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
|
|
|
4339
4372
|
);
|
|
4340
4373
|
console.log(lines.join("\n"));
|
|
4341
4374
|
}
|
|
4342
|
-
function boldFirstToken(usage) {
|
|
4343
|
-
const spaceIdx = usage.indexOf(" ");
|
|
4344
|
-
if (spaceIdx < 0) return colors.bold(usage);
|
|
4345
|
-
return `${colors.bold(usage.slice(0, spaceIdx))}${usage.slice(spaceIdx)}`;
|
|
4346
|
-
}
|
|
4347
4375
|
function printVersion() {
|
|
4348
4376
|
const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
|
|
4349
4377
|
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
@@ -4351,9 +4379,63 @@ function printVersion() {
|
|
|
4351
4379
|
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
4352
4380
|
}
|
|
4353
4381
|
|
|
4354
|
-
// src/
|
|
4355
|
-
import
|
|
4356
|
-
|
|
4382
|
+
// src/open.ts
|
|
4383
|
+
import { spawn } from "child_process";
|
|
4384
|
+
|
|
4385
|
+
// src/lifecycle.ts
|
|
4386
|
+
var silentSigint = false;
|
|
4387
|
+
function setSilentSigint(value) {
|
|
4388
|
+
silentSigint = value;
|
|
4389
|
+
}
|
|
4390
|
+
function isSilentSigint() {
|
|
4391
|
+
return silentSigint;
|
|
4392
|
+
}
|
|
4393
|
+
|
|
4394
|
+
// src/open.ts
|
|
4395
|
+
function openUrl(url) {
|
|
4396
|
+
try {
|
|
4397
|
+
const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
|
|
4398
|
+
child.unref();
|
|
4399
|
+
child.on("error", () => {
|
|
4400
|
+
});
|
|
4401
|
+
return true;
|
|
4402
|
+
} catch {
|
|
4403
|
+
return false;
|
|
4404
|
+
}
|
|
4405
|
+
}
|
|
4406
|
+
function openLogFile(logPath, label) {
|
|
4407
|
+
const displayLabel = label || logPath;
|
|
4408
|
+
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${displayLabel}`);
|
|
4409
|
+
const success = openUrl(logPath);
|
|
4410
|
+
if (!success) {
|
|
4411
|
+
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
4412
|
+
}
|
|
4413
|
+
}
|
|
4414
|
+
function viewLogWithTail(logPath, options) {
|
|
4415
|
+
const follow = options?.follow;
|
|
4416
|
+
const lines = options?.lines || 100;
|
|
4417
|
+
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
4418
|
+
if (follow) {
|
|
4419
|
+
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
4420
|
+
} else {
|
|
4421
|
+
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
4422
|
+
`);
|
|
4423
|
+
}
|
|
4424
|
+
const tailArgs = [];
|
|
4425
|
+
if (follow) tailArgs.push("-f");
|
|
4426
|
+
tailArgs.push("-n", lines.toString());
|
|
4427
|
+
tailArgs.push(logPath);
|
|
4428
|
+
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
4429
|
+
if (follow) setSilentSigint(true);
|
|
4430
|
+
tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
|
|
4431
|
+
tail.on("error", (e) => {
|
|
4432
|
+
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
4433
|
+
process.exit(1);
|
|
4434
|
+
});
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
// src/commands/shared.ts
|
|
4438
|
+
import readline from "readline";
|
|
4357
4439
|
|
|
4358
4440
|
// src/log-files.ts
|
|
4359
4441
|
import fs5 from "fs";
|
|
@@ -4366,6 +4448,29 @@ function rotateAndCleanupLogs() {
|
|
|
4366
4448
|
function getLogPath() {
|
|
4367
4449
|
return PATHS.logFile;
|
|
4368
4450
|
}
|
|
4451
|
+
function readLogTail(maxLines = 15) {
|
|
4452
|
+
const TAIL_BYTES = 64 * 1024;
|
|
4453
|
+
let fd = null;
|
|
4454
|
+
try {
|
|
4455
|
+
const size = fs5.statSync(PATHS.logFile).size;
|
|
4456
|
+
if (size === 0) return [];
|
|
4457
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
4458
|
+
const length = size - start;
|
|
4459
|
+
const buf = Buffer.alloc(length);
|
|
4460
|
+
fd = fs5.openSync(PATHS.logFile, "r");
|
|
4461
|
+
fs5.readSync(fd, buf, 0, length, start);
|
|
4462
|
+
return buf.toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-maxLines);
|
|
4463
|
+
} catch {
|
|
4464
|
+
return [];
|
|
4465
|
+
} finally {
|
|
4466
|
+
if (fd !== null) {
|
|
4467
|
+
try {
|
|
4468
|
+
fs5.closeSync(fd);
|
|
4469
|
+
} catch {
|
|
4470
|
+
}
|
|
4471
|
+
}
|
|
4472
|
+
}
|
|
4473
|
+
}
|
|
4369
4474
|
function rotateLog() {
|
|
4370
4475
|
const logFile = PATHS.logFile;
|
|
4371
4476
|
if (!fs5.existsSync(logFile)) return null;
|
|
@@ -4465,7 +4570,8 @@ function isProcessRoot(pid) {
|
|
|
4465
4570
|
return false;
|
|
4466
4571
|
}
|
|
4467
4572
|
}
|
|
4468
|
-
var
|
|
4573
|
+
var BINARY_ALTERNATION = `(?:${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
4574
|
+
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
4469
4575
|
function getPid() {
|
|
4470
4576
|
if (!fs6.existsSync(PATHS.pidFile)) return null;
|
|
4471
4577
|
try {
|
|
@@ -4478,7 +4584,7 @@ function getPid() {
|
|
|
4478
4584
|
function isRunning() {
|
|
4479
4585
|
const pid = getPid();
|
|
4480
4586
|
if (!pid) return false;
|
|
4481
|
-
return isProcessRunning(pid) && isProcessCommandMatching(pid, PATHS.mihomoBinary);
|
|
4587
|
+
return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
|
|
4482
4588
|
}
|
|
4483
4589
|
function getMihomoPids() {
|
|
4484
4590
|
try {
|
|
@@ -4511,9 +4617,6 @@ function checkStaleState() {
|
|
|
4511
4617
|
needsSudo: hasRootProcess || hasRootPidFile
|
|
4512
4618
|
};
|
|
4513
4619
|
}
|
|
4514
|
-
function hasRootResidue() {
|
|
4515
|
-
return checkStaleState().needsSudo;
|
|
4516
|
-
}
|
|
4517
4620
|
function getProcessInfo(pid) {
|
|
4518
4621
|
try {
|
|
4519
4622
|
const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
|
|
@@ -4532,19 +4635,19 @@ function getProcessInfo(pid) {
|
|
|
4532
4635
|
function getStatus() {
|
|
4533
4636
|
const running = isRunning();
|
|
4534
4637
|
const pid = getPid();
|
|
4535
|
-
const allPids = getMihomoPids();
|
|
4536
4638
|
return {
|
|
4537
4639
|
running,
|
|
4538
4640
|
pid: running ? pid : null,
|
|
4539
4641
|
processInfo: running && pid ? getProcessInfo(pid) : null,
|
|
4540
4642
|
hasConfig: hasConfig(),
|
|
4541
4643
|
hasKernel: hasKernel(),
|
|
4542
|
-
kernelVersion: getKernelVersion()
|
|
4543
|
-
allProcesses: allPids,
|
|
4544
|
-
hasStaleProcesses: allPids.length > (running ? 1 : 0)
|
|
4644
|
+
kernelVersion: getKernelVersion()
|
|
4545
4645
|
};
|
|
4546
4646
|
}
|
|
4547
4647
|
|
|
4648
|
+
// src/process-start.ts
|
|
4649
|
+
import fs8 from "fs";
|
|
4650
|
+
|
|
4548
4651
|
// src/sudo.ts
|
|
4549
4652
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
4550
4653
|
import fs7 from "fs";
|
|
@@ -4579,41 +4682,202 @@ function runSudoScript(scriptBody, opts) {
|
|
|
4579
4682
|
}
|
|
4580
4683
|
}
|
|
4581
4684
|
|
|
4582
|
-
// src/
|
|
4583
|
-
var
|
|
4584
|
-
function
|
|
4585
|
-
|
|
4586
|
-
|
|
4685
|
+
// src/process-start.ts
|
|
4686
|
+
var TUN_MODE_POST_WAIT_MS = 500;
|
|
4687
|
+
function buildTunLaunchScript() {
|
|
4688
|
+
const binary = shellQuote(PATHS.mihomoBinary);
|
|
4689
|
+
const configFile = shellQuote(PATHS.configFile);
|
|
4690
|
+
const logFile = shellQuote(PATHS.logFile);
|
|
4691
|
+
const pidFile = shellQuote(PATHS.pidFile);
|
|
4692
|
+
const dataDir = shellQuote(DIRS.data);
|
|
4693
|
+
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
4694
|
+
return `#!/bin/bash
|
|
4695
|
+
BINARY=${binary}
|
|
4696
|
+
CONFIG_FILE=${configFile}
|
|
4697
|
+
LOG_FILE=${logFile}
|
|
4698
|
+
PID_FILE=${pidFile}
|
|
4699
|
+
DATA_DIR=${dataDir}
|
|
4700
|
+
KILL_PATTERN=${killPattern}
|
|
4701
|
+
|
|
4702
|
+
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
4703
|
+
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
4704
|
+
sleep 0.2
|
|
4705
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4706
|
+
|
|
4707
|
+
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
4708
|
+
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
4709
|
+
|
|
4710
|
+
# \u542F\u52A8
|
|
4711
|
+
cd /tmp
|
|
4712
|
+
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
4713
|
+
NEW_PID=$!
|
|
4714
|
+
echo \${NEW_PID} > "\${PID_FILE}"
|
|
4715
|
+
|
|
4716
|
+
# \u9A8C\u8BC1
|
|
4717
|
+
for i in 1 2 3 4 5; do
|
|
4718
|
+
sleep 0.4
|
|
4719
|
+
if kill -0 \${NEW_PID} 2>/dev/null; then
|
|
4720
|
+
exit 0
|
|
4721
|
+
fi
|
|
4722
|
+
done
|
|
4723
|
+
|
|
4724
|
+
# \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
|
|
4725
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
4726
|
+
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
4727
|
+
echo ""
|
|
4728
|
+
echo "--- \u65E5\u5FD7 ---"
|
|
4729
|
+
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
4730
|
+
exit 2
|
|
4731
|
+
`;
|
|
4732
|
+
}
|
|
4733
|
+
async function startTun() {
|
|
4734
|
+
ensureDirs();
|
|
4735
|
+
rotateAndCleanupLogs();
|
|
4736
|
+
if (!fs8.existsSync(PATHS.mihomoBinary)) {
|
|
4737
|
+
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4738
|
+
}
|
|
4739
|
+
if (!fs8.existsSync(PATHS.configFile)) {
|
|
4740
|
+
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
4741
|
+
}
|
|
4742
|
+
const logFile = PATHS.logFile;
|
|
4743
|
+
if (fs8.existsSync(logFile)) {
|
|
4744
|
+
try {
|
|
4745
|
+
fs8.accessSync(logFile, fs8.constants.W_OK);
|
|
4746
|
+
} catch {
|
|
4747
|
+
try {
|
|
4748
|
+
fs8.unlinkSync(logFile);
|
|
4749
|
+
} catch {
|
|
4750
|
+
}
|
|
4751
|
+
}
|
|
4752
|
+
}
|
|
4753
|
+
const staleState = checkStaleState();
|
|
4754
|
+
if (staleState.needsCleanup) {
|
|
4755
|
+
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
4756
|
+
}
|
|
4757
|
+
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
4758
|
+
runSudoScript(buildTunLaunchScript(), {
|
|
4759
|
+
action: "TUN \u542F\u52A8",
|
|
4760
|
+
file: "launch-tun.sh",
|
|
4761
|
+
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
4762
|
+
});
|
|
4763
|
+
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
4764
|
+
const finalPid = getPid();
|
|
4765
|
+
if (!finalPid) {
|
|
4766
|
+
throw new CliError("TUN \u542F\u52A8\u5931\u8D25");
|
|
4767
|
+
}
|
|
4768
|
+
return { success: true, pid: finalPid, mode: "tun" };
|
|
4769
|
+
}
|
|
4770
|
+
|
|
4771
|
+
// src/service.ts
|
|
4772
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
4773
|
+
import fs9 from "fs";
|
|
4774
|
+
import path6 from "path";
|
|
4775
|
+
function assertServiceLabelSafe() {
|
|
4776
|
+
if (RAW_SERVICE_LABEL_INPUT !== void 0 && !isValidServiceLabel(RAW_SERVICE_LABEL_INPUT)) {
|
|
4777
|
+
throw new CliError(`MIHOMO_CLI_DAEMON_LABEL \u65E0\u6548: "${RAW_SERVICE_LABEL_INPUT}"`, {
|
|
4587
4778
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4588
|
-
hint: [
|
|
4589
|
-
'\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002',
|
|
4590
|
-
"\u8BE5\u503C\u4F1A\u6210\u4E3A /Library/LaunchDaemons/ \u4E0B\u7684 plist \u6587\u4EF6\u540D\uFF0C\u5E76\u4F5C\u4E3A root \u5199\u5165/\u5220\u9664\u7684\u76EE\u6807\u8DEF\u5F84\u3002"
|
|
4591
|
-
]
|
|
4779
|
+
hint: ['\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\uFF0C\u4E14\u4E0D\u80FD\u542B ".."\u3002', "\u8BE5\u503C\u4F1A\u6210\u4E3A launchd plist \u7684\u6587\u4EF6\u540D\uFF0C\u5E76\u53C2\u4E0E\u6E05\u7406\u9057\u7559\u5B89\u88C5\u65F6\u7684 root \u5220\u9664\u8DEF\u5F84\u3002"]
|
|
4592
4780
|
});
|
|
4593
4781
|
}
|
|
4594
4782
|
}
|
|
4595
4783
|
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
4596
|
-
var
|
|
4784
|
+
var SERVICE_HEALTH_INTERVAL_MS = 100;
|
|
4785
|
+
var SERVICE_OBSERVE_MS = 1200;
|
|
4786
|
+
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
4597
4787
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4598
|
-
|
|
4788
|
+
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
4789
|
+
function serviceTarget() {
|
|
4790
|
+
return `${bootstrapDomain()}/${SERVICE_LABEL}`;
|
|
4791
|
+
}
|
|
4792
|
+
function bootstrapDomain() {
|
|
4793
|
+
return `gui/${process.getuid?.() ?? 0}`;
|
|
4794
|
+
}
|
|
4795
|
+
function isServiceInstalled() {
|
|
4796
|
+
return fs9.existsSync(PATHS.userAgentPlist);
|
|
4797
|
+
}
|
|
4798
|
+
function detectLegacySystemInstall() {
|
|
4799
|
+
return fs9.existsSync(PATHS.systemDaemonPlist);
|
|
4800
|
+
}
|
|
4801
|
+
function parseServicePrint(output) {
|
|
4802
|
+
const stateMatch = output.match(/^\tstate = (.+)$/m);
|
|
4803
|
+
const pidMatch = output.match(/^\tpid = (\d+)$/m);
|
|
4804
|
+
const pid = pidMatch ? Number.parseInt(pidMatch[1], 10) : null;
|
|
4805
|
+
const exitMatch = output.match(/^\tlast exit code = (\d+)$/m);
|
|
4806
|
+
const lastExitCode = exitMatch ? Number.parseInt(exitMatch[1], 10) : null;
|
|
4807
|
+
return {
|
|
4808
|
+
state: stateMatch ? stateMatch[1].trim() : null,
|
|
4809
|
+
pid: pid !== null && Number.isInteger(pid) && pid > 0 ? pid : null,
|
|
4810
|
+
lastExitCode: lastExitCode !== null && Number.isInteger(lastExitCode) ? lastExitCode : null
|
|
4811
|
+
};
|
|
4812
|
+
}
|
|
4813
|
+
function parseDisabledList(output, label) {
|
|
4814
|
+
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4815
|
+
const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
|
|
4816
|
+
if (!match) return false;
|
|
4817
|
+
const value = match[1].toLowerCase();
|
|
4818
|
+
return value === "true" || value === "disabled";
|
|
4819
|
+
}
|
|
4820
|
+
function runLaunchctl(args) {
|
|
4599
4821
|
try {
|
|
4600
|
-
|
|
4822
|
+
const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout: LAUNCHCTL_TIMEOUT_MS });
|
|
4823
|
+
return { status: result.status, stdout: result.stdout || "" };
|
|
4601
4824
|
} catch {
|
|
4602
|
-
return
|
|
4825
|
+
return { status: null, stdout: "" };
|
|
4826
|
+
}
|
|
4827
|
+
}
|
|
4828
|
+
function getServiceStatus() {
|
|
4829
|
+
const installed = isServiceInstalled();
|
|
4830
|
+
const print = runLaunchctl(["print", serviceTarget()]);
|
|
4831
|
+
const loaded = print.status === 0;
|
|
4832
|
+
if (!installed && !loaded) {
|
|
4833
|
+
return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null };
|
|
4834
|
+
}
|
|
4835
|
+
const { state, pid, lastExitCode } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null };
|
|
4836
|
+
const disabledOut = runLaunchctl(["print-disabled", bootstrapDomain()]);
|
|
4837
|
+
const disabled = disabledOut.status === 0 ? parseDisabledList(disabledOut.stdout, SERVICE_LABEL) : false;
|
|
4838
|
+
return { installed, loaded, running: state === "running", pid, disabled, lastExitCode };
|
|
4839
|
+
}
|
|
4840
|
+
async function waitServiceHealthy() {
|
|
4841
|
+
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
4842
|
+
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
4843
|
+
let last = getServiceStatus();
|
|
4844
|
+
while (Date.now() < deadline) {
|
|
4845
|
+
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
4846
|
+
last = getServiceStatus();
|
|
4847
|
+
if (isCrashed(last)) {
|
|
4848
|
+
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode };
|
|
4849
|
+
}
|
|
4850
|
+
if (!last.loaded) {
|
|
4851
|
+
return { healthy: false, crashed: false, pid: null, exitCode: last.lastExitCode };
|
|
4852
|
+
}
|
|
4853
|
+
}
|
|
4854
|
+
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null };
|
|
4855
|
+
while (Date.now() < graceDeadline) {
|
|
4856
|
+
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
4857
|
+
last = getServiceStatus();
|
|
4858
|
+
if (isCrashed(last)) {
|
|
4859
|
+
return { healthy: false, crashed: true, pid: null, exitCode: last.lastExitCode };
|
|
4860
|
+
}
|
|
4861
|
+
if (!last.loaded) break;
|
|
4862
|
+
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null };
|
|
4603
4863
|
}
|
|
4864
|
+
return { healthy: false, crashed: false, pid: last.pid, exitCode: last.lastExitCode };
|
|
4865
|
+
}
|
|
4866
|
+
function isCrashed(status) {
|
|
4867
|
+
return !status.running && status.lastExitCode !== null && status.lastExitCode !== 0;
|
|
4604
4868
|
}
|
|
4605
4869
|
function escapeXml(s) {
|
|
4606
4870
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4607
4871
|
}
|
|
4608
4872
|
function buildPlist() {
|
|
4609
|
-
const programArguments = [PATHS.
|
|
4873
|
+
const programArguments = [PATHS.serviceBinary, "-d", DIRS.data, "-f", PATHS.configFile];
|
|
4610
4874
|
const argsXml = programArguments.map((a) => ` <string>${escapeXml(a)}</string>`).join("\n");
|
|
4611
4875
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
4612
4876
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4613
4877
|
<plist version="1.0">
|
|
4614
4878
|
<dict>
|
|
4615
4879
|
<key>Label</key>
|
|
4616
|
-
<string>${escapeXml(
|
|
4880
|
+
<string>${escapeXml(SERVICE_LABEL)}</string>
|
|
4617
4881
|
<key>ProgramArguments</key>
|
|
4618
4882
|
<array>
|
|
4619
4883
|
${argsXml}
|
|
@@ -4622,6 +4886,8 @@ ${argsXml}
|
|
|
4622
4886
|
<true/>
|
|
4623
4887
|
<key>KeepAlive</key>
|
|
4624
4888
|
<true/>
|
|
4889
|
+
<key>ProcessType</key>
|
|
4890
|
+
<string>Background</string>
|
|
4625
4891
|
<key>StandardOutPath</key>
|
|
4626
4892
|
<string>${escapeXml(PATHS.logFile)}</string>
|
|
4627
4893
|
<key>StandardErrorPath</key>
|
|
@@ -4632,97 +4898,172 @@ ${argsXml}
|
|
|
4632
4898
|
</plist>
|
|
4633
4899
|
`;
|
|
4634
4900
|
}
|
|
4635
|
-
function
|
|
4636
|
-
|
|
4901
|
+
function ensureServiceSymlink() {
|
|
4902
|
+
if (!fs9.existsSync(PATHS.mihomoBinary)) {
|
|
4903
|
+
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4904
|
+
}
|
|
4905
|
+
try {
|
|
4906
|
+
const current = fs9.readlinkSync(PATHS.serviceBinary);
|
|
4907
|
+
if (current === "mihomo") return;
|
|
4908
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
4909
|
+
} catch (e) {
|
|
4910
|
+
const code = e.code;
|
|
4911
|
+
if (code === "EINVAL") {
|
|
4912
|
+
try {
|
|
4913
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
4914
|
+
} catch {
|
|
4915
|
+
}
|
|
4916
|
+
} else if (code !== "ENOENT") {
|
|
4917
|
+
throw e;
|
|
4918
|
+
}
|
|
4919
|
+
}
|
|
4920
|
+
fs9.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
4637
4921
|
}
|
|
4638
|
-
function
|
|
4639
|
-
|
|
4640
|
-
|
|
4922
|
+
function runLaunchctlSteps(steps, opts) {
|
|
4923
|
+
const script = ["#!/bin/bash", ...steps, "exit 0", ""].join("\n");
|
|
4924
|
+
const result = spawnSync4("/bin/bash", ["-c", script], { stdio: "inherit", timeout: 6e4 });
|
|
4925
|
+
if (result.error) throw result.error;
|
|
4926
|
+
if (result.status !== 0) {
|
|
4927
|
+
const custom = result.status !== null ? opts.codeMessages?.[result.status] : void 0;
|
|
4928
|
+
throw new CliError(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status ?? "\u4FE1\u53F7\u4E2D\u65AD"}\uFF09`);
|
|
4641
4929
|
}
|
|
4642
|
-
const rootPids = getMihomoPids().filter(isProcessRoot);
|
|
4643
|
-
return { enabled: true, loaded: rootPids.length > 0, pid: rootPids[0] ?? null };
|
|
4644
4930
|
}
|
|
4645
|
-
function
|
|
4646
|
-
|
|
4931
|
+
function cleanupRootResidue() {
|
|
4932
|
+
const rootPids = getMihomoPids().filter(isProcessRoot);
|
|
4933
|
+
const pidFileIsRoot = fs9.existsSync(PATHS.pidFile) && (() => {
|
|
4934
|
+
try {
|
|
4935
|
+
return fs9.statSync(PATHS.pidFile).uid === 0;
|
|
4936
|
+
} catch {
|
|
4937
|
+
return false;
|
|
4938
|
+
}
|
|
4939
|
+
})();
|
|
4940
|
+
if (rootPids.length === 0 && !pidFileIsRoot) return;
|
|
4941
|
+
const script = [
|
|
4942
|
+
"#!/bin/bash",
|
|
4943
|
+
`pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null || true`,
|
|
4944
|
+
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
4945
|
+
"exit 0",
|
|
4946
|
+
""
|
|
4947
|
+
].join("\n");
|
|
4948
|
+
runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh" });
|
|
4647
4949
|
}
|
|
4648
|
-
function
|
|
4649
|
-
|
|
4650
|
-
if (
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4950
|
+
function killResidualKernels() {
|
|
4951
|
+
const pids = getMihomoPids();
|
|
4952
|
+
if (pids.length === 0) return;
|
|
4953
|
+
const rootPids = pids.filter(isProcessRoot);
|
|
4954
|
+
for (const pid of pids) {
|
|
4955
|
+
if (rootPids.includes(pid)) continue;
|
|
4956
|
+
try {
|
|
4957
|
+
process.kill(pid, "SIGKILL");
|
|
4958
|
+
} catch {
|
|
4959
|
+
}
|
|
4655
4960
|
}
|
|
4961
|
+
if (rootPids.length > 0) cleanupRootResidue();
|
|
4962
|
+
}
|
|
4963
|
+
function waitUnloadedSteps() {
|
|
4964
|
+
const target = shellQuote(serviceTarget());
|
|
4965
|
+
return ["n=0", "while [ $n -lt 25 ]; do", ` launchctl print ${target} >/dev/null 2>&1 || break`, " sleep 0.2", " n=$((n+1))", "done"];
|
|
4966
|
+
}
|
|
4967
|
+
function installService(wasRunning) {
|
|
4968
|
+
assertServiceLabelSafe();
|
|
4656
4969
|
ensureDirs();
|
|
4657
|
-
|
|
4970
|
+
ensureServiceSymlink();
|
|
4971
|
+
const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
|
|
4658
4972
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
4659
|
-
const target = shellQuote(
|
|
4660
|
-
const
|
|
4973
|
+
const target = shellQuote(serviceTarget());
|
|
4974
|
+
const dest = shellQuote(PATHS.userAgentPlist);
|
|
4661
4975
|
const stage = shellQuote(stagePath);
|
|
4662
|
-
const
|
|
4663
|
-
const
|
|
4664
|
-
|
|
4665
|
-
"#!/bin/bash",
|
|
4976
|
+
const destDir = shellQuote(path6.dirname(PATHS.userAgentPlist));
|
|
4977
|
+
const steps = [
|
|
4978
|
+
`plutil -lint ${stage} >/dev/null || exit 2`,
|
|
4666
4979
|
`launchctl bootout ${target} 2>/dev/null || true`,
|
|
4667
|
-
|
|
4668
|
-
//
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
`
|
|
4672
|
-
|
|
4673
|
-
`install -m 644 -o root -g wheel ${stage} ${plistDest} || exit 2`,
|
|
4674
|
-
`launchctl bootstrap system ${plistDest} || { launchctl bootout ${target} 2>/dev/null; rm -f ${plistDest}; exit 3; }`,
|
|
4675
|
-
"exit 0",
|
|
4676
|
-
""
|
|
4677
|
-
].join("\n");
|
|
4980
|
+
...waitUnloadedSteps(),
|
|
4981
|
+
// ~/Library/LaunchAgents 在全新系统上可能不存在;只在缺失时创建,避免改动已有目录权限
|
|
4982
|
+
`[ -d ${destDir} ] || mkdir -p ${destDir}`,
|
|
4983
|
+
`install -m 644 ${stage} ${dest} || exit 3`,
|
|
4984
|
+
...wasRunning ? [`launchctl enable ${target} || exit 5`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 4`] : [`launchctl disable ${target} 2>/dev/null || true`]
|
|
4985
|
+
];
|
|
4678
4986
|
try {
|
|
4679
|
-
|
|
4680
|
-
action: "\
|
|
4681
|
-
file: "daemon-enable.sh",
|
|
4987
|
+
runLaunchctlSteps(steps, {
|
|
4988
|
+
action: "\u5B89\u88C5\u670D\u52A1",
|
|
4682
4989
|
codeMessages: {
|
|
4683
|
-
2: "
|
|
4684
|
-
3:
|
|
4990
|
+
2: "plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09",
|
|
4991
|
+
3: `\u5B89\u88C5 plist \u5230 ${path6.dirname(PATHS.userAgentPlist)} \u5931\u8D25`,
|
|
4992
|
+
4: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09",
|
|
4993
|
+
5: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09"
|
|
4685
4994
|
}
|
|
4686
4995
|
});
|
|
4687
4996
|
} finally {
|
|
4688
4997
|
try {
|
|
4689
|
-
|
|
4998
|
+
fs9.unlinkSync(stagePath);
|
|
4690
4999
|
} catch {
|
|
4691
5000
|
}
|
|
4692
5001
|
}
|
|
4693
5002
|
}
|
|
4694
|
-
function
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
4698
|
-
|
|
4699
|
-
if (!plistExists) {
|
|
4700
|
-
console.log("\u672A\u627E\u5230 plist\uFF0C\u4F46\u68C0\u6D4B\u5230 root \u5185\u6838\u5728\u8FD0\u884C\uFF08\u53EF\u80FD plist \u88AB\u624B\u52A8\u5220\u9664\u800C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09");
|
|
4701
|
-
console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
|
|
5003
|
+
function startService() {
|
|
5004
|
+
assertServiceLabelSafe();
|
|
5005
|
+
ensureServiceSymlink();
|
|
5006
|
+
if (!isServiceInstalled()) {
|
|
5007
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
4702
5008
|
}
|
|
4703
|
-
|
|
4704
|
-
|
|
4705
|
-
|
|
4706
|
-
|
|
5009
|
+
if (!fs9.existsSync(PATHS.configFile)) {
|
|
5010
|
+
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
|
|
5011
|
+
}
|
|
5012
|
+
cleanupRootResidue();
|
|
5013
|
+
const target = shellQuote(serviceTarget());
|
|
5014
|
+
const dest = shellQuote(PATHS.userAgentPlist);
|
|
5015
|
+
runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], { action: "\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B" });
|
|
5016
|
+
rotateAndCleanupLogs();
|
|
5017
|
+
runLaunchctlSteps([`launchctl enable ${target} || exit 2`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`], {
|
|
5018
|
+
action: "\u542F\u52A8\u670D\u52A1",
|
|
5019
|
+
codeMessages: { 2: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09", 3: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
|
|
5020
|
+
});
|
|
5021
|
+
}
|
|
5022
|
+
function stopService() {
|
|
5023
|
+
assertServiceLabelSafe();
|
|
5024
|
+
const target = shellQuote(serviceTarget());
|
|
5025
|
+
runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
|
|
5026
|
+
action: "\u505C\u6B62\u670D\u52A1"
|
|
5027
|
+
});
|
|
5028
|
+
killResidualKernels();
|
|
5029
|
+
}
|
|
5030
|
+
function uninstallService() {
|
|
5031
|
+
assertServiceLabelSafe();
|
|
5032
|
+
const target = shellQuote(serviceTarget());
|
|
5033
|
+
runLaunchctlSteps(
|
|
5034
|
+
[`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, `rm -f ${shellQuote(PATHS.userAgentPlist)}`],
|
|
5035
|
+
{ action: "\u5378\u8F7D\u670D\u52A1" }
|
|
5036
|
+
);
|
|
5037
|
+
killResidualKernels();
|
|
5038
|
+
try {
|
|
5039
|
+
fs9.unlinkSync(PATHS.serviceBinary);
|
|
5040
|
+
} catch {
|
|
5041
|
+
}
|
|
5042
|
+
}
|
|
5043
|
+
function cleanupLegacySystemInstall() {
|
|
5044
|
+
assertServiceLabelSafe();
|
|
4707
5045
|
const script = [
|
|
4708
5046
|
"#!/bin/bash",
|
|
4709
|
-
`launchctl bootout ${
|
|
4710
|
-
`rm -f ${
|
|
4711
|
-
`chown "$SUDO_UID:$SUDO_GID" ${logFile} 2>/dev/null || true`,
|
|
4712
|
-
`chown -R "$SUDO_UID:$SUDO_GID" ${
|
|
5047
|
+
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || true`,
|
|
5048
|
+
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5049
|
+
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
5050
|
+
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
5051
|
+
`rm -f ${shellQuote(PATHS.pidFile)}`,
|
|
4713
5052
|
"exit 0",
|
|
4714
5053
|
""
|
|
4715
5054
|
].join("\n");
|
|
4716
|
-
runSudoScript(script, { action: "\
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
5055
|
+
runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
|
|
5056
|
+
}
|
|
5057
|
+
function logOversized() {
|
|
5058
|
+
try {
|
|
5059
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5060
|
+
} catch {
|
|
5061
|
+
return false;
|
|
4722
5062
|
}
|
|
4723
5063
|
}
|
|
4724
5064
|
async function tryHotReload() {
|
|
4725
|
-
|
|
5065
|
+
const status = getServiceStatus();
|
|
5066
|
+
if (!status.running || status.pid === null) return false;
|
|
4726
5067
|
const controller = new AbortController();
|
|
4727
5068
|
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
4728
5069
|
const secret = readSettings().controller_secret;
|
|
@@ -4746,42 +5087,88 @@ async function tryHotReload() {
|
|
|
4746
5087
|
clearTimeout(timer);
|
|
4747
5088
|
}
|
|
4748
5089
|
}
|
|
4749
|
-
async function
|
|
4750
|
-
if (!
|
|
4751
|
-
throw new CliError("\
|
|
5090
|
+
async function restartService() {
|
|
5091
|
+
if (!isServiceInstalled()) {
|
|
5092
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
4752
5093
|
}
|
|
4753
|
-
if (!logOversized() && await tryHotReload()) return;
|
|
4754
|
-
const target = shellQuote(
|
|
4755
|
-
const
|
|
5094
|
+
if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
|
|
5095
|
+
const target = shellQuote(serviceTarget());
|
|
5096
|
+
const dest = shellQuote(PATHS.userAgentPlist);
|
|
4756
5097
|
const logFile = shellQuote(PATHS.logFile);
|
|
4757
5098
|
const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
|
|
4758
|
-
|
|
4759
|
-
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
action: "\u91CD\u542F\u4FDD\u6D3B",
|
|
4770
|
-
file: "daemon-restart.sh",
|
|
4771
|
-
codeMessages: { 3: "\u91CD\u542F\u4FDD\u6D3B\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
|
|
4772
|
-
});
|
|
5099
|
+
runLaunchctlSteps(
|
|
5100
|
+
[
|
|
5101
|
+
`if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
|
|
5102
|
+
` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
|
|
5103
|
+
"fi",
|
|
5104
|
+
`if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
|
|
5105
|
+
`launchctl enable ${target} 2>/dev/null || true`,
|
|
5106
|
+
`launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`
|
|
5107
|
+
],
|
|
5108
|
+
{ action: "\u91CD\u542F\u670D\u52A1", codeMessages: { 3: "\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" } }
|
|
5109
|
+
);
|
|
4773
5110
|
cleanupOldLogs();
|
|
5111
|
+
return { hotReloaded: false };
|
|
4774
5112
|
}
|
|
4775
5113
|
|
|
4776
|
-
// src/
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4783
|
-
|
|
4784
|
-
|
|
5114
|
+
// src/runtime.ts
|
|
5115
|
+
function getRuntimeMode() {
|
|
5116
|
+
if (isServiceInstalled()) return "mixed";
|
|
5117
|
+
return getConfigInfo()?.tun ? "tun" : "mixed";
|
|
5118
|
+
}
|
|
5119
|
+
function getRunningState() {
|
|
5120
|
+
const service = getServiceStatus();
|
|
5121
|
+
if (service.running) {
|
|
5122
|
+
return { running: true, pid: service.pid, kind: "service", processInfo: null };
|
|
5123
|
+
}
|
|
5124
|
+
const status = getStatus();
|
|
5125
|
+
if (status.running) {
|
|
5126
|
+
return { running: true, pid: status.pid, kind: "tun", processInfo: status.processInfo };
|
|
5127
|
+
}
|
|
5128
|
+
return { running: false, pid: null, kind: null, processInfo: null };
|
|
5129
|
+
}
|
|
5130
|
+
function isRestartNeededOnChange() {
|
|
5131
|
+
return getRunningState().running;
|
|
5132
|
+
}
|
|
5133
|
+
async function launchOrRestart(mode) {
|
|
5134
|
+
if (mode === "tun") {
|
|
5135
|
+
const result = await startTun();
|
|
5136
|
+
return result.pid;
|
|
5137
|
+
}
|
|
5138
|
+
const status = getServiceStatus();
|
|
5139
|
+
if (status.running && !status.disabled) {
|
|
5140
|
+
const { hotReloaded } = await restartService();
|
|
5141
|
+
if (hotReloaded) return getServiceStatus().pid;
|
|
5142
|
+
} else {
|
|
5143
|
+
startService();
|
|
5144
|
+
}
|
|
5145
|
+
return assertServiceHealthy();
|
|
5146
|
+
}
|
|
5147
|
+
async function assertServiceHealthy() {
|
|
5148
|
+
const health = await waitServiceHealthy();
|
|
5149
|
+
if (health.healthy) return health.pid;
|
|
5150
|
+
const tail = readLogTail();
|
|
5151
|
+
const reason = health.crashed ? `\u5185\u6838\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${health.exitCode}\uFF09` : "\u5185\u6838\u672A\u80FD\u8FDB\u5165\u8FD0\u884C\u72B6\u6001";
|
|
5152
|
+
throw new CliError(reason, {
|
|
5153
|
+
label: "\u542F\u52A8\u5931\u8D25",
|
|
5154
|
+
hint: [
|
|
5155
|
+
...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo stop\u3002"] : [],
|
|
5156
|
+
...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
|
|
5157
|
+
"",
|
|
5158
|
+
"\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"
|
|
5159
|
+
]
|
|
5160
|
+
});
|
|
5161
|
+
}
|
|
5162
|
+
|
|
5163
|
+
// src/http.ts
|
|
5164
|
+
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5165
|
+
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5166
|
+
function createHttpClient(options = {}) {
|
|
5167
|
+
const { timeout = 6e4, secret } = options;
|
|
5168
|
+
const authHeaders = secret ? { Authorization: `Bearer ${secret}` } : {};
|
|
5169
|
+
return {
|
|
5170
|
+
async get(url, config) {
|
|
5171
|
+
const controller = new AbortController();
|
|
4785
5172
|
const timer = setTimeout(() => controller.abort(), timeout);
|
|
4786
5173
|
const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
|
|
4787
5174
|
try {
|
|
@@ -4978,7 +5365,7 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
4978
5365
|
]
|
|
4979
5366
|
});
|
|
4980
5367
|
}
|
|
4981
|
-
async function downloadSubscription(url, subName = "default", signal
|
|
5368
|
+
async function downloadSubscription(url, subName = "default", signal) {
|
|
4982
5369
|
let response;
|
|
4983
5370
|
try {
|
|
4984
5371
|
response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
|
|
@@ -5000,13 +5387,9 @@ async function downloadSubscription(url, subName = "default", signal, persist =
|
|
|
5000
5387
|
const parsed = parseYamlOrJson(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5001
5388
|
if (!parsed) throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5002
5389
|
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5003
|
-
|
|
5004
|
-
saveSubscriptionRawConfig(subName, content);
|
|
5005
|
-
}
|
|
5390
|
+
saveSubscriptionRawConfig(subName, content);
|
|
5006
5391
|
const meta = extractSubscriptionMeta(response.headers);
|
|
5007
|
-
|
|
5008
|
-
saveSubscriptionMeta(subName, meta);
|
|
5009
|
-
}
|
|
5392
|
+
saveSubscriptionMeta(subName, meta);
|
|
5010
5393
|
const proxies = parsed.proxies;
|
|
5011
5394
|
const proxyGroups = parsed["proxy-groups"];
|
|
5012
5395
|
return {
|
|
@@ -5112,320 +5495,32 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5112
5495
|
return { total: staleSubs.length, updated: updatedCount, failed: staleSubs.length - updatedCount };
|
|
5113
5496
|
}
|
|
5114
5497
|
|
|
5115
|
-
// src/commands/shared.ts
|
|
5116
|
-
import readline from "readline";
|
|
5117
|
-
|
|
5118
|
-
// src/process-start.ts
|
|
5119
|
-
import { spawn } from "child_process";
|
|
5120
|
-
import fs10 from "fs";
|
|
5121
|
-
|
|
5122
|
-
// src/process-stop.ts
|
|
5123
|
-
import { spawnSync as spawnSync4 } from "child_process";
|
|
5124
|
-
import fs9 from "fs";
|
|
5125
|
-
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
5126
|
-
var PROCESS_WAIT_INTERVAL = 100;
|
|
5127
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
5128
|
-
function clearRuntime() {
|
|
5129
|
-
if (fs9.existsSync(DIRS.runtime)) {
|
|
5130
|
-
rmrf(DIRS.runtime);
|
|
5131
|
-
}
|
|
5132
|
-
ensureDirs();
|
|
5133
|
-
}
|
|
5134
|
-
function clearPid() {
|
|
5135
|
-
if (!fs9.existsSync(PATHS.pidFile)) return;
|
|
5136
|
-
if (isPidFileOwnedByRoot()) {
|
|
5137
|
-
try {
|
|
5138
|
-
spawnSync4("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
5139
|
-
} catch {
|
|
5140
|
-
}
|
|
5141
|
-
} else {
|
|
5142
|
-
try {
|
|
5143
|
-
fs9.unlinkSync(PATHS.pidFile);
|
|
5144
|
-
} catch {
|
|
5145
|
-
}
|
|
5146
|
-
}
|
|
5147
|
-
}
|
|
5148
|
-
function killProcess(pid) {
|
|
5149
|
-
try {
|
|
5150
|
-
process.kill(pid, "SIGKILL");
|
|
5151
|
-
return true;
|
|
5152
|
-
} catch {
|
|
5153
|
-
return false;
|
|
5154
|
-
}
|
|
5155
|
-
}
|
|
5156
|
-
function killAllMihomo(forceSudo = false) {
|
|
5157
|
-
const pattern = MAIN_INSTANCE_PATTERN;
|
|
5158
|
-
if (forceSudo) {
|
|
5159
|
-
try {
|
|
5160
|
-
spawnSync4("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
|
|
5161
|
-
return true;
|
|
5162
|
-
} catch {
|
|
5163
|
-
return false;
|
|
5164
|
-
}
|
|
5165
|
-
} else {
|
|
5166
|
-
try {
|
|
5167
|
-
spawnSync4("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
|
|
5168
|
-
return true;
|
|
5169
|
-
} catch {
|
|
5170
|
-
return false;
|
|
5171
|
-
}
|
|
5172
|
-
}
|
|
5173
|
-
}
|
|
5174
|
-
async function cleanupAll(forceSudo = false) {
|
|
5175
|
-
const pids = getMihomoPids();
|
|
5176
|
-
if (pids.length === 0) {
|
|
5177
|
-
clearPid();
|
|
5178
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
5179
|
-
}
|
|
5180
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
5181
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
5182
|
-
let killedCount = 0;
|
|
5183
|
-
const failedPids = [];
|
|
5184
|
-
if (needsSudo) {
|
|
5185
|
-
const success = killAllMihomo(true);
|
|
5186
|
-
if (success) {
|
|
5187
|
-
killedCount = pids.length;
|
|
5188
|
-
} else {
|
|
5189
|
-
failedPids.push(...pids);
|
|
5190
|
-
}
|
|
5191
|
-
} else {
|
|
5192
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
5193
|
-
killAllMihomo(false);
|
|
5194
|
-
killedCount = pids.length;
|
|
5195
|
-
} else {
|
|
5196
|
-
for (const pid of pids) {
|
|
5197
|
-
if (killProcess(pid)) {
|
|
5198
|
-
killedCount++;
|
|
5199
|
-
} else {
|
|
5200
|
-
failedPids.push(pid);
|
|
5201
|
-
}
|
|
5202
|
-
}
|
|
5203
|
-
}
|
|
5204
|
-
}
|
|
5205
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
5206
|
-
if (getMihomoPids().length === 0) break;
|
|
5207
|
-
await sleep(PROCESS_WAIT_INTERVAL);
|
|
5208
|
-
}
|
|
5209
|
-
clearPid();
|
|
5210
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
5211
|
-
}
|
|
5212
|
-
async function stop(forceSudo = false) {
|
|
5213
|
-
const allPids = getMihomoPids();
|
|
5214
|
-
if (allPids.length === 0) {
|
|
5215
|
-
clearPid();
|
|
5216
|
-
clearRuntime();
|
|
5217
|
-
return { success: true, notRunning: true };
|
|
5218
|
-
}
|
|
5219
|
-
const result = await cleanupAll(forceSudo);
|
|
5220
|
-
const remaining = getMihomoPids();
|
|
5221
|
-
if (remaining.length > 0) {
|
|
5222
|
-
console.log("");
|
|
5223
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5224
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5225
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
5226
|
-
console.log("");
|
|
5227
|
-
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
5228
|
-
}
|
|
5229
|
-
clearRuntime();
|
|
5230
|
-
return { success: true, killed: result.killed };
|
|
5231
|
-
}
|
|
5232
|
-
|
|
5233
|
-
// src/process-start.ts
|
|
5234
|
-
var STARTUP_WAIT_MS = 800;
|
|
5235
|
-
var TUN_MODE_POST_WAIT_MS = 500;
|
|
5236
|
-
function savePid(pid) {
|
|
5237
|
-
ensureDirs();
|
|
5238
|
-
fs10.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
5239
|
-
}
|
|
5240
|
-
function buildTunLaunchScript() {
|
|
5241
|
-
const binary = shellQuote(PATHS.mihomoBinary);
|
|
5242
|
-
const configFile = shellQuote(PATHS.configFile);
|
|
5243
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
5244
|
-
const pidFile = shellQuote(PATHS.pidFile);
|
|
5245
|
-
const dataDir = shellQuote(DIRS.data);
|
|
5246
|
-
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
5247
|
-
return `#!/bin/bash
|
|
5248
|
-
BINARY=${binary}
|
|
5249
|
-
CONFIG_FILE=${configFile}
|
|
5250
|
-
LOG_FILE=${logFile}
|
|
5251
|
-
PID_FILE=${pidFile}
|
|
5252
|
-
DATA_DIR=${dataDir}
|
|
5253
|
-
KILL_PATTERN=${killPattern}
|
|
5254
|
-
|
|
5255
|
-
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
5256
|
-
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
5257
|
-
sleep 0.2
|
|
5258
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5259
|
-
|
|
5260
|
-
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
5261
|
-
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
5262
|
-
|
|
5263
|
-
# \u542F\u52A8
|
|
5264
|
-
cd /tmp
|
|
5265
|
-
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
5266
|
-
NEW_PID=$!
|
|
5267
|
-
echo \${NEW_PID} > "\${PID_FILE}"
|
|
5268
|
-
|
|
5269
|
-
# \u9A8C\u8BC1
|
|
5270
|
-
for i in 1 2 3 4 5; do
|
|
5271
|
-
sleep 0.4
|
|
5272
|
-
if kill -0 \${NEW_PID} 2>/dev/null; then
|
|
5273
|
-
exit 0
|
|
5274
|
-
fi
|
|
5275
|
-
done
|
|
5276
|
-
|
|
5277
|
-
# \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
|
|
5278
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
5279
|
-
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
5280
|
-
echo ""
|
|
5281
|
-
echo "--- \u65E5\u5FD7 ---"
|
|
5282
|
-
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
5283
|
-
exit 2
|
|
5284
|
-
`;
|
|
5285
|
-
}
|
|
5286
|
-
async function start(mode = "mixed") {
|
|
5287
|
-
const isTunMode = mode === "tun";
|
|
5288
|
-
ensureDirs();
|
|
5289
|
-
rotateAndCleanupLogs();
|
|
5290
|
-
const binary = PATHS.mihomoBinary;
|
|
5291
|
-
if (!fs10.existsSync(binary)) {
|
|
5292
|
-
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
5293
|
-
}
|
|
5294
|
-
const configFile = PATHS.configFile;
|
|
5295
|
-
if (!fs10.existsSync(configFile)) {
|
|
5296
|
-
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
5297
|
-
}
|
|
5298
|
-
const staleState = checkStaleState();
|
|
5299
|
-
if (isTunMode) {
|
|
5300
|
-
return startTunMode(staleState);
|
|
5301
|
-
}
|
|
5302
|
-
return startMixedMode(staleState);
|
|
5303
|
-
}
|
|
5304
|
-
async function startMixedMode(staleState) {
|
|
5305
|
-
if (staleState.needsCleanup) {
|
|
5306
|
-
if (staleState.needsSudo) {
|
|
5307
|
-
console.log("\n\u53D1\u73B0\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6");
|
|
5308
|
-
console.log(`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`);
|
|
5309
|
-
console.log("\u6216\u8005\u5207\u6362\u5230 TUN \u6A21\u5F0F\uFF0C\u542F\u52A8\u65F6\u4F1A\u81EA\u52A8\u6E05\u7406");
|
|
5310
|
-
throw new Error("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559");
|
|
5311
|
-
}
|
|
5312
|
-
const cleanupResult = await cleanupAll();
|
|
5313
|
-
if (cleanupResult.killed > 0) {
|
|
5314
|
-
console.log(`\u6E05\u7406\u4E86 ${cleanupResult.killed} \u4E2A\u6B8B\u7559\u8FDB\u7A0B`);
|
|
5315
|
-
}
|
|
5316
|
-
}
|
|
5317
|
-
if (isRunning()) {
|
|
5318
|
-
const pid2 = getPid();
|
|
5319
|
-
return { success: true, pid: pid2, alreadyRunning: true };
|
|
5320
|
-
}
|
|
5321
|
-
const configFile = PATHS.configFile;
|
|
5322
|
-
const logFile = PATHS.logFile;
|
|
5323
|
-
const args = ["-d", DIRS.data, "-f", configFile];
|
|
5324
|
-
if (fs10.existsSync(logFile)) {
|
|
5325
|
-
try {
|
|
5326
|
-
fs10.accessSync(logFile, fs10.constants.W_OK);
|
|
5327
|
-
} catch {
|
|
5328
|
-
try {
|
|
5329
|
-
fs10.unlinkSync(logFile);
|
|
5330
|
-
} catch {
|
|
5331
|
-
}
|
|
5332
|
-
}
|
|
5333
|
-
}
|
|
5334
|
-
const logFd = fs10.openSync(logFile, "a");
|
|
5335
|
-
const child = spawn(PATHS.mihomoBinary, args, {
|
|
5336
|
-
detached: true,
|
|
5337
|
-
stdio: ["ignore", logFd, logFd]
|
|
5338
|
-
});
|
|
5339
|
-
child.on("error", () => {
|
|
5340
|
-
});
|
|
5341
|
-
fs10.closeSync(logFd);
|
|
5342
|
-
child.unref();
|
|
5343
|
-
const pid = child.pid;
|
|
5344
|
-
if (!pid) {
|
|
5345
|
-
clearPid();
|
|
5346
|
-
throw new Error("\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u5185\u6838\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
|
|
5347
|
-
}
|
|
5348
|
-
savePid(pid);
|
|
5349
|
-
await new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS));
|
|
5350
|
-
if (!isRunning()) {
|
|
5351
|
-
clearPid();
|
|
5352
|
-
let errorMsg = "\u542F\u52A8\u5931\u8D25";
|
|
5353
|
-
if (fs10.existsSync(logFile)) {
|
|
5354
|
-
try {
|
|
5355
|
-
const logs = fs10.readFileSync(logFile, "utf8").slice(-3e3);
|
|
5356
|
-
if (logs.trim()) {
|
|
5357
|
-
errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
|
|
5358
|
-
}
|
|
5359
|
-
} catch {
|
|
5360
|
-
}
|
|
5361
|
-
}
|
|
5362
|
-
throw new Error(errorMsg);
|
|
5363
|
-
}
|
|
5364
|
-
return { success: true, pid, mode: "mixed" };
|
|
5365
|
-
}
|
|
5366
|
-
async function startTunMode(staleState) {
|
|
5367
|
-
if (staleState.needsCleanup) {
|
|
5368
|
-
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
5369
|
-
}
|
|
5370
|
-
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
5371
|
-
runSudoScript(buildTunLaunchScript(), {
|
|
5372
|
-
action: "TUN \u542F\u52A8",
|
|
5373
|
-
file: "launch-tun.sh",
|
|
5374
|
-
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
5375
|
-
});
|
|
5376
|
-
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
5377
|
-
const finalPid = getPid();
|
|
5378
|
-
if (!finalPid) {
|
|
5379
|
-
throw new Error("TUN \u542F\u52A8\u5931\u8D25");
|
|
5380
|
-
}
|
|
5381
|
-
return { success: true, pid: finalPid, mode: "tun" };
|
|
5382
|
-
}
|
|
5383
|
-
|
|
5384
|
-
// src/runtime.ts
|
|
5385
|
-
function getRuntimeMode() {
|
|
5386
|
-
if (isDaemonEnabled()) return "mixed";
|
|
5387
|
-
return getConfigInfo()?.tun ? "tun" : "mixed";
|
|
5388
|
-
}
|
|
5389
|
-
function getRunningState() {
|
|
5390
|
-
if (isDaemonEnabled()) {
|
|
5391
|
-
const daemon = getDaemonStatus();
|
|
5392
|
-
return { running: isDaemonRunning(daemon), pid: daemon.pid, daemon: true, processInfo: null };
|
|
5393
|
-
}
|
|
5394
|
-
const status = getStatus();
|
|
5395
|
-
return { running: status.running, pid: status.pid, daemon: false, processInfo: status.processInfo };
|
|
5396
|
-
}
|
|
5397
|
-
function isRestartNeededOnChange() {
|
|
5398
|
-
return isDaemonEnabled() || getStatus().running;
|
|
5399
|
-
}
|
|
5400
|
-
async function launchOrRestart(mode) {
|
|
5401
|
-
if (isDaemonEnabled()) {
|
|
5402
|
-
await restartDaemon();
|
|
5403
|
-
await sleep(DAEMON_BOOT_WAIT_MS);
|
|
5404
|
-
return getDaemonStatus().pid;
|
|
5405
|
-
}
|
|
5406
|
-
const result = await start(mode);
|
|
5407
|
-
return result.pid;
|
|
5408
|
-
}
|
|
5409
|
-
|
|
5410
5498
|
// src/commands/status.ts
|
|
5411
5499
|
async function printStatus() {
|
|
5412
5500
|
const state = getRunningState();
|
|
5501
|
+
const service = getServiceStatus();
|
|
5413
5502
|
const info = getConfigInfo();
|
|
5414
5503
|
const overwriteEnabled = isOverwriteEnabled();
|
|
5415
5504
|
const overwriteFiles = listOverwriteFile().files;
|
|
5416
5505
|
const activeSub = getActiveSubscription();
|
|
5417
|
-
const { running, pid,
|
|
5506
|
+
const { running, pid, kind, processInfo } = state;
|
|
5418
5507
|
console.log("");
|
|
5419
5508
|
let modeLabel = "";
|
|
5420
5509
|
if (info) {
|
|
5421
|
-
|
|
5510
|
+
const mode = info.tun ? "TUN" : "Mixed";
|
|
5511
|
+
const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
|
|
5512
|
+
modeLabel = colors.cyan(` (${mode}${carrier})`);
|
|
5422
5513
|
}
|
|
5423
5514
|
const statusText = running ? colors.green("\u25CF \u8FD0\u884C\u4E2D") : colors.yellow("\u4E0D\u5728\u8FD0\u884C");
|
|
5424
5515
|
console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}${modeLabel}`);
|
|
5516
|
+
if (!running && service.installed && !service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
|
|
5517
|
+
console.log(colors.yellow(` \u5F02\u5E38: \u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`));
|
|
5518
|
+
console.log(colors.gray(" \u67E5\u770B\u539F\u56E0: mihomo logs 0 \u505C\u6B62\u91CD\u8BD5: mihomo stop"));
|
|
5519
|
+
}
|
|
5425
5520
|
console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
|
|
5426
5521
|
if (pid) {
|
|
5427
5522
|
console.log(`${colors.gray("PID: ")}${pid}`);
|
|
5428
|
-
if (
|
|
5523
|
+
if (kind === "tun" && processInfo) {
|
|
5429
5524
|
console.log(`${colors.gray("\u5185\u5B58: ")}${processInfo.memory}`);
|
|
5430
5525
|
}
|
|
5431
5526
|
}
|
|
@@ -5467,33 +5562,29 @@ async function printStatus() {
|
|
|
5467
5562
|
} else {
|
|
5468
5563
|
console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
|
|
5469
5564
|
}
|
|
5470
|
-
|
|
5471
|
-
console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
|
|
5472
|
-
}
|
|
5565
|
+
printServiceLines(service);
|
|
5473
5566
|
console.log("");
|
|
5474
5567
|
}
|
|
5475
|
-
|
|
5476
|
-
|
|
5477
|
-
|
|
5478
|
-
|
|
5479
|
-
|
|
5568
|
+
function printServiceLines(service) {
|
|
5569
|
+
const legacy = detectLegacySystemInstall();
|
|
5570
|
+
if (!service.installed && !service.loaded) {
|
|
5571
|
+
console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
|
|
5572
|
+
} else if (!service.installed) {
|
|
5573
|
+
console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u5F02\u5E38")} ${colors.gray("(plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001)")}`);
|
|
5574
|
+
console.log(colors.gray(" KeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838\uFF0C\u6E05\u7406: mihomo uninstall"));
|
|
5575
|
+
printAutoStart(service);
|
|
5576
|
+
} else {
|
|
5577
|
+
console.log(`${colors.gray("\u670D\u52A1: ")}${colors.green("\u5DF2\u5B89\u88C5")}`);
|
|
5578
|
+
printAutoStart(service);
|
|
5480
5579
|
}
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
if (isDaemonEnabled()) {
|
|
5485
|
-
console.log(colors.yellow("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF0C\u4EE3\u7406\u7531 launchd \u6258\u7BA1"));
|
|
5486
|
-
console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
|
|
5487
|
-
return;
|
|
5580
|
+
if (legacy) {
|
|
5581
|
+
console.log(colors.yellow(" \u5F02\u5E38: \u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
|
|
5582
|
+
console.log(colors.gray(" \u5B83\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u6E05\u7406: mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
5488
5583
|
}
|
|
5489
|
-
|
|
5490
|
-
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
}
|
|
5494
|
-
console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
|
|
5495
|
-
handleStopResult(await stop());
|
|
5496
|
-
console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
|
|
5584
|
+
}
|
|
5585
|
+
function printAutoStart(service) {
|
|
5586
|
+
const autoStart = service.disabled ? colors.yellow("\u5DF2\u5173\u95ED") : colors.green("\u5DF2\u5F00\u542F");
|
|
5587
|
+
console.log(`${colors.gray("\u81EA\u542F: ")}${autoStart}`);
|
|
5497
5588
|
}
|
|
5498
5589
|
|
|
5499
5590
|
// src/commands/start.ts
|
|
@@ -5509,14 +5600,27 @@ async function cmdStart(args) {
|
|
|
5509
5600
|
assertNoRemovedSshFlag(args);
|
|
5510
5601
|
const targetMode = resolveStartMode(args);
|
|
5511
5602
|
if (!hasKernel()) {
|
|
5512
|
-
throw new CliError(
|
|
5513
|
-
}
|
|
5514
|
-
const daemonEnabled = isDaemonEnabled();
|
|
5515
|
-
if (targetMode === "tun" && daemonEnabled) {
|
|
5516
|
-
throw new CliError("\u4FDD\u6D3B\u5DF2\u542F\u7528\uFF08\u4EC5\u652F\u6301 Mixed \u6A21\u5F0F\uFF09\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", { hint: "\u8BF7\u5148\u5173\u95ED\u4FDD\u6D3B: mihomo daemon off" });
|
|
5603
|
+
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
5517
5604
|
}
|
|
5518
5605
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
5519
5606
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
5607
|
+
const serviceBefore = getServiceStatus();
|
|
5608
|
+
if (targetMode === "tun") {
|
|
5609
|
+
if (serviceBefore.loaded) {
|
|
5610
|
+
throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
|
|
5611
|
+
hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D\u670D\u52A1"]
|
|
5612
|
+
});
|
|
5613
|
+
}
|
|
5614
|
+
} else if (!serviceBefore.installed) {
|
|
5615
|
+
if (serviceBefore.loaded) {
|
|
5616
|
+
throw new CliError("\u670D\u52A1\u5904\u4E8E\u5F02\u5E38\u72B6\u6001\uFF08plist \u4E0D\u5B58\u5728\uFF0C\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09", {
|
|
5617
|
+
hint: ["\u5148\u6E05\u7406\u6B8B\u7559\u4EFB\u52A1\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:", " mihomo uninstall", " mihomo install"]
|
|
5618
|
+
});
|
|
5619
|
+
}
|
|
5620
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", {
|
|
5621
|
+
hint: ["Mixed \u6A21\u5F0F\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u9700\u5148\u5B89\u88C5:", " mihomo install", "", "\u4E34\u65F6\u4F7F\u7528\u53EF\u8D70 TUN: mihomo tun"]
|
|
5622
|
+
});
|
|
5623
|
+
}
|
|
5520
5624
|
const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
5521
5625
|
if (!skipUpdate) {
|
|
5522
5626
|
await autoUpdateStaleSubscription({ timeout: updateTimeout });
|
|
@@ -5528,31 +5632,12 @@ async function cmdStart(args) {
|
|
|
5528
5632
|
if (e instanceof CliError) throw e;
|
|
5529
5633
|
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
5530
5634
|
}
|
|
5531
|
-
if (!daemonEnabled) {
|
|
5532
|
-
if (targetMode !== "tun" && hasRootResidue()) {
|
|
5533
|
-
throw new CliError("\u5B58\u5728\u9700\u8981 root \u6743\u9650\u6E05\u7406\u7684\u6B8B\u7559\u8FDB\u7A0B/\u6587\u4EF6", {
|
|
5534
|
-
hint: [`\u8BF7\u5148\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo && sudo rm -f ${PATHS.pidFile}`, "\u6216\u5207\u6362\u5230 TUN \u6A21\u5F0F\u542F\u52A8\uFF08\u81EA\u52A8\u6E05\u7406\uFF09: mihomo start tun"]
|
|
5535
|
-
});
|
|
5536
|
-
}
|
|
5537
|
-
const status = getStatus();
|
|
5538
|
-
const hasProcess = status.running || status.allProcesses.length > 0;
|
|
5539
|
-
if (hasProcess) {
|
|
5540
|
-
const count = status.allProcesses.length > 0 ? status.allProcesses.length : 1;
|
|
5541
|
-
console.log(`\u505C\u6B62 ${count} \u4E2A\u8FDB\u7A0B...`);
|
|
5542
|
-
}
|
|
5543
|
-
handleStopResult(await stop());
|
|
5544
|
-
if (hasProcess) {
|
|
5545
|
-
console.log(`${colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B")}
|
|
5546
|
-
`);
|
|
5547
|
-
}
|
|
5548
|
-
}
|
|
5549
5635
|
const configInfo = commitPreparedConfig(prepared);
|
|
5550
5636
|
const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
|
|
5551
5637
|
console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
5552
5638
|
try {
|
|
5553
5639
|
const pid = await launchOrRestart(targetMode);
|
|
5554
|
-
|
|
5555
|
-
console.log(`${colors.green(label)}${pid ? ` (PID ${pid})` : ""}`);
|
|
5640
|
+
console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
|
|
5556
5641
|
} catch (e) {
|
|
5557
5642
|
if (e instanceof CliError) throw e;
|
|
5558
5643
|
const lines = e.message.split("\n");
|
|
@@ -5575,179 +5660,25 @@ async function confirmPrompt(question) {
|
|
|
5575
5660
|
if (!process.stdin.isTTY) return false;
|
|
5576
5661
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
5577
5662
|
const answer = await new Promise((resolve) => {
|
|
5578
|
-
rl.question(`${question} (y/N) `, (a) => {
|
|
5579
|
-
rl.close();
|
|
5580
|
-
resolve(a);
|
|
5581
|
-
});
|
|
5582
|
-
});
|
|
5583
|
-
return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
|
|
5584
|
-
}
|
|
5585
|
-
async function confirmOrThrow(question, opts) {
|
|
5586
|
-
if (!process.stdin.isTTY) {
|
|
5587
|
-
throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
|
|
5588
|
-
}
|
|
5589
|
-
return confirmPrompt(question);
|
|
5590
|
-
}
|
|
5591
|
-
async function restartToApply(args) {
|
|
5592
|
-
if (!isRestartNeededOnChange()) return false;
|
|
5593
|
-
const currentMode = getRuntimeMode();
|
|
5594
|
-
console.log("");
|
|
5595
|
-
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
5596
|
-
return true;
|
|
5597
|
-
}
|
|
5598
|
-
|
|
5599
|
-
// src/commands/daemon.ts
|
|
5600
|
-
function printDaemonStatus() {
|
|
5601
|
-
const status = getDaemonStatus();
|
|
5602
|
-
const stateText = status.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
|
|
5603
|
-
console.log(`${colors.gray("\u4FDD\u6D3B: ")}${stateText}`);
|
|
5604
|
-
if (status.enabled) {
|
|
5605
|
-
const runText = isDaemonRunning(status) ? colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`) : colors.yellow("\u672A\u8FD0\u884C");
|
|
5606
|
-
console.log(`${colors.gray("\u5185\u6838: ")}${runText}`);
|
|
5607
|
-
}
|
|
5608
|
-
console.log("");
|
|
5609
|
-
if (status.enabled) {
|
|
5610
|
-
console.log("\u5173\u95ED\u4FDD\u6D3B: mihomo daemon off");
|
|
5611
|
-
} else {
|
|
5612
|
-
console.log("\u5F00\u542F\u4FDD\u6D3B: mihomo daemon on");
|
|
5613
|
-
console.log(colors.gray(" \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF08\u4EC5 Mixed \u6A21\u5F0F\uFF09"));
|
|
5614
|
-
}
|
|
5615
|
-
console.log("");
|
|
5616
|
-
}
|
|
5617
|
-
async function daemonOn() {
|
|
5618
|
-
if (!hasKernel()) {
|
|
5619
|
-
throw new CliError('\u672A\u627E\u5230\u5185\u6838\uFF0C\u8BF7\u8FD0\u884C "mihomo kernel"');
|
|
5620
|
-
}
|
|
5621
|
-
const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
5622
|
-
let configInfo;
|
|
5623
|
-
try {
|
|
5624
|
-
configInfo = commitPreparedConfig(prepareConfigForStart("mixed", sub.name));
|
|
5625
|
-
} catch (e) {
|
|
5626
|
-
if (e instanceof CliError) throw e;
|
|
5627
|
-
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
5628
|
-
}
|
|
5629
|
-
console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u5B89\u88C5\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1\uFF08LaunchDaemon\uFF09"));
|
|
5630
|
-
console.log(colors.gray("\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u9700\u8981 root\uFF0C\u4EE5\u89E3\u51B3\u5C40\u57DF\u7F51\u8BBF\u95EE\u53D7\u9650\u95EE\u9898"));
|
|
5631
|
-
try {
|
|
5632
|
-
enableDaemon();
|
|
5633
|
-
} catch (e) {
|
|
5634
|
-
if (e instanceof CliError) throw e;
|
|
5635
|
-
throw new CliError(e.message, { label: "\u542F\u7528\u4FDD\u6D3B\u5931\u8D25" });
|
|
5636
|
-
}
|
|
5637
|
-
console.log(`${colors.green("\u5DF2\u542F\u7528\u4FDD\u6D3B")} \xB7 ${sub.name} \xB7 ${formatProxySummary(configInfo)}`);
|
|
5638
|
-
console.log(colors.gray("\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF0C\u4EE3\u7406\u5C06\u5728\u540E\u53F0\u5E38\u9A7B"));
|
|
5639
|
-
console.log("");
|
|
5640
|
-
await sleep(DAEMON_BOOT_WAIT_MS);
|
|
5641
|
-
printDaemonStatus();
|
|
5642
|
-
}
|
|
5643
|
-
function daemonOff() {
|
|
5644
|
-
const residualRootKernel = getMihomoPids().some(isProcessRoot);
|
|
5645
|
-
if (!isDaemonEnabled() && !residualRootKernel) {
|
|
5646
|
-
console.log("\u4FDD\u6D3B\u5DF2\u662F\u5173\u95ED\u72B6\u6001");
|
|
5647
|
-
console.log("");
|
|
5648
|
-
printDaemonStatus();
|
|
5649
|
-
return;
|
|
5650
|
-
}
|
|
5651
|
-
console.log(colors.gray("\u5C06\u8BF7\u6C42\u7BA1\u7406\u5458\u6743\u9650\u4EE5\u79FB\u9664\u7CFB\u7EDF\u7EA7\u4FDD\u6D3B\u670D\u52A1"));
|
|
5652
|
-
try {
|
|
5653
|
-
disableDaemon();
|
|
5654
|
-
} catch (e) {
|
|
5655
|
-
if (e instanceof CliError) throw e;
|
|
5656
|
-
throw new CliError(e.message, { label: "\u5173\u95ED\u4FDD\u6D3B\u5931\u8D25" });
|
|
5657
|
-
}
|
|
5658
|
-
console.log(`${colors.green("\u5DF2\u5173\u95ED\u4FDD\u6D3B")}\uFF0C\u4EE3\u7406\u5DF2\u505C\u6B62`);
|
|
5659
|
-
console.log(colors.gray("\u91CD\u65B0\u542F\u7528: mihomo daemon on"));
|
|
5660
|
-
console.log("");
|
|
5661
|
-
}
|
|
5662
|
-
var SUBCOMMANDS = [
|
|
5663
|
-
{ name: "on", aliases: ["enable"], handler: daemonOn },
|
|
5664
|
-
{ name: "off", aliases: ["disable"], handler: daemonOff }
|
|
5665
|
-
];
|
|
5666
|
-
async function cmdDaemon(args) {
|
|
5667
|
-
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
5668
|
-
// 无 action → 显示状态;未知 action → 报错
|
|
5669
|
-
fallback: () => {
|
|
5670
|
-
console.log("");
|
|
5671
|
-
printDaemonStatus();
|
|
5672
|
-
},
|
|
5673
|
-
onUnknown: (action) => {
|
|
5674
|
-
const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
5675
|
-
const suggestion = suggestSimilar(action, names);
|
|
5676
|
-
throw new CliError(`\u672A\u77E5\u7684 daemon \u5B50\u547D\u4EE4: ${action}`, {
|
|
5677
|
-
hint: [
|
|
5678
|
-
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
5679
|
-
"",
|
|
5680
|
-
"\u53EF\u7528\u5B50\u547D\u4EE4: on, off",
|
|
5681
|
-
"\u67E5\u770B\u4FDD\u6D3B\u72B6\u6001: mihomo daemon\uFF08\u65E0\u53C2\uFF09\u6216 mihomo status"
|
|
5682
|
-
]
|
|
5683
|
-
});
|
|
5684
|
-
}
|
|
5685
|
-
});
|
|
5686
|
-
}
|
|
5687
|
-
|
|
5688
|
-
// src/open.ts
|
|
5689
|
-
import { spawn as spawn2 } from "child_process";
|
|
5690
|
-
|
|
5691
|
-
// src/lifecycle.ts
|
|
5692
|
-
var cleanupFns = /* @__PURE__ */ new Set();
|
|
5693
|
-
var silentSigint = false;
|
|
5694
|
-
function setSilentSigint(value) {
|
|
5695
|
-
silentSigint = value;
|
|
5696
|
-
}
|
|
5697
|
-
function isSilentSigint() {
|
|
5698
|
-
return silentSigint;
|
|
5699
|
-
}
|
|
5700
|
-
function runCleanup() {
|
|
5701
|
-
for (const fn of cleanupFns) {
|
|
5702
|
-
try {
|
|
5703
|
-
fn();
|
|
5704
|
-
} catch {
|
|
5705
|
-
}
|
|
5706
|
-
}
|
|
5707
|
-
cleanupFns.clear();
|
|
5708
|
-
}
|
|
5709
|
-
|
|
5710
|
-
// src/open.ts
|
|
5711
|
-
function openUrl(url) {
|
|
5712
|
-
try {
|
|
5713
|
-
const child = spawn2("open", ["--", url], { stdio: "ignore", detached: true });
|
|
5714
|
-
child.unref();
|
|
5715
|
-
child.on("error", () => {
|
|
5663
|
+
rl.question(`${question} (y/N) `, (a) => {
|
|
5664
|
+
rl.close();
|
|
5665
|
+
resolve(a);
|
|
5716
5666
|
});
|
|
5717
|
-
|
|
5718
|
-
|
|
5719
|
-
return false;
|
|
5720
|
-
}
|
|
5667
|
+
});
|
|
5668
|
+
return answer.toLowerCase() === "y" || answer.toLowerCase() === "yes";
|
|
5721
5669
|
}
|
|
5722
|
-
function
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
const success = openUrl(logPath);
|
|
5726
|
-
if (!success) {
|
|
5727
|
-
console.log(`\u8BF7\u624B\u52A8\u6253\u5F00: ${logPath}`);
|
|
5670
|
+
async function confirmOrThrow(question, opts) {
|
|
5671
|
+
if (!process.stdin.isTTY) {
|
|
5672
|
+
throw new CliError(opts.nonTtyMessage, { label: "\u5DF2\u53D6\u6D88", hint: opts.hint });
|
|
5728
5673
|
}
|
|
5674
|
+
return confirmPrompt(question);
|
|
5729
5675
|
}
|
|
5730
|
-
function
|
|
5731
|
-
|
|
5732
|
-
const
|
|
5733
|
-
console.log(
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
} else {
|
|
5737
|
-
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
5738
|
-
`);
|
|
5739
|
-
}
|
|
5740
|
-
const tailArgs = [];
|
|
5741
|
-
if (follow) tailArgs.push("-f");
|
|
5742
|
-
tailArgs.push("-n", lines.toString());
|
|
5743
|
-
tailArgs.push(logPath);
|
|
5744
|
-
const tail = spawn2("tail", tailArgs, { stdio: "inherit" });
|
|
5745
|
-
if (follow) setSilentSigint(true);
|
|
5746
|
-
tail.on("close", (code, signal) => process.exit(signal ? 0 : code ?? 0));
|
|
5747
|
-
tail.on("error", (e) => {
|
|
5748
|
-
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5749
|
-
process.exit(1);
|
|
5750
|
-
});
|
|
5676
|
+
async function restartToApply(args) {
|
|
5677
|
+
if (!isRestartNeededOnChange()) return false;
|
|
5678
|
+
const currentMode = getRuntimeMode();
|
|
5679
|
+
console.log("");
|
|
5680
|
+
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
5681
|
+
return true;
|
|
5751
5682
|
}
|
|
5752
5683
|
|
|
5753
5684
|
// src/commands/directory.ts
|
|
@@ -5795,12 +5726,12 @@ function printDirectoryInfo() {
|
|
|
5795
5726
|
console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
|
|
5796
5727
|
console.log("");
|
|
5797
5728
|
}
|
|
5798
|
-
var
|
|
5729
|
+
var SUBCOMMANDS = [{ name: "open", handler: openDirectory }];
|
|
5799
5730
|
async function cmdDirectory(args) {
|
|
5800
|
-
await dispatchSubcommand(args,
|
|
5731
|
+
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
5801
5732
|
fallback: printDirectoryInfo,
|
|
5802
5733
|
onUnknown: (action) => {
|
|
5803
|
-
const names =
|
|
5734
|
+
const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
5804
5735
|
const suggestion = suggestSimilar(action, names);
|
|
5805
5736
|
throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
|
|
5806
5737
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
|
|
@@ -5811,10 +5742,10 @@ async function cmdDirectory(args) {
|
|
|
5811
5742
|
|
|
5812
5743
|
// src/kernel.ts
|
|
5813
5744
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
5814
|
-
import
|
|
5745
|
+
import fs10 from "fs";
|
|
5815
5746
|
import path7 from "path";
|
|
5816
5747
|
|
|
5817
|
-
//
|
|
5748
|
+
// node_modules/compare-versions/lib/esm/utils.js
|
|
5818
5749
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
5819
5750
|
var validateAndParse = (version) => {
|
|
5820
5751
|
if (typeof version !== "string") {
|
|
@@ -5852,7 +5783,7 @@ var compareSegments = (a, b) => {
|
|
|
5852
5783
|
return 0;
|
|
5853
5784
|
};
|
|
5854
5785
|
|
|
5855
|
-
//
|
|
5786
|
+
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
5856
5787
|
var compareVersions = (v1, v2) => {
|
|
5857
5788
|
const n1 = validateAndParse(v1);
|
|
5858
5789
|
const n2 = validateAndParse(v2);
|
|
@@ -5955,10 +5886,10 @@ async function checkUpdate() {
|
|
|
5955
5886
|
}
|
|
5956
5887
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
5957
5888
|
if (maxDepth <= 0) return null;
|
|
5958
|
-
const files =
|
|
5889
|
+
const files = fs10.readdirSync(dir);
|
|
5959
5890
|
for (const f of files) {
|
|
5960
5891
|
const fullPath = path7.join(dir, f);
|
|
5961
|
-
const stat =
|
|
5892
|
+
const stat = fs10.lstatSync(fullPath);
|
|
5962
5893
|
if (stat.isDirectory()) {
|
|
5963
5894
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
5964
5895
|
if (found) return found;
|
|
@@ -6024,19 +5955,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6024
5955
|
}
|
|
6025
5956
|
if (curlResult.status !== 0) {
|
|
6026
5957
|
try {
|
|
6027
|
-
|
|
5958
|
+
fs10.unlinkSync(tempPath);
|
|
6028
5959
|
} catch {
|
|
6029
5960
|
}
|
|
6030
5961
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
6031
5962
|
}
|
|
6032
|
-
if (!
|
|
5963
|
+
if (!fs10.existsSync(tempPath)) {
|
|
6033
5964
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
6034
5965
|
}
|
|
6035
5966
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
6036
|
-
const actual =
|
|
5967
|
+
const actual = fs10.statSync(tempPath).size;
|
|
6037
5968
|
if (actual !== asset.size) {
|
|
6038
5969
|
try {
|
|
6039
|
-
|
|
5970
|
+
fs10.unlinkSync(tempPath);
|
|
6040
5971
|
} catch {
|
|
6041
5972
|
}
|
|
6042
5973
|
throw new Error(
|
|
@@ -6081,12 +6012,12 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6081
6012
|
const gzipResult = spawnSync5("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
6082
6013
|
if (gzipResult.error) throw gzipResult.error;
|
|
6083
6014
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
6084
|
-
|
|
6015
|
+
fs10.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
6085
6016
|
extractedBinary = outputPath;
|
|
6086
6017
|
}
|
|
6087
6018
|
} catch (e) {
|
|
6088
6019
|
try {
|
|
6089
|
-
|
|
6020
|
+
fs10.unlinkSync(tempPath);
|
|
6090
6021
|
} catch {
|
|
6091
6022
|
}
|
|
6092
6023
|
throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
|
|
@@ -6094,23 +6025,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6094
6025
|
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
6095
6026
|
if (!foundBinary) {
|
|
6096
6027
|
try {
|
|
6097
|
-
|
|
6028
|
+
fs10.unlinkSync(tempPath);
|
|
6098
6029
|
} catch {
|
|
6099
6030
|
}
|
|
6100
6031
|
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
6101
6032
|
}
|
|
6102
6033
|
const targetPath = PATHS.mihomoBinary;
|
|
6103
6034
|
if (foundBinary !== targetPath) {
|
|
6104
|
-
if (
|
|
6105
|
-
|
|
6035
|
+
if (fs10.existsSync(targetPath)) {
|
|
6036
|
+
fs10.chmodSync(targetPath, 493);
|
|
6106
6037
|
try {
|
|
6107
|
-
|
|
6038
|
+
fs10.unlinkSync(targetPath);
|
|
6108
6039
|
} catch {
|
|
6109
6040
|
}
|
|
6110
6041
|
}
|
|
6111
|
-
|
|
6042
|
+
fs10.renameSync(foundBinary, targetPath);
|
|
6112
6043
|
}
|
|
6113
|
-
|
|
6044
|
+
fs10.chmodSync(targetPath, 493);
|
|
6114
6045
|
if (progressCallback) {
|
|
6115
6046
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
6116
6047
|
}
|
|
@@ -6118,11 +6049,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6118
6049
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
6119
6050
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
6120
6051
|
try {
|
|
6121
|
-
|
|
6052
|
+
fs10.unlinkSync(targetPath);
|
|
6122
6053
|
} catch {
|
|
6123
6054
|
}
|
|
6124
6055
|
try {
|
|
6125
|
-
|
|
6056
|
+
fs10.unlinkSync(tempPath);
|
|
6126
6057
|
} catch {
|
|
6127
6058
|
}
|
|
6128
6059
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
|
|
@@ -6130,7 +6061,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6130
6061
|
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
6131
6062
|
}
|
|
6132
6063
|
try {
|
|
6133
|
-
|
|
6064
|
+
fs10.unlinkSync(tempPath);
|
|
6134
6065
|
} catch {
|
|
6135
6066
|
}
|
|
6136
6067
|
clearKernelVersionCache();
|
|
@@ -6315,19 +6246,19 @@ async function setOverwrite(enabled, args) {
|
|
|
6315
6246
|
console.log("");
|
|
6316
6247
|
printOverwriteList();
|
|
6317
6248
|
}
|
|
6318
|
-
var
|
|
6249
|
+
var SUBCOMMANDS2 = [
|
|
6319
6250
|
{ name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
|
|
6320
6251
|
{ name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
|
|
6321
6252
|
];
|
|
6322
6253
|
async function cmdOverwrite(args) {
|
|
6323
|
-
await dispatchSubcommand(args,
|
|
6324
|
-
// 无子命令 → 列表;未知子命令 → 报错(与 sub/
|
|
6254
|
+
await dispatchSubcommand(args, SUBCOMMANDS2, {
|
|
6255
|
+
// 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
|
|
6325
6256
|
fallback: () => {
|
|
6326
6257
|
console.log("");
|
|
6327
6258
|
printOverwriteList();
|
|
6328
6259
|
},
|
|
6329
6260
|
onUnknown: (action) => {
|
|
6330
|
-
const names =
|
|
6261
|
+
const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6331
6262
|
const suggestion = suggestSimilar(action, names);
|
|
6332
6263
|
throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
|
|
6333
6264
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
|
|
@@ -6336,8 +6267,128 @@ async function cmdOverwrite(args) {
|
|
|
6336
6267
|
});
|
|
6337
6268
|
}
|
|
6338
6269
|
|
|
6270
|
+
// src/commands/removed.ts
|
|
6271
|
+
function removedCommand(name, version, hint) {
|
|
6272
|
+
return () => {
|
|
6273
|
+
throw new CliError(`${name} \u5DF2\u79FB\u9664\uFF08${version}\uFF09`, { label: "\u547D\u4EE4\u4E0D\u5B58\u5728", hint });
|
|
6274
|
+
};
|
|
6275
|
+
}
|
|
6276
|
+
|
|
6339
6277
|
// src/commands/reset.ts
|
|
6340
6278
|
import fs12 from "fs";
|
|
6279
|
+
|
|
6280
|
+
// src/process-stop.ts
|
|
6281
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6282
|
+
import fs11 from "fs";
|
|
6283
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6284
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
6285
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
6286
|
+
function clearRuntime() {
|
|
6287
|
+
if (fs11.existsSync(DIRS.runtime)) {
|
|
6288
|
+
rmrf(DIRS.runtime);
|
|
6289
|
+
}
|
|
6290
|
+
ensureDirs();
|
|
6291
|
+
}
|
|
6292
|
+
function clearPid() {
|
|
6293
|
+
if (!fs11.existsSync(PATHS.pidFile)) return;
|
|
6294
|
+
if (isPidFileOwnedByRoot()) {
|
|
6295
|
+
try {
|
|
6296
|
+
spawnSync6("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
6297
|
+
} catch {
|
|
6298
|
+
}
|
|
6299
|
+
} else {
|
|
6300
|
+
try {
|
|
6301
|
+
fs11.unlinkSync(PATHS.pidFile);
|
|
6302
|
+
} catch {
|
|
6303
|
+
}
|
|
6304
|
+
}
|
|
6305
|
+
}
|
|
6306
|
+
function killProcess(pid) {
|
|
6307
|
+
try {
|
|
6308
|
+
process.kill(pid, "SIGKILL");
|
|
6309
|
+
return true;
|
|
6310
|
+
} catch {
|
|
6311
|
+
return false;
|
|
6312
|
+
}
|
|
6313
|
+
}
|
|
6314
|
+
function killAllMihomo(forceSudo = false) {
|
|
6315
|
+
const pattern = MAIN_INSTANCE_PATTERN;
|
|
6316
|
+
if (forceSudo) {
|
|
6317
|
+
try {
|
|
6318
|
+
spawnSync6("sudo", ["pkill", "-9", "-f", pattern], { stdio: "inherit", timeout: 15e3 });
|
|
6319
|
+
return true;
|
|
6320
|
+
} catch {
|
|
6321
|
+
return false;
|
|
6322
|
+
}
|
|
6323
|
+
} else {
|
|
6324
|
+
try {
|
|
6325
|
+
spawnSync6("pkill", ["-9", "-f", pattern], { timeout: 1e4 });
|
|
6326
|
+
return true;
|
|
6327
|
+
} catch {
|
|
6328
|
+
return false;
|
|
6329
|
+
}
|
|
6330
|
+
}
|
|
6331
|
+
}
|
|
6332
|
+
async function cleanupAll(forceSudo = false) {
|
|
6333
|
+
const pids = getMihomoPids();
|
|
6334
|
+
if (pids.length === 0) {
|
|
6335
|
+
clearPid();
|
|
6336
|
+
return { killed: 0, failed: 0, remaining: [] };
|
|
6337
|
+
}
|
|
6338
|
+
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
6339
|
+
const needsSudo = forceSudo || hasRootProcess;
|
|
6340
|
+
let killedCount = 0;
|
|
6341
|
+
const failedPids = [];
|
|
6342
|
+
if (needsSudo) {
|
|
6343
|
+
const success = killAllMihomo(true);
|
|
6344
|
+
if (success) {
|
|
6345
|
+
killedCount = pids.length;
|
|
6346
|
+
} else {
|
|
6347
|
+
failedPids.push(...pids);
|
|
6348
|
+
}
|
|
6349
|
+
} else {
|
|
6350
|
+
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
6351
|
+
killAllMihomo(false);
|
|
6352
|
+
killedCount = pids.length;
|
|
6353
|
+
} else {
|
|
6354
|
+
for (const pid of pids) {
|
|
6355
|
+
if (killProcess(pid)) {
|
|
6356
|
+
killedCount++;
|
|
6357
|
+
} else {
|
|
6358
|
+
failedPids.push(pid);
|
|
6359
|
+
}
|
|
6360
|
+
}
|
|
6361
|
+
}
|
|
6362
|
+
}
|
|
6363
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6364
|
+
if (getMihomoPids().length === 0) break;
|
|
6365
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
6366
|
+
}
|
|
6367
|
+
clearPid();
|
|
6368
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
6369
|
+
}
|
|
6370
|
+
async function stop(forceSudo = false) {
|
|
6371
|
+
const allPids = getMihomoPids();
|
|
6372
|
+
if (allPids.length === 0) {
|
|
6373
|
+
clearPid();
|
|
6374
|
+
clearRuntime();
|
|
6375
|
+
return { success: true, notRunning: true };
|
|
6376
|
+
}
|
|
6377
|
+
const result = await cleanupAll(forceSudo);
|
|
6378
|
+
const remaining = getMihomoPids();
|
|
6379
|
+
if (remaining.length > 0) {
|
|
6380
|
+
console.log("");
|
|
6381
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
6382
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
6383
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
6384
|
+
console.log("");
|
|
6385
|
+
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
6386
|
+
}
|
|
6387
|
+
clearRuntime();
|
|
6388
|
+
return { success: true, killed: result.killed };
|
|
6389
|
+
}
|
|
6390
|
+
|
|
6391
|
+
// src/commands/reset.ts
|
|
6341
6392
|
var RESET_TARGETS = [
|
|
6342
6393
|
{
|
|
6343
6394
|
id: "subs",
|
|
@@ -6403,19 +6454,23 @@ var RESET_TARGETS = [
|
|
|
6403
6454
|
needsStop: false
|
|
6404
6455
|
},
|
|
6405
6456
|
{
|
|
6406
|
-
id: "
|
|
6407
|
-
aliases: ["daemon"],
|
|
6408
|
-
label: "\
|
|
6409
|
-
// 卸载由确认后的
|
|
6410
|
-
//
|
|
6411
|
-
// onAfter
|
|
6457
|
+
id: "service",
|
|
6458
|
+
aliases: ["service", "daemon"],
|
|
6459
|
+
label: "\u670D\u52A1",
|
|
6460
|
+
// 卸载由确认后的 uninstallsService 段统一处理;此处 paths 返回空
|
|
6461
|
+
// (plist 不在数据目录里,且不应提前删破坏卸载),
|
|
6462
|
+
// onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
|
|
6412
6463
|
paths: () => [],
|
|
6413
6464
|
needsStop: false,
|
|
6414
|
-
onAfter: () =>
|
|
6415
|
-
|
|
6416
|
-
|
|
6465
|
+
onAfter: () => {
|
|
6466
|
+
const st = getServiceStatus();
|
|
6467
|
+
if (st.installed || st.loaded) uninstallService();
|
|
6468
|
+
},
|
|
6469
|
+
checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
|
|
6470
|
+
emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
|
|
6417
6471
|
}
|
|
6418
6472
|
];
|
|
6473
|
+
var RESET_PRESERVED_ON_BARE = ["settings", "kernel", "overwrites", "service"];
|
|
6419
6474
|
function resolveResetTargets(names) {
|
|
6420
6475
|
const matched = [];
|
|
6421
6476
|
const unmatched = [];
|
|
@@ -6461,7 +6516,7 @@ async function cmdReset(args) {
|
|
|
6461
6516
|
}
|
|
6462
6517
|
targets = matched;
|
|
6463
6518
|
} else {
|
|
6464
|
-
targets = RESET_TARGETS.filter((t) => !
|
|
6519
|
+
targets = RESET_TARGETS.filter((t) => !RESET_PRESERVED_ON_BARE.includes(t.id));
|
|
6465
6520
|
}
|
|
6466
6521
|
for (const t of targets) {
|
|
6467
6522
|
if (t.checkEmpty?.()) {
|
|
@@ -6474,14 +6529,19 @@ async function cmdReset(args) {
|
|
|
6474
6529
|
const needsStop = targets.some((t) => t.needsStop);
|
|
6475
6530
|
const warnRunning = targets.some((t) => t.warnIfRunning);
|
|
6476
6531
|
const kernelTargeted = targets.some((t) => t.id === "kernel");
|
|
6477
|
-
const
|
|
6478
|
-
const
|
|
6532
|
+
const serviceTargeted = targets.some((t) => t.id === "service");
|
|
6533
|
+
const uninstallsService = serviceTargeted;
|
|
6534
|
+
const stopsService = needsStop || kernelTargeted;
|
|
6535
|
+
const serviceStatus = getServiceStatus();
|
|
6536
|
+
const serviceActive = serviceStatus.installed || serviceStatus.loaded;
|
|
6479
6537
|
const pids = needsStop || warnRunning ? getMihomoPids() : [];
|
|
6480
6538
|
if (warnRunning && pids.length > 0) {
|
|
6481
6539
|
console.log(colors.yellow(`\u8B66\u544A: mihomo \u6B63\u5728\u8FD0\u884C (PID ${pids.join(", ")})\uFF0C\u5220\u9664\u5185\u6838\u540E\u5C06\u65E0\u6CD5\u91CD\u65B0\u542F\u52A8`));
|
|
6482
6540
|
}
|
|
6483
|
-
if (
|
|
6484
|
-
console.log(colors.yellow("\
|
|
6541
|
+
if (uninstallsService && serviceActive) {
|
|
6542
|
+
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08\u79FB\u9664\u767B\u5F55\u81EA\u542F\uFF0CMixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
6543
|
+
} else if (stopsService && serviceActive) {
|
|
6544
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
6485
6545
|
}
|
|
6486
6546
|
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
6487
6547
|
if (!skipConfirm) {
|
|
@@ -6493,12 +6553,16 @@ async function cmdReset(args) {
|
|
|
6493
6553
|
return;
|
|
6494
6554
|
}
|
|
6495
6555
|
}
|
|
6496
|
-
if (
|
|
6556
|
+
if ((uninstallsService || stopsService) && serviceActive) {
|
|
6497
6557
|
try {
|
|
6498
|
-
|
|
6558
|
+
if (uninstallsService) {
|
|
6559
|
+
uninstallService();
|
|
6560
|
+
} else {
|
|
6561
|
+
stopService();
|
|
6562
|
+
}
|
|
6499
6563
|
} catch (e) {
|
|
6500
6564
|
if (e instanceof CliError) throw e;
|
|
6501
|
-
throw new CliError(e.message.split("\n")[0], { label: "\
|
|
6565
|
+
throw new CliError(e.message.split("\n")[0], { label: "\u670D\u52A1\u64CD\u4F5C\u5DF2\u53D6\u6D88\uFF0C\u91CD\u7F6E\u4E2D\u6B62" });
|
|
6502
6566
|
}
|
|
6503
6567
|
}
|
|
6504
6568
|
if (needsStop && getMihomoPids().length > 0) {
|
|
@@ -6539,6 +6603,110 @@ async function cmdReset(args) {
|
|
|
6539
6603
|
console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
|
|
6540
6604
|
}
|
|
6541
6605
|
|
|
6606
|
+
// src/commands/service.ts
|
|
6607
|
+
import fs13 from "fs";
|
|
6608
|
+
async function handleLegacyInstall() {
|
|
6609
|
+
if (!detectLegacySystemInstall()) return;
|
|
6610
|
+
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
|
|
6611
|
+
console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
|
|
6612
|
+
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
6613
|
+
console.log("");
|
|
6614
|
+
try {
|
|
6615
|
+
cleanupLegacySystemInstall();
|
|
6616
|
+
} catch (e) {
|
|
6617
|
+
if (e instanceof CliError) throw e;
|
|
6618
|
+
throw new CliError(e.message, {
|
|
6619
|
+
label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
|
|
6620
|
+
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
6621
|
+
});
|
|
6622
|
+
}
|
|
6623
|
+
console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
|
|
6624
|
+
console.log("");
|
|
6625
|
+
}
|
|
6626
|
+
async function cmdInstall(_args) {
|
|
6627
|
+
if (!hasKernel()) {
|
|
6628
|
+
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
6629
|
+
}
|
|
6630
|
+
await handleLegacyInstall();
|
|
6631
|
+
const wasRunning = getServiceStatus().running;
|
|
6632
|
+
installService(wasRunning);
|
|
6633
|
+
console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
|
|
6634
|
+
console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
|
|
6635
|
+
console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
|
|
6636
|
+
console.log("");
|
|
6637
|
+
if (wasRunning) {
|
|
6638
|
+
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
6639
|
+
} else {
|
|
6640
|
+
console.log("\u542F\u52A8: mihomo start");
|
|
6641
|
+
if (!fs13.existsSync(PATHS.configFile)) {
|
|
6642
|
+
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
6643
|
+
}
|
|
6644
|
+
}
|
|
6645
|
+
console.log("");
|
|
6646
|
+
}
|
|
6647
|
+
async function cmdUninstall(_args) {
|
|
6648
|
+
const status = getServiceStatus();
|
|
6649
|
+
const legacy = detectLegacySystemInstall();
|
|
6650
|
+
const residue = getMihomoPids();
|
|
6651
|
+
if (!status.installed && !status.loaded && !legacy && residue.length === 0) {
|
|
6652
|
+
console.log("\u670D\u52A1\u672A\u5B89\u88C5");
|
|
6653
|
+
return;
|
|
6654
|
+
}
|
|
6655
|
+
if (!status.installed && status.loaded) {
|
|
6656
|
+
console.log(colors.yellow("\u672A\u627E\u5230 plist\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001\uFF08plist \u53EF\u80FD\u88AB\u624B\u52A8\u5220\u9664\uFF09"));
|
|
6657
|
+
console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
|
|
6658
|
+
}
|
|
6659
|
+
if (status.installed || status.loaded) {
|
|
6660
|
+
uninstallService();
|
|
6661
|
+
console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
|
|
6662
|
+
}
|
|
6663
|
+
if (legacy) {
|
|
6664
|
+
console.log(colors.gray("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801"));
|
|
6665
|
+
cleanupLegacySystemInstall();
|
|
6666
|
+
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
6667
|
+
}
|
|
6668
|
+
const remaining = getMihomoPids();
|
|
6669
|
+
if (remaining.length > 0) {
|
|
6670
|
+
console.log("");
|
|
6671
|
+
console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
|
|
6672
|
+
console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
|
|
6673
|
+
}
|
|
6674
|
+
console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo install"));
|
|
6675
|
+
console.log("");
|
|
6676
|
+
}
|
|
6677
|
+
|
|
6678
|
+
// src/commands/stop.ts
|
|
6679
|
+
function handleStopResult(result) {
|
|
6680
|
+
if (result.remaining && result.remaining.length > 0) {
|
|
6681
|
+
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
|
|
6682
|
+
}
|
|
6683
|
+
}
|
|
6684
|
+
async function cmdStop(args) {
|
|
6685
|
+
assertNoRemovedSshFlag(args);
|
|
6686
|
+
const status = getServiceStatus();
|
|
6687
|
+
const pids = getMihomoPids();
|
|
6688
|
+
const needsServiceWork = status.loaded || status.installed && !status.disabled;
|
|
6689
|
+
if (!needsServiceWork && pids.length === 0) {
|
|
6690
|
+
console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
|
|
6691
|
+
return;
|
|
6692
|
+
}
|
|
6693
|
+
if (!needsServiceWork) {
|
|
6694
|
+
console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
|
|
6695
|
+
handleStopResult(await stop());
|
|
6696
|
+
console.log(colors.green("\u5DF2\u505C\u6B62"));
|
|
6697
|
+
return;
|
|
6698
|
+
}
|
|
6699
|
+
stopService();
|
|
6700
|
+
const remaining = getMihomoPids();
|
|
6701
|
+
if (remaining.length > 0) {
|
|
6702
|
+
throw new CliError(remaining.join(", "), {
|
|
6703
|
+
label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62",
|
|
6704
|
+
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
6705
|
+
});
|
|
6706
|
+
}
|
|
6707
|
+
console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
|
|
6708
|
+
}
|
|
6709
|
+
|
|
6542
6710
|
// src/commands/subscription.ts
|
|
6543
6711
|
function printRestartHintIfRunning() {
|
|
6544
6712
|
if (getRunningState().running) {
|
|
@@ -6702,18 +6870,18 @@ async function subRemove(args) {
|
|
|
6702
6870
|
console.log("");
|
|
6703
6871
|
printSubscriptionList();
|
|
6704
6872
|
}
|
|
6705
|
-
var
|
|
6873
|
+
var SUBCOMMANDS3 = [
|
|
6706
6874
|
{ name: "add", handler: subAdd },
|
|
6707
6875
|
{ name: "update", handler: subUpdate },
|
|
6708
6876
|
{ name: "use", handler: subUse },
|
|
6709
6877
|
{ name: "remove", aliases: ["rm", "delete"], handler: subRemove }
|
|
6710
6878
|
];
|
|
6711
6879
|
async function cmdSubscription(args) {
|
|
6712
|
-
await dispatchSubcommand(args,
|
|
6880
|
+
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6713
6881
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6714
6882
|
fallback: printSubscriptionList,
|
|
6715
6883
|
onUnknown: (action) => {
|
|
6716
|
-
const names =
|
|
6884
|
+
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6717
6885
|
const suggestion = suggestSimilar(action, names);
|
|
6718
6886
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
6719
6887
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
@@ -6746,7 +6914,7 @@ function cmdUI(args) {
|
|
|
6746
6914
|
}
|
|
6747
6915
|
|
|
6748
6916
|
// src/commands/update.ts
|
|
6749
|
-
import { execFile, spawn as
|
|
6917
|
+
import { execFile, spawn as spawn2 } from "child_process";
|
|
6750
6918
|
import { promisify } from "util";
|
|
6751
6919
|
var execFileAsync = promisify(execFile);
|
|
6752
6920
|
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
@@ -6777,7 +6945,7 @@ async function cmdUpdate() {
|
|
|
6777
6945
|
console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
|
|
6778
6946
|
console.log("");
|
|
6779
6947
|
await new Promise((resolve, reject) => {
|
|
6780
|
-
const npm =
|
|
6948
|
+
const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
|
|
6781
6949
|
npm.on("close", (code) => {
|
|
6782
6950
|
if (code === 0) {
|
|
6783
6951
|
resolve();
|
|
@@ -6809,12 +6977,19 @@ async function cmdUpdate() {
|
|
|
6809
6977
|
// src/commands/registry.ts
|
|
6810
6978
|
var COMMANDS = [
|
|
6811
6979
|
// === 控制 ===
|
|
6980
|
+
{
|
|
6981
|
+
name: "install",
|
|
6982
|
+
aliases: [],
|
|
6983
|
+
handler: cmdInstall,
|
|
6984
|
+
group: "control",
|
|
6985
|
+
usage: [{ signature: "install", description: "\u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09" }]
|
|
6986
|
+
},
|
|
6812
6987
|
{
|
|
6813
6988
|
name: "start",
|
|
6814
|
-
aliases: [
|
|
6989
|
+
aliases: [],
|
|
6815
6990
|
handler: cmdStart,
|
|
6816
6991
|
group: "control",
|
|
6817
|
-
usage: ["start [tun|mixed] [-s] [-u ms]
|
|
6992
|
+
usage: [{ signature: "start [tun|mixed] [-s] [-u ms]", description: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F\uFF08\u9ED8\u8BA4 mixed\uFF09" }]
|
|
6818
6993
|
},
|
|
6819
6994
|
{
|
|
6820
6995
|
name: "tun",
|
|
@@ -6826,17 +7001,53 @@ var COMMANDS = [
|
|
|
6826
7001
|
},
|
|
6827
7002
|
{
|
|
6828
7003
|
name: "stop",
|
|
6829
|
-
aliases: [
|
|
7004
|
+
aliases: [],
|
|
6830
7005
|
handler: cmdStop,
|
|
6831
7006
|
group: "control",
|
|
6832
|
-
usage: ["stop
|
|
7007
|
+
usage: [{ signature: "stop", description: "\u505C\u6B62\u4EE3\u7406\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F" }]
|
|
7008
|
+
},
|
|
7009
|
+
{
|
|
7010
|
+
name: "uninstall",
|
|
7011
|
+
aliases: [],
|
|
7012
|
+
handler: cmdUninstall,
|
|
7013
|
+
group: "control",
|
|
7014
|
+
usage: [{ signature: "uninstall", description: "\u5378\u8F7D\u670D\u52A1" }]
|
|
6833
7015
|
},
|
|
6834
7016
|
{
|
|
6835
7017
|
name: "status",
|
|
6836
7018
|
aliases: [],
|
|
6837
7019
|
handler: printStatus,
|
|
6838
7020
|
group: "control",
|
|
6839
|
-
usage: ["status
|
|
7021
|
+
usage: [{ signature: "status", description: "\u67E5\u770B\u72B6\u6001" }]
|
|
7022
|
+
},
|
|
7023
|
+
// === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
|
|
7024
|
+
{
|
|
7025
|
+
name: "daemon",
|
|
7026
|
+
aliases: [],
|
|
7027
|
+
handler: removedCommand("daemon", "v4.1.0", [
|
|
7028
|
+
"\u4FDD\u6D3B\u5DF2\u6210\u4E3A Mixed \u6A21\u5F0F\u7684\u552F\u4E00\u8FD0\u884C\u65B9\u5F0F\uFF0C\u6539\u7528\u670D\u52A1\u547D\u4EE4\u65CF\uFF1A",
|
|
7029
|
+
" mihomo daemon on \u2192 mihomo install\uFF08\u4E00\u6B21\uFF09+ mihomo start",
|
|
7030
|
+
" mihomo daemon off \u2192 mihomo stop\uFF08\u505C\u6B62\u5E76\u5173\u95ED\u81EA\u542F\uFF09",
|
|
7031
|
+
" mihomo daemon \u2192 mihomo status",
|
|
7032
|
+
"",
|
|
7033
|
+
"\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
|
|
7034
|
+
]),
|
|
7035
|
+
group: "meta",
|
|
7036
|
+
usage: []
|
|
7037
|
+
},
|
|
7038
|
+
{
|
|
7039
|
+
name: "up",
|
|
7040
|
+
aliases: [],
|
|
7041
|
+
handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
|
|
7042
|
+
group: "meta",
|
|
7043
|
+
usage: []
|
|
7044
|
+
},
|
|
7045
|
+
{
|
|
7046
|
+
name: "down",
|
|
7047
|
+
aliases: [],
|
|
7048
|
+
handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
|
|
7049
|
+
group: "meta",
|
|
7050
|
+
usage: []
|
|
6840
7051
|
},
|
|
6841
7052
|
// === 界面 ===
|
|
6842
7053
|
{
|
|
@@ -6844,7 +7055,7 @@ var COMMANDS = [
|
|
|
6844
7055
|
aliases: [],
|
|
6845
7056
|
handler: cmdUI,
|
|
6846
7057
|
group: "interface",
|
|
6847
|
-
usage: ["ui [zash|dash|yacd]
|
|
7058
|
+
usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
|
|
6848
7059
|
},
|
|
6849
7060
|
{
|
|
6850
7061
|
// 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
|
|
@@ -6860,7 +7071,7 @@ var COMMANDS = [
|
|
|
6860
7071
|
aliases: [],
|
|
6861
7072
|
handler: cmdLogs,
|
|
6862
7073
|
group: "interface",
|
|
6863
|
-
usage: ["logs [-f] [-n N] [\u7F16\u53F7] [-o]
|
|
7074
|
+
usage: [{ signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]", description: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF0C-f \u8DDF\u968F\uFF1B\u7701\u7565\u7F16\u53F7\u5373\u5F53\u524D\uFF09" }]
|
|
6864
7075
|
},
|
|
6865
7076
|
// === 订阅 ===
|
|
6866
7077
|
{
|
|
@@ -6869,11 +7080,11 @@ var COMMANDS = [
|
|
|
6869
7080
|
handler: cmdSubscription,
|
|
6870
7081
|
group: "subscription",
|
|
6871
7082
|
usage: [
|
|
6872
|
-
"subscription
|
|
6873
|
-
"subscription use <name>
|
|
6874
|
-
"subscription add <url> [name]
|
|
6875
|
-
"subscription update [name]
|
|
6876
|
-
"subscription remove <name>
|
|
7083
|
+
{ signature: "subscription", description: "\u5217\u51FA\u6240\u6709\u8BA2\u9605\uFF08\u522B\u540D sub/subs\uFF09" },
|
|
7084
|
+
{ signature: "subscription use <name>", description: "\u5207\u6362\u5F53\u524D\u8BA2\u9605" },
|
|
7085
|
+
{ signature: "subscription add <url> [name]", description: "\u6DFB\u52A0\u8BA2\u9605" },
|
|
7086
|
+
{ signature: "subscription update [name]", description: "\u66F4\u65B0\u8BA2\u9605\uFF08\u65E0\u53C2\u66F4\u65B0\u6240\u6709\uFF09" },
|
|
7087
|
+
{ signature: "subscription remove <name>", description: "\u5220\u9664\u8BA2\u9605\uFF08\u6A21\u7CCA\u5339\u914D\u9700\u786E\u8BA4\uFF0C-y \u8DF3\u8FC7\uFF09" }
|
|
6877
7088
|
]
|
|
6878
7089
|
},
|
|
6879
7090
|
// === 配置 ===
|
|
@@ -6882,14 +7093,20 @@ var COMMANDS = [
|
|
|
6882
7093
|
aliases: ["ow"],
|
|
6883
7094
|
handler: cmdOverwrite,
|
|
6884
7095
|
group: "config",
|
|
6885
|
-
usage: [
|
|
7096
|
+
usage: [
|
|
7097
|
+
{ signature: "overwrite", description: "\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF08\u522B\u540D ow\uFF09" },
|
|
7098
|
+
{ signature: "overwrite on|off", description: "\u542F\u7528/\u7981\u7528\u8986\u5199\u914D\u7F6E" }
|
|
7099
|
+
]
|
|
6886
7100
|
},
|
|
6887
7101
|
{
|
|
6888
7102
|
name: "directory",
|
|
6889
7103
|
aliases: ["dir", "dirs", "directories"],
|
|
6890
7104
|
handler: cmdDirectory,
|
|
6891
7105
|
group: "config",
|
|
6892
|
-
usage: [
|
|
7106
|
+
usage: [
|
|
7107
|
+
{ signature: "directory", description: "\u663E\u793A\u6570\u636E\u76EE\u5F55\u4F4D\u7F6E\uFF08\u522B\u540D dir\uFF09" },
|
|
7108
|
+
{ signature: "directory open [target]", description: "\u6253\u5F00\u76EE\u5F55: root|subs|logs|data|runtime|kernel" }
|
|
7109
|
+
]
|
|
6893
7110
|
},
|
|
6894
7111
|
// === 系统 ===
|
|
6895
7112
|
{
|
|
@@ -6897,28 +7114,21 @@ var COMMANDS = [
|
|
|
6897
7114
|
aliases: [],
|
|
6898
7115
|
handler: cmdKernel,
|
|
6899
7116
|
group: "system",
|
|
6900
|
-
usage: ["kernel [--mirror [\u955C\u50CF]]
|
|
6901
|
-
},
|
|
6902
|
-
{
|
|
6903
|
-
name: "daemon",
|
|
6904
|
-
aliases: [],
|
|
6905
|
-
handler: cmdDaemon,
|
|
6906
|
-
group: "system",
|
|
6907
|
-
usage: ["daemon [on|off] \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09\uFF1B\u65E0\u53C2\u770B\u72B6\u6001"]
|
|
7117
|
+
usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u9ED8\u8BA4\u76F4\u8FDE\uFF0C--mirror \u8D70\u955C\u50CF\u4E0B\u8F7D\uFF09" }]
|
|
6908
7118
|
},
|
|
6909
7119
|
{
|
|
6910
7120
|
name: "update",
|
|
6911
7121
|
aliases: [],
|
|
6912
7122
|
handler: cmdUpdate,
|
|
6913
7123
|
group: "system",
|
|
6914
|
-
usage: ["update
|
|
7124
|
+
usage: [{ signature: "update", description: "\u66F4\u65B0 mihomo-cli\uFF08npm install -g\uFF09" }]
|
|
6915
7125
|
},
|
|
6916
7126
|
{
|
|
6917
7127
|
name: "reset",
|
|
6918
7128
|
aliases: [],
|
|
6919
7129
|
handler: cmdReset,
|
|
6920
7130
|
group: "system",
|
|
6921
|
-
usage: ["reset [\u76EE\u6807...] [--full] [-y]
|
|
7131
|
+
usage: [{ signature: "reset [\u76EE\u6807...] [--full] [-y]", description: "\u91CD\u7F6E: \u7559\u7A7A\u4FDD\u7559\u8BBE\u7F6E/\u5185\u6838/\u8986\u5199\uFF0C\u6307\u5B9A\u76EE\u6807\u5220\u5BF9\u5E94\u9879\uFF0C--full \u5220\u5168\u90E8\uFF0C-y \u8DF3\u8FC7\u786E\u8BA4" }]
|
|
6922
7132
|
},
|
|
6923
7133
|
// === meta(不在分组清单展示,help 末尾单列) ===
|
|
6924
7134
|
{
|
|
@@ -6926,14 +7136,14 @@ var COMMANDS = [
|
|
|
6926
7136
|
aliases: ["-h", "--help"],
|
|
6927
7137
|
handler: () => printHelp(COMMANDS),
|
|
6928
7138
|
group: "meta",
|
|
6929
|
-
usage: ["help, -h
|
|
7139
|
+
usage: [{ signature: "help, -h", description: "\u663E\u793A\u5E2E\u52A9" }]
|
|
6930
7140
|
},
|
|
6931
7141
|
{
|
|
6932
7142
|
name: "version",
|
|
6933
7143
|
aliases: ["-v", "--version"],
|
|
6934
7144
|
handler: printVersion,
|
|
6935
7145
|
group: "meta",
|
|
6936
|
-
usage: ["version, -v
|
|
7146
|
+
usage: [{ signature: "version, -v", description: "\u663E\u793A\u7248\u672C" }]
|
|
6937
7147
|
}
|
|
6938
7148
|
];
|
|
6939
7149
|
var COMMAND_INDEX = (() => {
|
|
@@ -6960,11 +7170,9 @@ process.on("SIGINT", () => {
|
|
|
6960
7170
|
if (!isSilentSigint()) {
|
|
6961
7171
|
console.log("\n\u6B63\u5728\u9000\u51FA...");
|
|
6962
7172
|
}
|
|
6963
|
-
runCleanup();
|
|
6964
7173
|
process.exit(130);
|
|
6965
7174
|
});
|
|
6966
7175
|
process.on("SIGTERM", () => {
|
|
6967
|
-
runCleanup();
|
|
6968
7176
|
process.exit(143);
|
|
6969
7177
|
});
|
|
6970
7178
|
process.on("uncaughtException", (e) => {
|
|
@@ -6973,14 +7181,12 @@ process.on("uncaughtException", (e) => {
|
|
|
6973
7181
|
if (e.stack) {
|
|
6974
7182
|
console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
6975
7183
|
}
|
|
6976
|
-
runCleanup();
|
|
6977
7184
|
process.exit(1);
|
|
6978
7185
|
});
|
|
6979
7186
|
process.on("unhandledRejection", (reason) => {
|
|
6980
7187
|
const msg = reason instanceof Error ? reason.message : String(reason);
|
|
6981
7188
|
console.error(`
|
|
6982
7189
|
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${msg}`);
|
|
6983
|
-
runCleanup();
|
|
6984
7190
|
process.exit(1);
|
|
6985
7191
|
});
|
|
6986
7192
|
function clearProxyEnv() {
|
|
@@ -6999,7 +7205,7 @@ function assertSupportedPlatform(commandName) {
|
|
|
6999
7205
|
throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
|
|
7000
7206
|
label: "\u5E73\u53F0\u4E0D\u652F\u6301",
|
|
7001
7207
|
hint: [
|
|
7002
|
-
"\
|
|
7208
|
+
"\u670D\u52A1\u6258\u7BA1\u4F9D\u8D56 launchd\u3001\u76EE\u5F55/UI \u6253\u5F00\u4F9D\u8D56 open\u3001\u63D0\u6743\u4F9D\u8D56 sudo\uFF0C\u5747\u65E0\u5176\u4ED6\u5E73\u53F0\u5B9E\u73B0\u3002",
|
|
7003
7209
|
"Windows / Linux \u9002\u914D\u4ECD\u5728\u8FDB\u884C\u4E2D\u3002",
|
|
7004
7210
|
"\u5982\u9700\u5728\u975E macOS \u4E0A\u5F00\u53D1\u8C03\u8BD5\uFF0C\u53EF\u8BBE MIHOMO_CLI_ALLOW_ANY_PLATFORM=1\uFF08\u529F\u80FD\u4E0D\u4FDD\u8BC1\u53EF\u7528\uFF09\u3002"
|
|
7005
7211
|
]
|
|
@@ -7031,13 +7237,11 @@ main().catch((e) => {
|
|
|
7031
7237
|
if (e instanceof CliError) {
|
|
7032
7238
|
console.error(`${colors.red(`${e.label}:`)} ${e.message}`);
|
|
7033
7239
|
for (const line of e.hint) console.error(line);
|
|
7034
|
-
runCleanup();
|
|
7035
7240
|
process.exit(e.exitCode);
|
|
7036
7241
|
}
|
|
7037
7242
|
const err = e;
|
|
7038
7243
|
console.error(`${colors.red("\u9519\u8BEF:")} ${err.message}`);
|
|
7039
7244
|
if (err.stack) console.error(err.stack.split("\n").slice(1).join("\n"));
|
|
7040
|
-
runCleanup();
|
|
7041
7245
|
process.exit(1);
|
|
7042
7246
|
});
|
|
7043
7247
|
/*! Bundled license information:
|