mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-02-28 17:49:55 +00:00
Compare commits
322 Commits
android-re
...
v1.18.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48e481d0a2 | ||
|
|
e749c7e492 | ||
|
|
c3ee921d30 | ||
|
|
df69a31e62 | ||
|
|
b7c02a5923 | ||
|
|
bfb6caeeaf | ||
|
|
30a913aad6 | ||
|
|
00e361c5ac | ||
|
|
56edd8f671 | ||
|
|
2b52809d2c | ||
|
|
5c3a9b1dfc | ||
|
|
fe88f0e437 | ||
|
|
87877d1b80 | ||
|
|
1bc3c16b59 | ||
|
|
ed1e7e32c7 | ||
|
|
5da9ccaa98 | ||
|
|
fd7ecc004f | ||
|
|
3ae4014b39 | ||
|
|
a50339bd5f | ||
|
|
7df1c26942 | ||
|
|
fc82a32a48 | ||
|
|
adf0ff588f | ||
|
|
b840eae4c6 | ||
|
|
619f34119e | ||
|
|
6d1c62bbf0 | ||
|
|
5dd883e790 | ||
|
|
a2b43faa0b | ||
|
|
8861eaf903 | ||
|
|
107e3e7630 | ||
|
|
81947304bc | ||
|
|
314c0bb34b | ||
|
|
89a097faa8 | ||
|
|
df01582996 | ||
|
|
8ff56b5bb8 | ||
|
|
2f8f139f7c | ||
|
|
b2280c85b7 | ||
|
|
002b8af94a | ||
|
|
99b274acbc | ||
|
|
d4ececae20 | ||
|
|
ff2071c1da | ||
|
|
189b7b9c5f | ||
|
|
a878254662 | ||
|
|
3566542d0e | ||
|
|
ca84ab1a94 | ||
|
|
d84f88b50f | ||
|
|
e3b69b8ae2 | ||
|
|
91a7ffaad2 | ||
|
|
16fadd2441 | ||
|
|
cff7df164f | ||
|
|
de38fa882c | ||
|
|
bd703b8ff2 | ||
|
|
72df27be44 | ||
|
|
f3e23b1128 | ||
|
|
19f7220c0b | ||
|
|
3249572dc1 | ||
|
|
ba09139bd7 | ||
|
|
90bf158e9f | ||
|
|
d1539e6c07 | ||
|
|
c893e3c462 | ||
|
|
b56e73a02a | ||
|
|
40f5c5b987 | ||
|
|
d48517b29d | ||
|
|
3b472f786e | ||
|
|
f3743fc7f9 | ||
|
|
56ed9019a6 | ||
|
|
3e0bd65135 | ||
|
|
e27d7c010f | ||
|
|
72d0948224 | ||
|
|
4542fc0991 | ||
|
|
914bc8a3e9 | ||
|
|
11f0983e5c | ||
|
|
89d7b8138a | ||
|
|
eae1f05e88 | ||
|
|
367a287153 | ||
|
|
06b5121d9e | ||
|
|
82517e6ba8 | ||
|
|
582e94ff4d | ||
|
|
0b4662e4b7 | ||
|
|
288899a473 | ||
|
|
5af7f4e847 | ||
|
|
d2ae94f20b | ||
|
|
d56a439a74 | ||
|
|
9c08e936f9 | ||
|
|
284b01ca38 | ||
|
|
2e94531c72 | ||
|
|
e1a5b93cce | ||
|
|
7fd5902e6b | ||
|
|
143fe84b8e | ||
|
|
80408855ac | ||
|
|
c80dd5d738 | ||
|
|
b3db113b1b | ||
|
|
dceb8ee535 | ||
|
|
31d3614060 | ||
|
|
5fdfde6a07 | ||
|
|
81c832ef9e | ||
|
|
012e448562 | ||
|
|
44d8a14629 | ||
|
|
7ad37ca0e3 | ||
|
|
f0ff6546e4 | ||
|
|
77c10d90f3 | ||
|
|
e0248faebd | ||
|
|
feedc9ec66 | ||
|
|
7754b46dc4 | ||
|
|
90d0ef033b | ||
|
|
5702d28cda | ||
|
|
0bb5568de9 | ||
|
|
37b02b18f7 | ||
|
|
cd9e9cd2c1 | ||
|
|
234a4bfc93 | ||
|
|
fad1a08378 | ||
|
|
04886761a2 | ||
|
|
823f59b5c7 | ||
|
|
974332c0cc | ||
|
|
8b9813079b | ||
|
|
fe4acebb8b | ||
|
|
69bf434e2c | ||
|
|
e867497315 | ||
|
|
3ec23c1fc5 | ||
|
|
d27340867f | ||
|
|
7eb16a098a | ||
|
|
f0bc68585a | ||
|
|
092e53586e | ||
|
|
41e3571e1d | ||
|
|
e58294198c | ||
|
|
0619c75276 | ||
|
|
78b4b11f26 | ||
|
|
8d9eb1e534 | ||
|
|
d2a5376cb8 | ||
|
|
f8295a02fd | ||
|
|
3d833ef6a8 | ||
|
|
1c7e011f87 | ||
|
|
9e7eaf720f | ||
|
|
6399347a63 | ||
|
|
23e3f12e88 | ||
|
|
985b884d85 | ||
|
|
93b48a94fc | ||
|
|
080d316059 | ||
|
|
0c384b1e42 | ||
|
|
324c0bde7d | ||
|
|
9e57e7d29b | ||
|
|
20658f6eac | ||
|
|
822ba5f0b5 | ||
|
|
a034421a58 | ||
|
|
e6011301b2 | ||
|
|
947ad9b308 | ||
|
|
d1337f39ed | ||
|
|
c6843d6a2c | ||
|
|
f2634250a6 | ||
|
|
9bd70e1366 | ||
|
|
1025101954 | ||
|
|
80d6ca8ef9 | ||
|
|
5858384631 | ||
|
|
5c1404f78e | ||
|
|
7be6751650 | ||
|
|
e86567ead2 | ||
|
|
c1f0ed18ef | ||
|
|
0e1bdb07d4 | ||
|
|
25d6ad220d | ||
|
|
90ea6ab278 | ||
|
|
36ea09eff4 | ||
|
|
460cc240b0 | ||
|
|
c34a0ef8f0 | ||
|
|
061f83d92a | ||
|
|
edf318bae0 | ||
|
|
e860497c0c | ||
|
|
d2d8c0115c | ||
|
|
5ec686df08 | ||
|
|
7c54775ddc | ||
|
|
425bc692ad | ||
|
|
ffcd672ebf | ||
|
|
7e3e38d054 | ||
|
|
6bc915526f | ||
|
|
4af94df142 | ||
|
|
2e12ceeaed | ||
|
|
33bc7914e9 | ||
|
|
0404e35be8 | ||
|
|
fbaa323ad4 | ||
|
|
dc2108c174 | ||
|
|
4ee267ca7e | ||
|
|
1d3e9f4889 | ||
|
|
3d643cb95a | ||
|
|
22862f20cc | ||
|
|
2e87c6f4da | ||
|
|
fb1c0aa387 | ||
|
|
1701e4715d | ||
|
|
0d07cf40b8 | ||
|
|
41a05d96a5 | ||
|
|
4cea3125e6 | ||
|
|
997663a4ad | ||
|
|
b632575e39 | ||
|
|
59ab4fe745 | ||
|
|
147400fbe0 | ||
|
|
ac381736a5 | ||
|
|
08a1f10af4 | ||
|
|
8822349f94 | ||
|
|
27635ea027 | ||
|
|
429a03d986 | ||
|
|
518c31dd0e | ||
|
|
16769865e4 | ||
|
|
9d8c3b0a3b | ||
|
|
f16ebf9bfe | ||
|
|
f29329fe80 | ||
|
|
8cf14bb67e | ||
|
|
2bba8aa14a | ||
|
|
5b23b979df | ||
|
|
78e5d3229e | ||
|
|
0ab73a9beb | ||
|
|
7ee6809257 | ||
|
|
3cf865e5f0 | ||
|
|
9fc1fc4cfe | ||
|
|
d80fcb77f6 | ||
|
|
5a2ed71bd9 | ||
|
|
9729c2e440 | ||
|
|
c5d1e20a64 | ||
|
|
da65f8f935 | ||
|
|
582ac28728 | ||
|
|
262d3295d1 | ||
|
|
8dbc5e2100 | ||
|
|
941dd6c76d | ||
|
|
fdc9c01df1 | ||
|
|
b538aa6ca2 | ||
|
|
1d1841f7aa | ||
|
|
1b527fd494 | ||
|
|
73e16c912f | ||
|
|
9ac4738ef9 | ||
|
|
cbec564af9 | ||
|
|
c5d1db7905 | ||
|
|
ad263f7229 | ||
|
|
f63acc0202 | ||
|
|
f572e7fba8 | ||
|
|
ed210ee403 | ||
|
|
92129b33e7 | ||
|
|
ee6b974c18 | ||
|
|
2d73bcb951 | ||
|
|
2d7538aca6 | ||
|
|
aef87b29ba | ||
|
|
5f493fbcfb | ||
|
|
071e8488a8 | ||
|
|
22ed13b9df | ||
|
|
bda71dbfa1 | ||
|
|
1a0932c210 | ||
|
|
bc74c943b8 | ||
|
|
cc6429722a | ||
|
|
3b57a923fd | ||
|
|
7efd692bbc | ||
|
|
d773d335a2 | ||
|
|
78ae8815c2 | ||
|
|
8f61b0e180 | ||
|
|
a974e810c2 | ||
|
|
599ce784d2 | ||
|
|
db973de7bd | ||
|
|
5f7053c519 | ||
|
|
84a334dd3a | ||
|
|
7d15ce2b33 | ||
|
|
37791acb59 | ||
|
|
96f0254a48 | ||
|
|
8b4499e461 | ||
|
|
6a3e28c384 | ||
|
|
b05cf14b98 | ||
|
|
a6b816b1c6 | ||
|
|
bb9ad6cac0 | ||
|
|
b9d48f4115 | ||
|
|
84299606f4 | ||
|
|
8efb699231 | ||
|
|
3c088b33a2 | ||
|
|
4362dfacc9 | ||
|
|
05b9071ca6 | ||
|
|
117228fa8c | ||
|
|
3a3d88c668 | ||
|
|
54a7f52fe3 | ||
|
|
1479b449df | ||
|
|
fef5ad780d | ||
|
|
aa3c1ac623 | ||
|
|
b5a8f0fce1 | ||
|
|
d9cfdc3242 | ||
|
|
b73382f60a | ||
|
|
9e96d70840 | ||
|
|
d28c3b50e3 | ||
|
|
2f203330e4 | ||
|
|
7d222b1b71 | ||
|
|
d85d8ac13f | ||
|
|
7979eb654f | ||
|
|
2577dd3af4 | ||
|
|
daa332e7b0 | ||
|
|
288c0c27d6 | ||
|
|
832dae3421 | ||
|
|
fe7c1a2cdb | ||
|
|
e8e4288d85 | ||
|
|
6901afb406 | ||
|
|
f260d8cf01 | ||
|
|
575c1d4129 | ||
|
|
253b023442 | ||
|
|
17c9d507be | ||
|
|
8293b7fdae | ||
|
|
0ba415866e | ||
|
|
53b41ca166 | ||
|
|
8a75f78e63 | ||
|
|
d9692c6366 | ||
|
|
f4b0062dfc | ||
|
|
b9ffc82e53 | ||
|
|
78aaea6a45 | ||
|
|
3645fbf161 | ||
|
|
a1d0f22132 | ||
|
|
fa73b0f4bf | ||
|
|
3b76a8b839 | ||
|
|
667f42dcdc | ||
|
|
dfbe09860f | ||
|
|
9e20f9c26a | ||
|
|
f968d0cb82 | ||
|
|
2ad84f4379 | ||
|
|
c7aa16426f | ||
|
|
5987f8e3b5 | ||
|
|
3a8eb72de2 | ||
|
|
33abbdfd24 | ||
|
|
0703d6cbff | ||
|
|
10d2d14938 | ||
|
|
691cf1d8d6 | ||
|
|
d1decb8e58 | ||
|
|
7d04904109 | ||
|
|
a5acd3aa97 | ||
|
|
eea9a12560 | ||
|
|
0a4570b55c |
24
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
24
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -13,8 +13,8 @@ Please verify that you've followed these steps
|
|||||||
"
|
"
|
||||||
options:
|
options:
|
||||||
- label: "
|
- label: "
|
||||||
确保你使用的是**本仓库**最新的的 clash 或 clash Alpha 版本
|
确保你使用的是**本仓库**最新的的 mihomo 或 mihomo Alpha 版本
|
||||||
Ensure you are using the latest version of Clash or Clash Premium from **this repository**.
|
Ensure you are using the latest version of Mihomo or Mihomo Alpha from **this repository**.
|
||||||
"
|
"
|
||||||
required: true
|
required: true
|
||||||
- label: "
|
- label: "
|
||||||
@@ -38,14 +38,14 @@ I have read the [documentation](https://wiki.metacubex.one/) and was unable to s
|
|||||||
"
|
"
|
||||||
required: true
|
required: true
|
||||||
- label: "
|
- label: "
|
||||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
这是 Mihomo 核心的问题,并非我所使用的 Mihomo 衍生版本(如 OpenMihomo、KoolMihomo 等)的特定问题
|
||||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
This is an issue of the Mihomo core *per se*, not to the derivatives of Mihomo, like OpenMihomo or KoolMihomo.
|
||||||
"
|
"
|
||||||
required: true
|
required: true
|
||||||
- type: input
|
- type: input
|
||||||
attributes:
|
attributes:
|
||||||
label: Clash version
|
label: Mihomo version
|
||||||
description: "use `clash -v`"
|
description: "use `mihomo -v`"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
@@ -61,20 +61,20 @@ This is an issue of the Clash core *per se*, not to the derivatives of Clash, li
|
|||||||
- type: textarea
|
- type: textarea
|
||||||
attributes:
|
attributes:
|
||||||
render: yaml
|
render: yaml
|
||||||
label: "Clash config"
|
label: "Mihomo config"
|
||||||
description: "
|
description: "
|
||||||
在下方附上 Clash core 配置文件,请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等)
|
在下方附上 Mihomo core 配置文件,请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等)
|
||||||
Paste the Clash core configuration file below, please make sure that there is no sensitive information in the configuration file (e.g., server address/url, password, port)
|
Paste the Mihomo core configuration file below, please make sure that there is no sensitive information in the configuration file (e.g., server address/url, password, port)
|
||||||
"
|
"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
attributes:
|
attributes:
|
||||||
render: shell
|
render: shell
|
||||||
label: Clash log
|
label: Mihomo log
|
||||||
description: "
|
description: "
|
||||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
在下方附上 Mihomo Core 的日志,log level 使用 DEBUG
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
Paste the Mihomo core log below with the log level set to `DEBUG`.
|
||||||
"
|
"
|
||||||
- type: textarea
|
- type: textarea
|
||||||
attributes:
|
attributes:
|
||||||
|
|||||||
6
.github/ISSUE_TEMPLATE/config.yml
vendored
6
.github/ISSUE_TEMPLATE/config.yml
vendored
@@ -1,5 +1,5 @@
|
|||||||
blank_issues_enabled: false
|
blank_issues_enabled: false
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Clash.Meta Community Support
|
- name: mihomo Community Support
|
||||||
url: https://github.com/MetaCubeX/Clash.Meta/discussions
|
url: https://github.com/MetaCubeX/mihomo/discussions
|
||||||
about: Please ask and answer questions about Clash.Meta here.
|
about: Please ask and answer questions about mihomo here.
|
||||||
|
|||||||
2
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
2
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -25,7 +25,7 @@ I have read the [documentation](https://wiki.metacubex.one/) and was unable to s
|
|||||||
- type: textarea
|
- type: textarea
|
||||||
attributes:
|
attributes:
|
||||||
label: Description
|
label: Description
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Mihomo Core 的行为是什麽?
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
|
|||||||
32
.github/genReleaseNote.sh
vendored
Executable file
32
.github/genReleaseNote.sh
vendored
Executable file
@@ -0,0 +1,32 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
while getopts "v:" opt; do
|
||||||
|
case $opt in
|
||||||
|
v)
|
||||||
|
version_range=$OPTARG
|
||||||
|
;;
|
||||||
|
\?)
|
||||||
|
echo "Invalid option: -$OPTARG" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$version_range" ]; then
|
||||||
|
echo "Please provide the version range using -v option. Example: ./genReleashNote.sh -v v1.14.1...v1.14.2"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "## What's Changed" > release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "## BUG & Fix" >> release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "## Maintenance" >> release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "**Full Changelog**: https://github.com/MetaCubeX/mihomo/compare/$version_range" >> release.md
|
||||||
17
.github/mihomo.service
vendored
Normal file
17
.github/mihomo.service
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=mihomo Daemon, Another Clash Kernel.
|
||||||
|
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
LimitNPROC=500
|
||||||
|
LimitNOFILE=1000000
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
Restart=always
|
||||||
|
ExecStartPre=/usr/bin/sleep 2s
|
||||||
|
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
||||||
|
ExecReload=/bin/kill -HUP $MAINPID
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
54
.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
vendored
Normal file
54
.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
vendored
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
index 06e684c7116b4..b311a5c74684b 100644
|
||||||
|
--- a/src/syscall/exec_windows.go
|
||||||
|
+++ b/src/syscall/exec_windows.go
|
||||||
|
@@ -319,17 +319,6 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- var maj, min, build uint32
|
||||||
|
- rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
- isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
- // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
- // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
- // concerned about here. Except, the kernel will interpret some
|
||||||
|
- // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
- // checks to see that those bottom three bits are checked, but that top
|
||||||
|
- // bit is not checked.
|
||||||
|
- isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
-
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -338,15 +327,7 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- destinationProcessHandle := parentProcess
|
||||||
|
-
|
||||||
|
- // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
- // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
- if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
- destinationProcessHandle = p
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -377,14 +358,6 @@ func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
- // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
- // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
- for i := range fd {
|
||||||
|
- if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
- fd[i] = 0
|
||||||
|
- }
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
158
.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
vendored
Normal file
158
.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
vendored
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
index 62738e2cb1a7d..d0dcc7cc71fc0 100644
|
||||||
|
--- a/src/crypto/rand/rand.go
|
||||||
|
+++ b/src/crypto/rand/rand.go
|
||||||
|
@@ -15,7 +15,7 @@ import "io"
|
||||||
|
// available, /dev/urandom otherwise.
|
||||||
|
// On OpenBSD and macOS, Reader uses getentropy(2).
|
||||||
|
// On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
+// On Windows systems, Reader uses the ProcessPrng API.
|
||||||
|
// On JS/Wasm, Reader uses the Web Crypto API.
|
||||||
|
// On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.
|
||||||
|
var Reader io.Reader
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
index 6c0655c72b692..7380f1f0f1e6e 100644
|
||||||
|
--- a/src/crypto/rand/rand_windows.go
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go
|
||||||
|
@@ -15,11 +15,8 @@ func init() { Reader = &rngReader{} }
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (n int, err error) {
|
||||||
|
- // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
- // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
- // and 64-bit systems.
|
||||||
|
- if err := batched(windows.RtlGenRandom, 1<<31-1)(b); err != nil {
|
||||||
|
+func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
+ if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
index ab4ad2ec64108..5854ca60b5cef 100644
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
@@ -373,7 +373,7 @@ func ErrorLoadingGetTempPath2() error {
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
+//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
index e3f6d8d2a2208..5a587ad4f146c 100644
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
@@ -37,13 +37,14 @@ func errnoErr(e syscall.Errno) error {
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
- modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
- modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
- modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
- moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
- modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
+ modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -55,7 +56,7 @@ var (
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
+ procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -179,12 +180,12 @@ func SetTokenInformation(tokenHandle syscall.Token, tokenInformationClass uint32
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
+func ProcessPrng(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
index 8ca8d7790909e..3772a864b2ff4 100644
|
||||||
|
--- a/src/runtime/os_windows.go
|
||||||
|
+++ b/src/runtime/os_windows.go
|
||||||
|
@@ -127,15 +127,8 @@ var (
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
- // This approach has been recommended by Microsoft (see issue
|
||||||
|
- // 15589 for details).
|
||||||
|
- // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
- // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
- // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
- // when building executable as Cgo. So load SystemFunction036
|
||||||
|
- // manually during runtime startup.
|
||||||
|
- _RtlGenRandom stdFunction
|
||||||
|
+ // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
+ _ProcessPrng stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -151,11 +144,11 @@ var (
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
- advapi32dll = [...]uint16{'a', 'd', 'v', 'a', 'p', 'i', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
@@ -251,11 +244,11 @@ func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- a32 := windowsLoadSystemLib(advapi32dll[:])
|
||||||
|
- if a32 == 0 {
|
||||||
|
- throw("advapi32.dll not found")
|
||||||
|
+ bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
+ if bcryptPrimitives == 0 {
|
||||||
|
+ throw("bcryptprimitives.dll not found")
|
||||||
|
}
|
||||||
|
- _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+ _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
|
||||||
|
n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
if n32 == 0 {
|
||||||
|
@@ -531,7 +524,7 @@ func osinit() {
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
162
.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
vendored
Normal file
162
.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
vendored
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
index ab8656cbbf343..28c49cc6de7e7 100644
|
||||||
|
--- a/src/net/hook_windows.go
|
||||||
|
+++ b/src/net/hook_windows.go
|
||||||
|
@@ -14,7 +14,6 @@ var (
|
||||||
|
testHookDialChannel = func() { time.Sleep(time.Millisecond) } // see golang.org/issue/5349
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
- socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
index 0197feb3f199a..967ce6795aedb 100644
|
||||||
|
--- a/src/net/internal/socktest/main_test.go
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1
|
||||||
|
+//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
deleted file mode 100644
|
||||||
|
index df1cb97784b51..0000000000000
|
||||||
|
--- a/src/net/internal/socktest/main_windows_test.go
|
||||||
|
+++ /dev/null
|
||||||
|
@@ -1,22 +0,0 @@
|
||||||
|
-// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
-// Use of this source code is governed by a BSD-style
|
||||||
|
-// license that can be found in the LICENSE file.
|
||||||
|
-
|
||||||
|
-package socktest_test
|
||||||
|
-
|
||||||
|
-import "syscall"
|
||||||
|
-
|
||||||
|
-var (
|
||||||
|
- socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
- closeFunc func(syscall.Handle) error
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
-func installTestHooks() {
|
||||||
|
- socketFunc = sw.Socket
|
||||||
|
- closeFunc = sw.Closesocket
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
-func uninstallTestHooks() {
|
||||||
|
- socketFunc = syscall.Socket
|
||||||
|
- closeFunc = syscall.Closesocket
|
||||||
|
-}
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
index 8c1c862f33c9b..1c42e5c7f34b7 100644
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go
|
||||||
|
@@ -9,38 +9,6 @@ import (
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// Socket wraps syscall.Socket.
|
||||||
|
-func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
- sw.once.Do(sw.init)
|
||||||
|
-
|
||||||
|
- so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
- sw.fmu.RLock()
|
||||||
|
- f, _ := sw.fltab[FilterSocket]
|
||||||
|
- sw.fmu.RUnlock()
|
||||||
|
-
|
||||||
|
- af, err := f.apply(so)
|
||||||
|
- if err != nil {
|
||||||
|
- return syscall.InvalidHandle, err
|
||||||
|
- }
|
||||||
|
- s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
- if err = af.apply(so); err != nil {
|
||||||
|
- if so.Err == nil {
|
||||||
|
- syscall.Closesocket(s)
|
||||||
|
- }
|
||||||
|
- return syscall.InvalidHandle, err
|
||||||
|
- }
|
||||||
|
-
|
||||||
|
- sw.smu.Lock()
|
||||||
|
- defer sw.smu.Unlock()
|
||||||
|
- if so.Err != nil {
|
||||||
|
- sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
- return syscall.InvalidHandle, so.Err
|
||||||
|
- }
|
||||||
|
- nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
- sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
- return s, nil
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
index 07f21b72eb1fc..bc024c0bbd82d 100644
|
||||||
|
--- a/src/net/main_windows_test.go
|
||||||
|
+++ b/src/net/main_windows_test.go
|
||||||
|
@@ -8,7 +8,6 @@ import "internal/poll"
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
- origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -18,7 +17,6 @@ var (
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
- socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -28,7 +26,6 @@ func installTestHooks() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
- socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
index fa11c7af2e727..5540135a2c43e 100644
|
||||||
|
--- a/src/net/sock_windows.go
|
||||||
|
+++ b/src/net/sock_windows.go
|
||||||
|
@@ -19,21 +19,6 @@ func maxListenerBacklog() int {
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
- if err == nil {
|
||||||
|
- return s, nil
|
||||||
|
- }
|
||||||
|
- // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
- // old versions of Windows, see
|
||||||
|
- // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
- // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
-
|
||||||
|
- // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
- syscall.ForkLock.RLock()
|
||||||
|
- s, err = socketFunc(family, sotype, proto)
|
||||||
|
- if err == nil {
|
||||||
|
- syscall.CloseOnExec(s)
|
||||||
|
- }
|
||||||
|
- syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
index 0a93bc0a80d4e..06e684c7116b4 100644
|
||||||
|
--- a/src/syscall/exec_windows.go
|
||||||
|
+++ b/src/syscall/exec_windows.go
|
||||||
|
@@ -14,6 +14,7 @@ import (
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
26
.github/rename-cgo.sh
vendored
26
.github/rename-cgo.sh
vendored
@@ -5,25 +5,25 @@ for FILENAME in $FILENAMES
|
|||||||
do
|
do
|
||||||
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||||
echo "rename darwin-10.16-arm64 $FILENAME"
|
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||||
mv $FILENAME clash.meta-darwin-arm64-cgo
|
mv $FILENAME mihomo-darwin-arm64-cgo
|
||||||
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||||
echo "rename darwin-10.16-amd64 $FILENAME"
|
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||||
mv $FILENAME clash.meta-darwin-amd64-cgo
|
mv $FILENAME mihomo-darwin-amd64-cgo
|
||||||
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||||
echo "rename windows 386 $FILENAME"
|
echo "rename windows 386 $FILENAME"
|
||||||
mv $FILENAME clash.meta-windows-386-cgo.exe
|
mv $FILENAME mihomo-windows-386-cgo.exe
|
||||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
echo "rename windows amd64 $FILENAME"
|
echo "rename windows amd64 $FILENAME"
|
||||||
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
mv $FILENAME mihomo-windows-amd64-cgo.exe
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-5" ]];then
|
elif [[ $FILENAME =~ "mihomo-linux-arm-5" ]];then
|
||||||
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
echo "rename mihomo-linux-arm-5 $FILENAME"
|
||||||
mv $FILENAME clash.meta-linux-armv5-cgo
|
mv $FILENAME mihomo-linux-armv5-cgo
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
elif [[ $FILENAME =~ "mihomo-linux-arm-6" ]];then
|
||||||
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
echo "rename mihomo-linux-arm-6 $FILENAME"
|
||||||
mv $FILENAME clash.meta-linux-armv6-cgo
|
mv $FILENAME mihomo-linux-armv6-cgo
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
elif [[ $FILENAME =~ "mihomo-linux-arm-7" ]];then
|
||||||
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
echo "rename mihomo-linux-arm-7 $FILENAME"
|
||||||
mv $FILENAME clash.meta-linux-armv7-cgo
|
mv $FILENAME mihomo-linux-armv7-cgo
|
||||||
elif [[ $FILENAME =~ "linux" ]];then
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
echo "rename linux $FILENAME"
|
echo "rename linux $FILENAME"
|
||||||
mv $FILENAME $FILENAME-cgo
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
|||||||
16
.github/workflows/Delete.yml
vendored
Normal file
16
.github/workflows/Delete.yml
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
name: Delete old workflow runs
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 1 * *'
|
||||||
|
# Run monthly, at 00:00 on the 1st day of month.
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
del_runs:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Delete workflow runs
|
||||||
|
uses: GitRML/delete-workflow-runs@main
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.AUTH_PAT }}
|
||||||
|
repository: ${{ github.repository }}
|
||||||
|
retain_days: 30
|
||||||
69
.github/workflows/android-branch-auto-sync.yml
vendored
69
.github/workflows/android-branch-auto-sync.yml
vendored
@@ -1,69 +0,0 @@
|
|||||||
name: Android Branch Auto Sync
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
paths-ignore:
|
|
||||||
- "docs/**"
|
|
||||||
- "README.md"
|
|
||||||
- ".github/ISSUE_TEMPLATE/**"
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- android-open
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- android-open
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
update-dependencies:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout Repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Configure Git
|
|
||||||
run: |
|
|
||||||
git config --global user.name 'GitHub Action'
|
|
||||||
git config --global user.email 'action@github.com'
|
|
||||||
|
|
||||||
- name: Sync android-real with Alpha rebase android-open
|
|
||||||
run: |
|
|
||||||
git fetch origin
|
|
||||||
git checkout origin/Alpha -b android-real
|
|
||||||
git merge --squash origin/android-open
|
|
||||||
git commit -m "Android: patch"
|
|
||||||
|
|
||||||
- name: Check for conflicts
|
|
||||||
run: |
|
|
||||||
CONFLICTS=$(git diff --name-only --diff-filter=U)
|
|
||||||
if [ ! -z "$CONFLICTS" ]; then
|
|
||||||
echo "There are conflicts in the following files:"
|
|
||||||
echo $CONFLICTS
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Push changes
|
|
||||||
run: |
|
|
||||||
git push origin android-real --force
|
|
||||||
|
|
||||||
# Send "core-updated" to MetaCubeX/ClashMetaForAndroid to trigger update-dependencies
|
|
||||||
trigger-CMFA-update:
|
|
||||||
needs: update-dependencies
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: tibdex/github-app-token@v1
|
|
||||||
id: generate-token
|
|
||||||
with:
|
|
||||||
app_id: ${{ secrets.MAINTAINER_APPID }}
|
|
||||||
private_key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
|
||||||
|
|
||||||
- name: Trigger update-dependencies
|
|
||||||
run: |
|
|
||||||
curl -X POST https://api.github.com/repos/MetaCubeX/ClashMetaForAndroid/dispatches \
|
|
||||||
-H "Accept: application/vnd.github.everest-preview+json" \
|
|
||||||
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
|
||||||
-d '{"event_type": "core-updated"}'
|
|
||||||
608
.github/workflows/build.yml
vendored
608
.github/workflows/build.yml
vendored
@@ -1,6 +1,10 @@
|
|||||||
name: Build
|
name: Build
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Tag version to release"
|
||||||
|
required: true
|
||||||
push:
|
push:
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- "docs/**"
|
- "docs/**"
|
||||||
@@ -13,344 +17,435 @@ on:
|
|||||||
pull_request_target:
|
pull_request_target:
|
||||||
branches:
|
branches:
|
||||||
- Alpha
|
- Alpha
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.ref }}-${{ github.workflow }}
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: docker.io
|
REGISTRY: docker.io
|
||||||
jobs:
|
jobs:
|
||||||
Build:
|
build:
|
||||||
permissions: write-all
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
matrix:
|
||||||
job:
|
jobs:
|
||||||
- {
|
- { goos: darwin, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
target: "linux-amd64 linux-amd64-compatible",
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
id: "1",
|
|
||||||
}
|
- { goos: linux, goarch: '386', output: '386' }
|
||||||
- {
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible, test: test }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
- { goos: linux, goarch: arm64, output: arm64 }
|
||||||
id: "2",
|
- { goos: linux, goarch: arm, goarm: '5', output: armv5 }
|
||||||
}
|
- { goos: linux, goarch: arm, goarm: '6', output: armv6 }
|
||||||
- {
|
- { goos: linux, goarch: arm, goarm: '7', output: armv7 }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: mips, mips: hardfloat, output: mips-hardfloat }
|
||||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
- { goos: linux, goarch: mips, mips: softfloat, output: mips-softfloat }
|
||||||
id: "3",
|
- { goos: linux, goarch: mipsle, mips: hardfloat, output: mipsle-hardfloat }
|
||||||
}
|
- { goos: linux, goarch: mipsle, mips: softfloat, output: mipsle-softfloat }
|
||||||
- {
|
- { goos: linux, goarch: mips64, output: mips64 }
|
||||||
type: "WithoutCGO",
|
- { goos: linux, goarch: mips64le, output: mips64le }
|
||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
- { goos: linux, goarch: loong64, output: loong64-abi1, abi: '1' }
|
||||||
id: "4",
|
- { goos: linux, goarch: loong64, output: loong64-abi2, abi: '2' }
|
||||||
}
|
- { goos: linux, goarch: riscv64, output: riscv64 }
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
- { goos: linux, goarch: s390x, output: s390x }
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
- { goos: windows, goarch: '386', output: '386' }
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
id: "6",
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
}
|
- { goos: windows, goarch: arm, goarm: '7', output: armv7 }
|
||||||
- {
|
- { goos: windows, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
- { goos: freebsd, goarch: '386', output: '386' }
|
||||||
id: "7",
|
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-compatible }
|
||||||
}
|
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
- {
|
- { goos: freebsd, goarch: arm64, output: arm64 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-arm64 windows-arm32v7",
|
- { goos: android, goarch: '386', ndk: i686-linux-android34, output: '386' }
|
||||||
id: "8",
|
- { goos: android, goarch: amd64, ndk: x86_64-linux-android34, output: amd64 }
|
||||||
}
|
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
||||||
- {
|
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
# Go 1.21 can revert commit `9e4385` to work on Windows 7
|
||||||
id: "9",
|
# https://github.com/golang/go/issues/64622#issuecomment-1847475161
|
||||||
}
|
# (OR we can just use golang1.21.4 which unneeded any patch)
|
||||||
# only for test
|
- { goos: windows, goarch: '386', output: '386-go121', goversion: '1.21' }
|
||||||
- { type: "WithoutCGO-GO120", target: "linux-amd64 linux-amd64-compatible",id: "1" }
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go121, goversion: '1.21' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go121, goversion: '1.21' }
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
||||||
- { type: "WithoutCGO-GO120", target: "windows-amd64-compatible windows-amd64 windows-386",id: "2" }
|
- { goos: windows, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
|
|
||||||
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
||||||
- { type: "WithoutCGO-GO120", target: "darwin-amd64 darwin-arm64 android-arm64",id: "3" }
|
- { goos: darwin, goarch: arm64, output: arm64-go120, goversion: '1.20' }
|
||||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20' }
|
||||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
# only for test
|
||||||
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
- { goos: linux, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible-go120, goversion: '1.20', test: test }
|
||||||
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-go120, goversion: '1.20' }
|
||||||
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
|
||||||
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
|
||||||
- { type: "WithCGO", target: "android", id: "11" }
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out code into the Go module directory
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go
|
||||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.goarch != 'loong64' }}
|
||||||
shell: bash
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.goarch != 'loong64' }}
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
uses: actions/setup-go@v5
|
||||||
shell: bash
|
with:
|
||||||
|
go-version: ${{ matrix.jobs.goversion }}
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go1.22 loongarch abi1
|
||||||
if: ${{github.ref_name=='Beta'}}
|
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '1' }}
|
||||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: |
|
||||||
shell: bash
|
wget -q https://github.com/xishang0128/loongarch64-golang/releases/download/1.22.0/go1.22.0.linux-amd64-abi1.tar.gz
|
||||||
|
sudo tar zxf go1.22.0.linux-amd64-abi1.tar.gz -C /usr/local
|
||||||
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Set variables
|
- name: Set up Go1.22 loongarch abi2
|
||||||
if: ${{github.ref_name=='Meta'}}
|
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '2' }}
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: |
|
||||||
shell: bash
|
wget -q https://github.com/xishang0128/loongarch64-golang/releases/download/1.22.0/go1.22.0.linux-amd64-abi2.tar.gz
|
||||||
|
sudo tar zxf go1.22.0.linux-amd64-abi2.tar.gz -C /usr/local
|
||||||
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
- name: Set variables
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
# this patch file only works on golang1.22.x
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
# that means after golang1.23 release it must be changed
|
||||||
shell: bash
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
- name: Revert Golang1.22 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/693def151adff1af707d82d28f55dba81ceb08e1.diff
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/7c1157f9544922e96945196b47b95664b1e39108.diff
|
||||||
|
patch --verbose -R -p 1 < $GITHUB_WORKSPACE/.github/patch_go122/48042aa09c2f878c4faa576948b07fe625c4707a.diff
|
||||||
|
|
||||||
- name: Set ENV
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
run: |
|
- name: Revert Golang1.21 commit for Windows7/8
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
||||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
run: |
|
||||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
cd $(go env GOROOT)
|
||||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
curl https://github.com/golang/go/commit/9e43850a3298a9b8b1162ba0033d4c53f8637571.diff | patch --verbose -R -p 1
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
|
||||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
- name: Set variables
|
||||||
run: |
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
run: echo "VERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
shell: bash
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Set variables
|
||||||
if: ${{ matrix.job.type!='WithoutCGO-GO120' }}
|
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_name == 'Alpha' }}
|
||||||
uses: actions/setup-go@v4
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
with:
|
shell: bash
|
||||||
go-version: "1.21"
|
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Set Time Variable
|
||||||
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
run: |
|
||||||
uses: actions/setup-go@v4
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
with:
|
echo "CGO_ENABLED=0" >> $GITHUB_ENV
|
||||||
go-version: "1.20"
|
echo "BUILDTAG=-extldflags --static" >> $GITHUB_ENV
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Test
|
- name: Setup NDK
|
||||||
if: ${{ matrix.job.id=='1' && matrix.job.type!='WithCGO' }}
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
run: |
|
uses: nttld/setup-ndk@v1
|
||||||
go test ./...
|
id: setup-ndk
|
||||||
|
with:
|
||||||
|
ndk-version: r26c
|
||||||
|
|
||||||
- name: Build WithoutCGO
|
- name: Set NDK path
|
||||||
if: ${{ matrix.job.type!='WithCGO' }}
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
env:
|
run: |
|
||||||
NAME: Clash.Meta
|
echo "CC=${{steps.setup-ndk.outputs.ndk-path}}/toolchains/llvm/prebuilt/linux-x86_64/bin/${{matrix.jobs.ndk}}-clang" >> $GITHUB_ENV
|
||||||
BINDIR: bin
|
echo "CGO_ENABLED=1" >> $GITHUB_ENV
|
||||||
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
echo "BUILDTAG=" >> $GITHUB_ENV
|
||||||
|
|
||||||
- uses: nttld/setup-ndk@v1
|
- name: Test
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
if: ${{ matrix.jobs.test == 'test' }}
|
||||||
id: setup-ndk
|
run: |
|
||||||
with:
|
go test ./...
|
||||||
ndk-version: r26
|
|
||||||
add-to-path: false
|
|
||||||
local-cache: true
|
|
||||||
|
|
||||||
- name: Build Android
|
- name: Update CA
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
run: |
|
||||||
env:
|
sudo apt-get install ca-certificates
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
sudo update-ca-certificates
|
||||||
run: |
|
cp -f /etc/ssl/certs/ca-certificates.crt component/ca/ca-certificates.crt
|
||||||
mkdir bin
|
|
||||||
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
|
||||||
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
|
||||||
|
|
||||||
- name: Set up xgo
|
- name: Build core
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
env:
|
||||||
run: |
|
GOOS: ${{matrix.jobs.goos}}
|
||||||
docker pull techknowlogick/xgo:latest
|
GOARCH: ${{matrix.jobs.goarch}}
|
||||||
go install src.techknowlogick.com/xgo@latest
|
GOAMD64: ${{matrix.jobs.goamd64}}
|
||||||
|
GOARM: ${{matrix.jobs.arm}}
|
||||||
|
GOMIPS: ${{matrix.jobs.mips}}
|
||||||
|
run: |
|
||||||
|
echo $CGO_ENABLED
|
||||||
|
go build -v -tags "with_gvisor" -trimpath -ldflags "${BUILDTAG} -X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid="
|
||||||
|
if [ "${{matrix.jobs.goos}}" = "windows" ]; then
|
||||||
|
cp mihomo.exe mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
zip -r mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.zip mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
else
|
||||||
|
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
gzip -c mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}} > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.gz
|
||||||
|
rm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Build by xgo
|
- name: Create DEB package
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
||||||
env:
|
run: |
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
sudo apt-get install dpkg
|
||||||
run: |
|
if [ "${{matrix.jobs.abi}}" = "1" ]; then
|
||||||
mkdir bin
|
ARCH=loongarch64
|
||||||
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
else
|
||||||
|
ARCH=${{matrix.jobs.goarch}}
|
||||||
|
fi
|
||||||
|
PackageVersion=$(curl -s "https://api.github.com/repos/MetaCubeX/mihomo/releases/latest" | grep -o '"tag_name": "[^"]*' | grep -o '[^"]*$' | sed 's/v//g' )
|
||||||
|
if [ $(git branch | awk -F ' ' '{print $2}') = "Alpha" ]; then
|
||||||
|
PackageVersion="$(echo "${PackageVersion}" | awk -F '.' '{$NF = $NF + 1; print}' OFS='.')-${VERSION}"
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Rename
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN
|
||||||
if: ${{ matrix.job.type=='WithCGO' }}
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin
|
||||||
run: |
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo
|
||||||
cd bin
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
||||||
ls -la
|
mkdir -p mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo
|
||||||
cp ../.github/rename-cgo.sh ./
|
|
||||||
bash ./rename-cgo.sh
|
|
||||||
rm ./rename-cgo.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Rename
|
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/bin/mihomo
|
||||||
if: ${{ matrix.job.type=='WithoutCGO-GO120' }}
|
cp LICENSE mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/usr/share/licenses/mihomo/
|
||||||
run: |
|
cp .github/mihomo.service mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/systemd/system/
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
cp ../.github/rename-go120.sh ./
|
|
||||||
bash ./rename-go120.sh
|
|
||||||
rm ./rename-go120.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Zip
|
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/etc/mihomo/config.yaml <<EOF
|
||||||
if: ${{ success() }}
|
mixed-port: 7890
|
||||||
run: |
|
external-controller: 127.0.0.1:9090
|
||||||
cd bin
|
EOF
|
||||||
ls -la
|
|
||||||
chmod +x *
|
|
||||||
cp ../.github/release.sh ./
|
|
||||||
bash ./release.sh
|
|
||||||
rm ./release.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Save version
|
cat > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}/DEBIAN/control <<EOF
|
||||||
run: echo ${VERSION} > bin/version.txt
|
Package: mihomo
|
||||||
shell: bash
|
Version: ${PackageVersion}
|
||||||
|
Section:
|
||||||
|
Priority: extra
|
||||||
|
Architecture: ${ARCH}
|
||||||
|
Maintainer: MetaCubeX <none@example.com>
|
||||||
|
Homepage: https://wiki.metacubex.one/
|
||||||
|
Description: The universal proxy platform.
|
||||||
|
EOF
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
dpkg-deb -Z gzip --build mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
- name: Convert DEB to RPM
|
||||||
name: artifact
|
if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') }}
|
||||||
path: bin/
|
run: |
|
||||||
|
sudo apt-get install -y alien
|
||||||
|
alien --to-rpm --scripts mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
||||||
|
mv mihomo*.rpm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.rpm
|
||||||
|
|
||||||
|
# - name: Convert DEB to PKG
|
||||||
|
# if: ${{ matrix.jobs.goos == 'linux' && !contains(matrix.jobs.goarch, 'mips') && !contains(matrix.jobs.goarch, 'loong64') }}
|
||||||
|
# run: |
|
||||||
|
# docker pull archlinux
|
||||||
|
# docker run --rm -v ./:/mnt archlinux bash -c "
|
||||||
|
# pacman -Syu pkgfile base-devel --noconfirm
|
||||||
|
# curl -L https://github.com/helixarch/debtap/raw/master/debtap > /usr/bin/debtap
|
||||||
|
# chmod 755 /usr/bin/debtap
|
||||||
|
# debtap -u
|
||||||
|
# debtap -Q /mnt/mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb
|
||||||
|
# "
|
||||||
|
# mv mihomo*.pkg.tar.zst mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.pkg.tar.zst
|
||||||
|
|
||||||
|
- name: Save version
|
||||||
|
run: |
|
||||||
|
echo ${VERSION} > version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Archive production artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.jobs.goos }}-${{ matrix.jobs.output }}
|
||||||
|
path: |
|
||||||
|
mihomo*.gz
|
||||||
|
mihomo*.deb
|
||||||
|
mihomo*.rpm
|
||||||
|
mihomo*.zip
|
||||||
|
version.txt
|
||||||
|
|
||||||
Upload-Prerelease:
|
Upload-Prerelease:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='branch' && github.event_name != 'pull_request' }}
|
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v3
|
- name: Download all workflow run artifacts
|
||||||
with:
|
uses: actions/download-artifact@v4
|
||||||
name: artifact
|
with:
|
||||||
path: bin/
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Delete current release assets
|
||||||
run: ls -R
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
working-directory: bin
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
- name: Set Env
|
||||||
|
run: |
|
||||||
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
- name: Delete current release assets
|
- name: Tag Repo
|
||||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
uses: richardsimko/update-tag@v1
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
env:
|
||||||
deleteOnlyFromDrafts: false
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
cat > release.txt << 'EOF'
|
||||||
|
Release created at ${{ env.BUILDTIME }}
|
||||||
|
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||||
|
<br>
|
||||||
|
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
||||||
|
[二进制文件筛选 / Binary file selector](https://metacubex.github.io/Meta-Docs/startup/#_1)
|
||||||
|
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||||
|
EOF
|
||||||
|
|
||||||
- name: Set Env
|
- name: Upload Prerelease
|
||||||
run: |
|
uses: softprops/action-gh-release@v1
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
if: ${{ success() }}
|
||||||
shell: bash
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
- name: Tag Repo
|
files: |
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
bin/*
|
||||||
with:
|
prerelease: true
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
generate_release_notes: true
|
||||||
env:
|
body_path: release.txt
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- run: |
|
|
||||||
cat > release.txt << 'EOF'
|
|
||||||
Release created at ${{ env.BUILDTIME }}
|
|
||||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
|
||||||
<br>
|
|
||||||
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/Clash.Meta/wiki/FAQ)
|
|
||||||
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
|
||||||
bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
Upload-Release:
|
Upload-Release:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='tag' }}
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v3
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
name: artifact
|
ref: Meta
|
||||||
path: bin/
|
fetch-depth: '0'
|
||||||
|
fetch-tags: 'true'
|
||||||
|
|
||||||
|
- name: Get tags
|
||||||
|
run: |
|
||||||
|
echo "CURRENTVERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
git fetch --tags
|
||||||
|
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Merge Alpha branch into Meta
|
||||||
|
run: |
|
||||||
|
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git config --global user.name "github-actions[bot]"
|
||||||
|
git fetch origin Alpha:Alpha
|
||||||
|
git merge Alpha
|
||||||
|
git push origin Meta
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Tag the commit
|
||||||
|
run: |
|
||||||
|
git tag ${{ github.event.inputs.version }}
|
||||||
|
git push origin ${{ github.event.inputs.version }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Generate release notes
|
||||||
|
run: |
|
||||||
|
cp ./.github/genReleaseNote.sh ./
|
||||||
|
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
||||||
|
rm ./genReleaseNote.sh
|
||||||
|
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v2
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.event.inputs.version }}
|
||||||
files: bin/*
|
files: bin/*
|
||||||
generate_release_notes: true
|
body_path: release.md
|
||||||
|
|
||||||
Docker:
|
Docker:
|
||||||
if: ${{ github.event_name != 'pull_request' }}
|
if: ${{ !startsWith(github.event_name, 'pull_request') }}
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
needs: [Build]
|
needs: [build]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: artifact
|
|
||||||
path: bin/
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
- name: Display structure of downloaded files
|
||||||
run: ls -R
|
run: ls -R
|
||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
- name: Setup Docker buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
|
- name: Set Docker tags and labels based on trigger
|
||||||
|
id: set-meta
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||||
|
echo "tags=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
echo "labels=org.opencontainers.image.version=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
else
|
||||||
|
echo "tags=${{ steps.meta.outputs.tags }}" >> $GITHUB_ENV
|
||||||
|
echo "labels=${{ steps.meta.outputs.labels }}" >> $GITHUB_ENV
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
# Extract metadata (tags, labels) for Docker
|
||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v4
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
images: ${{ env.REGISTRY }}/${{ github.repository }}
|
||||||
|
tags: ${{ env.tags }}
|
||||||
|
labels: ${{ env.labels }}
|
||||||
|
|
||||||
|
|
||||||
- name: Show files
|
- name: Show files
|
||||||
run: |
|
run: |
|
||||||
ls .
|
ls .
|
||||||
ls bin/
|
ls bin/
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
- name: login to docker REGISTRY
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
@@ -360,7 +455,7 @@ jobs:
|
|||||||
# https://github.com/docker/build-push-action
|
# https://github.com/docker/build-push-action
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
id: build-and-push
|
id: build-and-push
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
@@ -368,8 +463,7 @@ jobs:
|
|||||||
platforms: |
|
platforms: |
|
||||||
linux/386
|
linux/386
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64/v8
|
linux/arm64
|
||||||
linux/arm/v7
|
linux/arm/v7
|
||||||
# linux/riscv64
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
33
.github/workflows/trigger-cmfa-update.yml
vendored
Normal file
33
.github/workflows/trigger-cmfa-update.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
name: Trigger CMFA Update
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
- ".github/ISSUE_TEMPLATE/**"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request_target:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Send "core-updated" to MetaCubeX/ClashMetaForAndroid to trigger update-dependencies
|
||||||
|
trigger-CMFA-update:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: tibdex/github-app-token@v1
|
||||||
|
id: generate-token
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.MAINTAINER_APPID }}
|
||||||
|
private_key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
|
- name: Trigger update-dependencies
|
||||||
|
run: |
|
||||||
|
curl -X POST https://api.github.com/repos/MetaCubeX/ClashMetaForAndroid/dispatches \
|
||||||
|
-H "Accept: application/vnd.github.everest-preview+json" \
|
||||||
|
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
||||||
|
-d '{"event_type": "core-updated"}'
|
||||||
@@ -11,7 +11,7 @@ linters-settings:
|
|||||||
custom-order: true
|
custom-order: true
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/Dreamacro/clash)
|
- prefix(github.com/metacubex/mihomo)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.19'
|
go: '1.19'
|
||||||
|
|||||||
28
Dockerfile
28
Dockerfile
@@ -3,25 +3,25 @@ ARG TARGETPLATFORM
|
|||||||
RUN echo "I'm building for $TARGETPLATFORM"
|
RUN echo "I'm building for $TARGETPLATFORM"
|
||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /clash-config && \
|
mkdir /mihomo-config && \
|
||||||
wget -O /clash-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
wget -O /mihomo-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
||||||
wget -O /clash-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
wget -O /mihomo-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geosite.dat && \
|
||||||
wget -O /clash-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
wget -O /mihomo-config/geoip.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
||||||
|
|
||||||
COPY docker/file-name.sh /clash/file-name.sh
|
COPY docker/file-name.sh /mihomo/file-name.sh
|
||||||
WORKDIR /clash
|
WORKDIR /mihomo
|
||||||
COPY bin/ bin/
|
COPY bin/ bin/
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.gz"|awk NR==1` && echo $FILE_NAME && \
|
||||||
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && echo "$FILE_NAME" > /mihomo-config/test
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata iptables
|
RUN apk add --no-cache ca-certificates tzdata iptables
|
||||||
|
|
||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/mihomo/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /mihomo-config/ /root/.config/mihomo/
|
||||||
COPY --from=builder /clash/clash /clash
|
COPY --from=builder /mihomo/mihomo /mihomo
|
||||||
RUN chmod +x /clash
|
RUN chmod +x /mihomo
|
||||||
ENTRYPOINT [ "/clash" ]
|
ENTRYPOINT [ "/mihomo" ]
|
||||||
|
|||||||
7
Makefile
7
Makefile
@@ -1,4 +1,4 @@
|
|||||||
NAME=clash.meta
|
NAME=mihomo
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
@@ -12,11 +12,12 @@ VERSION=$(shell git rev-parse --short HEAD)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/metacubex/mihomo/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/metacubex/mihomo/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
|
darwin-amd64-compatible \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64-compatible \
|
linux-amd64-compatible \
|
||||||
|
|||||||
27
README.md
27
README.md
@@ -3,17 +3,17 @@
|
|||||||
<br>Meta Kernel<br>
|
<br>Meta Kernel<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h3 align="center">Another Clash Kernel.</h3>
|
<h3 align="center">Another Mihomo Kernel.</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
<a href="https://goreportcard.com/report/github.com/MetaCubeX/mihomo">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/MetaCubeX/mihomo?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/MetaCubeX/mihomo/Alpha?style=flat-square">
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
<a href="https://github.com/MetaCubeX/mihomo/releases">
|
||||||
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/MetaCubeX/mihomo/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/MetaCubeX/mihomo">
|
||||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node
|
||||||
based off latency
|
based off latency
|
||||||
- Remote providers, allowing users to get node lists remotely instead of hard-coding in config
|
- Remote providers, allowing users to get node lists remotely instead of hard-coding in config
|
||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Mihomo on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Dashboard
|
## Dashboard
|
||||||
@@ -36,22 +36,22 @@ A web dashboard with first-class support for this project has been created; it c
|
|||||||
|
|
||||||
## Configration example
|
## Configration example
|
||||||
|
|
||||||
Configuration example is located at [/docs/config.yaml](https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml).
|
Configuration example is located at [/docs/config.yaml](https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml).
|
||||||
|
|
||||||
## Docs
|
## Docs
|
||||||
|
|
||||||
Documentation can be found in [Clash.Meta Docs](https://clash-meta.wiki).
|
Documentation can be found in [mihomo Docs](https://wiki.metacubex.one/).
|
||||||
|
|
||||||
## For development
|
## For development
|
||||||
|
|
||||||
Requirements:
|
Requirements:
|
||||||
[Go 1.20 or newer](https://go.dev/dl/)
|
[Go 1.20 or newer](https://go.dev/dl/)
|
||||||
|
|
||||||
Build Clash.Meta:
|
Build mihomo:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
git clone https://github.com/MetaCubeX/mihomo.git
|
||||||
cd Clash.Meta && go mod download
|
cd mihomo && go mod download
|
||||||
go build
|
go build
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -98,4 +98,3 @@ API.
|
|||||||
|
|
||||||
This software is released under the GPL-3.0 license.
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -12,14 +12,13 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
"github.com/metacubex/mihomo/common/queue"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/log"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/puzpuzpuz/xsync/v3"
|
||||||
"github.com/puzpuzpuz/xsync/v2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
@@ -28,22 +27,16 @@ const (
|
|||||||
defaultHistoriesNum = 10
|
defaultHistoriesNum = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
type extraProxyState struct {
|
type internalProxyState struct {
|
||||||
history *queue.Queue[C.DelayHistory]
|
|
||||||
alive atomic.Bool
|
alive atomic.Bool
|
||||||
|
history *queue.Queue[C.DelayHistory]
|
||||||
}
|
}
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue[C.DelayHistory]
|
|
||||||
alive atomic.Bool
|
alive atomic.Bool
|
||||||
url string
|
history *queue.Queue[C.DelayHistory]
|
||||||
extra *xsync.MapOf[string, *extraProxyState]
|
extra *xsync.MapOf[string, *internalProxyState]
|
||||||
}
|
|
||||||
|
|
||||||
// Alive implements C.Proxy
|
|
||||||
func (p *Proxy) Alive() bool {
|
|
||||||
return p.alive.Load()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AliveForTestUrl implements C.Proxy
|
// AliveForTestUrl implements C.Proxy
|
||||||
@@ -88,7 +81,6 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
histories = append(histories, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,11 +91,6 @@ func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
|||||||
if state, ok := p.extra.Load(url); ok {
|
if state, ok := p.extra.Load(url); ok {
|
||||||
queueM = state.history.Copy()
|
queueM = state.history.Copy()
|
||||||
}
|
}
|
||||||
|
|
||||||
if queueM == nil {
|
|
||||||
queueM = p.history.Copy()
|
|
||||||
}
|
|
||||||
|
|
||||||
histories := []C.DelayHistory{}
|
histories := []C.DelayHistory{}
|
||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
histories = append(histories, item)
|
||||||
@@ -111,61 +98,46 @@ func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
|||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Proxy) ExtraDelayHistory() map[string][]C.DelayHistory {
|
// ExtraDelayHistories return all delay histories for each test URL
|
||||||
extraHistory := map[string][]C.DelayHistory{}
|
// implements C.Proxy
|
||||||
|
func (p *Proxy) ExtraDelayHistories() map[string]C.ProxyState {
|
||||||
p.extra.Range(func(k string, v *extraProxyState) bool {
|
histories := map[string]C.ProxyState{}
|
||||||
|
|
||||||
|
p.extra.Range(func(k string, v *internalProxyState) bool {
|
||||||
testUrl := k
|
testUrl := k
|
||||||
state := v
|
state := v
|
||||||
|
|
||||||
histories := []C.DelayHistory{}
|
|
||||||
queueM := state.history.Copy()
|
queueM := state.history.Copy()
|
||||||
|
var history []C.DelayHistory
|
||||||
|
|
||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
history = append(history, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
extraHistory[testUrl] = histories
|
histories[testUrl] = C.ProxyState{
|
||||||
|
Alive: state.alive.Load(),
|
||||||
|
History: history,
|
||||||
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
return extraHistory
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
// LastDelayForTestUrl return last history record of the specified URL. if proxy is not alive, return the max value of uint16.
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) LastDelay() (delay uint16) {
|
|
||||||
var max uint16 = 0xffff
|
|
||||||
if !p.alive.Load() {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
history := p.history.Last()
|
|
||||||
if history.Delay == 0 {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
return history.Delay
|
|
||||||
}
|
|
||||||
|
|
||||||
// LastDelayForTestUrl implements C.Proxy
|
|
||||||
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
||||||
var max uint16 = 0xffff
|
var maxDelay uint16 = 0xffff
|
||||||
|
|
||||||
alive := p.alive.Load()
|
alive := false
|
||||||
history := p.history.Last()
|
var history C.DelayHistory
|
||||||
|
|
||||||
if state, ok := p.extra.Load(url); ok {
|
if state, ok := p.extra.Load(url); ok {
|
||||||
alive = state.alive.Load()
|
alive = state.alive.Load()
|
||||||
history = state.history.Last()
|
history = state.history.Last()
|
||||||
}
|
}
|
||||||
|
|
||||||
if !alive {
|
if !alive || history.Delay == 0 {
|
||||||
return max
|
return maxDelay
|
||||||
}
|
|
||||||
|
|
||||||
if history.Delay == 0 {
|
|
||||||
return max
|
|
||||||
}
|
}
|
||||||
return history.Delay
|
return history.Delay
|
||||||
}
|
}
|
||||||
@@ -180,8 +152,8 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping := map[string]any{}
|
mapping := map[string]any{}
|
||||||
_ = json.Unmarshal(inner, &mapping)
|
_ = json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["extra"] = p.ExtraDelayHistory()
|
mapping["extra"] = p.ExtraDelayHistories()
|
||||||
mapping["alive"] = p.Alive()
|
mapping["alive"] = p.alive.Load()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["xudp"] = p.SupportXUDP()
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
@@ -191,54 +163,42 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16], store C.DelayHistoryStoreType) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (t uint16, err error) {
|
||||||
|
var satisfied bool
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
alive := err == nil
|
alive := err == nil
|
||||||
store = p.determineFinalStoreType(store, url)
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
|
if alive {
|
||||||
switch store {
|
record.Delay = t
|
||||||
case C.OriginalHistory:
|
|
||||||
p.alive.Store(alive)
|
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
|
||||||
if alive {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
p.history.Put(record)
|
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
|
||||||
p.history.Pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// test URL configured by the proxy provider
|
|
||||||
if len(p.url) == 0 {
|
|
||||||
p.url = url
|
|
||||||
}
|
|
||||||
case C.ExtraHistory:
|
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
|
||||||
if alive {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
p.history.Put(record)
|
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
|
||||||
p.history.Pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
state, ok := p.extra.Load(url)
|
|
||||||
if !ok {
|
|
||||||
state = &extraProxyState{
|
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
|
||||||
alive: atomic.NewBool(true),
|
|
||||||
}
|
|
||||||
p.extra.Store(url, state)
|
|
||||||
}
|
|
||||||
|
|
||||||
state.alive.Store(alive)
|
|
||||||
state.history.Put(record)
|
|
||||||
if state.history.Len() > defaultHistoriesNum {
|
|
||||||
state.history.Pop()
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
log.Debugln("health check result will be discarded, url: %s alive: %t, delay: %d", url, alive, t)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
p.alive.Store(alive)
|
||||||
|
p.history.Put(record)
|
||||||
|
if p.history.Len() > defaultHistoriesNum {
|
||||||
|
p.history.Pop()
|
||||||
|
}
|
||||||
|
|
||||||
|
state, ok := p.extra.Load(url)
|
||||||
|
if !ok {
|
||||||
|
state = &internalProxyState{
|
||||||
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
|
alive: atomic.NewBool(true),
|
||||||
|
}
|
||||||
|
p.extra.Store(url, state)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !satisfied {
|
||||||
|
record.Delay = 0
|
||||||
|
alive = false
|
||||||
|
}
|
||||||
|
|
||||||
|
state.alive.Store(alive)
|
||||||
|
state.history.Put(record)
|
||||||
|
if state.history.Len() > defaultHistoriesNum {
|
||||||
|
state.history.Pop()
|
||||||
|
}
|
||||||
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
@@ -272,6 +232,7 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
@@ -301,22 +262,16 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if expectedStatus != nil && !expectedStatus.Check(uint16(resp.StatusCode)) {
|
satisfied = resp != nil && (expectedStatus == nil || expectedStatus.Check(uint16(resp.StatusCode)))
|
||||||
// maybe another value should be returned for differentiation
|
|
||||||
err = errors.New("response status is inconsistent with the expected status")
|
|
||||||
}
|
|
||||||
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{
|
return &Proxy{
|
||||||
ProxyAdapter: adapter,
|
ProxyAdapter: adapter,
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
alive: atomic.NewBool(true),
|
alive: atomic.NewBool(true),
|
||||||
url: "",
|
extra: xsync.NewMapOf[string, *internalProxyState]()}
|
||||||
extra: xsync.NewMapOf[*extraProxyState]()}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
@@ -349,24 +304,3 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Proxy) determineFinalStoreType(store C.DelayHistoryStoreType, url string) C.DelayHistoryStoreType {
|
|
||||||
if store != C.DropHistory {
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(p.url) == 0 || url == p.url {
|
|
||||||
return C.OriginalHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.extra.Size() < 2*C.DefaultMaxHealthCheckUrlNum {
|
|
||||||
return C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok := p.extra.Load(url)
|
|
||||||
if ok {
|
|
||||||
return C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Addition func(metadata *C.Metadata)
|
type Addition func(metadata *C.Metadata)
|
||||||
@@ -47,7 +47,7 @@ func WithDstAddr(addr net.Addr) Addition {
|
|||||||
func WithSrcAddr(addr net.Addr) Addition {
|
func WithSrcAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
metadata.SrcIP = m.DstIP
|
metadata.SrcIP = m.DstIP
|
||||||
metadata.SrcPort = m.DstPort
|
metadata.SrcPort = m.DstPort
|
||||||
}
|
}
|
||||||
@@ -57,9 +57,15 @@ func WithSrcAddr(addr net.Addr) Addition {
|
|||||||
func WithInAddr(addr net.Addr) Addition {
|
func WithInAddr(addr net.Addr) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
m := C.Metadata{}
|
m := C.Metadata{}
|
||||||
if err := m.SetRemoteAddr(addr);err ==nil{
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
metadata.InIP = m.DstIP
|
metadata.InIP = m.DstIP
|
||||||
metadata.InPort = m.DstPort
|
metadata.InPort = m.DstPort
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithDSCP(dscp uint8) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.DSCP = dscp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
var skipAuthPrefixes []netip.Prefix
|
var skipAuthPrefixes []netip.Prefix
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
@@ -12,7 +12,9 @@ func NewHTTP(target socks5.Addr, srcConn net.Conn, conn net.Conn, additions ...A
|
|||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
||||||
|
metadata.RawDstAddr = srcConn.LocalAddr()
|
||||||
|
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(srcConn.LocalAddr()))
|
||||||
ApplyAdditions(metadata, additions...)
|
ApplyAdditions(metadata, additions...)
|
||||||
return conn, metadata
|
return conn, metadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
|
|||||||
57
adapter/inbound/ipfilter.go
Normal file
57
adapter/inbound/ipfilter.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var lanAllowedIPs []netip.Prefix
|
||||||
|
var lanDisAllowedIPs []netip.Prefix
|
||||||
|
|
||||||
|
func SetAllowedIPs(prefixes []netip.Prefix) {
|
||||||
|
lanAllowedIPs = prefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetDisAllowedIPs(prefixes []netip.Prefix) {
|
||||||
|
lanDisAllowedIPs = prefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func AllowedIPs() []netip.Prefix {
|
||||||
|
return lanAllowedIPs
|
||||||
|
}
|
||||||
|
|
||||||
|
func DisAllowedIPs() []netip.Prefix {
|
||||||
|
return lanDisAllowedIPs
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsRemoteAddrDisAllowed(addr net.Addr) bool {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(addr); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return isAllowed(m.AddrPort().Addr().Unmap()) && !isDisAllowed(m.AddrPort().Addr().Unmap())
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAllowed(addr netip.Addr) bool {
|
||||||
|
if addr.IsValid() {
|
||||||
|
for _, prefix := range lanAllowedIPs {
|
||||||
|
if prefix.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDisAllowed(addr netip.Addr) bool {
|
||||||
|
if addr.IsValid() {
|
||||||
|
for _, prefix := range lanDisAllowedIPs {
|
||||||
|
if prefix.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
"github.com/metacubex/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
@@ -10,6 +10,8 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions
|
|||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
|
metadata.RawSrcAddr = packet.LocalAddr()
|
||||||
|
metadata.RawDstAddr = metadata.UDPAddr()
|
||||||
ApplyAdditions(metadata, WithSrcAddr(packet.LocalAddr()))
|
ApplyAdditions(metadata, WithSrcAddr(packet.LocalAddr()))
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
ApplyAdditions(metadata, WithInAddr(p.InAddr()))
|
ApplyAdditions(metadata, WithInAddr(p.InAddr()))
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/metacubex/mihomo/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
|
|||||||
@@ -5,14 +5,16 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/loopback"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
|
loopBack *loopback.Detector
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
type DirectOption struct {
|
||||||
@@ -22,17 +24,23 @@ type DirectOption struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
if err := d.loopBack.CheckConn(metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
N.TCPKeepAlive(c)
|
||||||
return NewConn(c, d), nil
|
return d.loopBack.NewConn(NewConn(c, d)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
if err := d.loopBack.CheckPacketConn(metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
||||||
@@ -45,7 +53,7 @@ func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(pc, d), nil
|
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirectWithOption(option DirectOption) *Direct {
|
func NewDirectWithOption(option DirectOption) *Direct {
|
||||||
@@ -60,6 +68,7 @@ func NewDirectWithOption(option DirectOption) *Direct {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,6 +80,7 @@ func NewDirect() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,5 +92,6 @@ func NewCompatible() *Direct {
|
|||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
159
adapter/outbound/dns.go
Normal file
159
adapter/outbound/dns.go
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Dns struct {
|
||||||
|
*Base
|
||||||
|
}
|
||||||
|
|
||||||
|
type DnsOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
left, right := N.Pipe()
|
||||||
|
go resolver.RelayDnsConn(context.Background(), right, 0)
|
||||||
|
return NewConn(left, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
log.Debugln("[DNS] hijack udp:%s from %s", metadata.RemoteAddress(), metadata.SourceAddrPort())
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
return newPacketConn(&dnsPacketConn{
|
||||||
|
response: make(chan dnsPacket, 1),
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
}, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type dnsPacket struct {
|
||||||
|
data []byte
|
||||||
|
put func()
|
||||||
|
addr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// dnsPacketConn implements net.PacketConn
|
||||||
|
type dnsPacketConn struct {
|
||||||
|
response chan dnsPacket
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
return packet.data, packet.put, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return nil, nil, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
n = copy(p, packet.data)
|
||||||
|
if packet.put != nil {
|
||||||
|
packet.put()
|
||||||
|
}
|
||||||
|
return n, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p) > resolver.SafeDnsPacketSize {
|
||||||
|
// wtf???
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := pool.Get(resolver.SafeDnsPacketSize)
|
||||||
|
put := func() { _ = pool.Put(buf) }
|
||||||
|
copy(buf, p) // avoid p be changed after WriteTo returned
|
||||||
|
|
||||||
|
go func() { // don't block the WriteTo function
|
||||||
|
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
||||||
|
if err != nil {
|
||||||
|
put()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
packet := dnsPacket{
|
||||||
|
data: buf,
|
||||||
|
put: put,
|
||||||
|
addr: addr,
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case d.response <- packet:
|
||||||
|
break
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) Close() error {
|
||||||
|
d.cancel()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) LocalAddr() net.Addr {
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: net.IPv4(127, 0, 0, 1),
|
||||||
|
Port: 53,
|
||||||
|
Zone: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDnsWithOption(option DnsOption) *Dns {
|
||||||
|
return &Dns{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Dns,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,11 +13,11 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Http struct {
|
type Http struct {
|
||||||
|
|||||||
@@ -14,17 +14,17 @@ import (
|
|||||||
"github.com/metacubex/quic-go/congestion"
|
"github.com/metacubex/quic-go/congestion"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
hyCongestion "github.com/metacubex/mihomo/transport/hysteria/congestion"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/core"
|
"github.com/metacubex/mihomo/transport/hysteria/core"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
"github.com/metacubex/mihomo/transport/hysteria/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
"github.com/metacubex/mihomo/transport/hysteria/transport"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/utils"
|
"github.com/metacubex/mihomo/transport/hysteria/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -8,23 +8,30 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
tuicCommon "github.com/Dreamacro/clash/transport/tuic/common"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||||
|
|
||||||
"github.com/metacubex/sing-quic/hysteria2"
|
"github.com/metacubex/sing-quic/hysteria2"
|
||||||
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const minHopInterval = 5
|
||||||
|
const defaultHopInterval = 30
|
||||||
|
|
||||||
type Hysteria2 struct {
|
type Hysteria2 struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
@@ -37,7 +44,9 @@ type Hysteria2Option struct {
|
|||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port,omitempty"`
|
||||||
|
Ports string `proxy:"ports,omitempty"`
|
||||||
|
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||||
Up string `proxy:"up,omitempty"`
|
Up string `proxy:"up,omitempty"`
|
||||||
Down string `proxy:"down,omitempty"`
|
Down string `proxy:"down,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
@@ -50,6 +59,7 @@ type Hysteria2Option struct {
|
|||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
CWND int `proxy:"cwnd,omitempty"`
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
|
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
@@ -117,12 +127,18 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if option.UdpMTU == 0 {
|
||||||
|
// "1200" from quic-go's MaxDatagramSize
|
||||||
|
// "-3" from quic-go's DatagramFrame.MaxDataLen
|
||||||
|
option.UdpMTU = 1200 - 3
|
||||||
|
}
|
||||||
|
|
||||||
singDialer := proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer())
|
singDialer := proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer())
|
||||||
|
|
||||||
clientOptions := hysteria2.ClientOptions{
|
clientOptions := hysteria2.ClientOptions{
|
||||||
Context: context.TODO(),
|
Context: context.TODO(),
|
||||||
Dialer: singDialer,
|
Dialer: singDialer,
|
||||||
ServerAddress: M.ParseSocksaddrHostPort(option.Server, uint16(option.Port)),
|
Logger: log.SingLogger,
|
||||||
SendBPS: StringToBps(option.Up),
|
SendBPS: StringToBps(option.Up),
|
||||||
ReceiveBPS: StringToBps(option.Down),
|
ReceiveBPS: StringToBps(option.Down),
|
||||||
SalamanderPassword: salamanderPassword,
|
SalamanderPassword: salamanderPassword,
|
||||||
@@ -130,6 +146,38 @@ func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|||||||
TLSConfig: tlsConfig,
|
TLSConfig: tlsConfig,
|
||||||
UDPDisabled: false,
|
UDPDisabled: false,
|
||||||
CWND: option.CWND,
|
CWND: option.CWND,
|
||||||
|
UdpMTU: option.UdpMTU,
|
||||||
|
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, C.NewDNSPrefer(option.IPVersion))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var ranges utils.IntRanges[uint16]
|
||||||
|
var serverAddress []string
|
||||||
|
if option.Ports != "" {
|
||||||
|
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ranges.Range(func(port uint16) bool {
|
||||||
|
serverAddress = append(serverAddress, net.JoinHostPort(option.Server, strconv.Itoa(int(port))))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if len(serverAddress) > 0 {
|
||||||
|
clientOptions.ServerAddress = func(ctx context.Context) (*net.UDPAddr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer(ctx, "udp", serverAddress[fastrand.Intn(len(serverAddress))], C.NewDNSPrefer(option.IPVersion))
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.HopInterval == 0 {
|
||||||
|
option.HopInterval = defaultHopInterval
|
||||||
|
} else if option.HopInterval < minHopInterval {
|
||||||
|
option.HopInterval = minHopInterval
|
||||||
|
}
|
||||||
|
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.Port == 0 && len(serverAddress) == 0 {
|
||||||
|
return nil, errors.New("invalid port")
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := hysteria2.NewClient(clientOptions)
|
client, err := hysteria2.NewClient(clientOptions)
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package outbound
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ecdh"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
|
||||||
"golang.org/x/crypto/curve25519"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type RealityOptions struct {
|
type RealityOptions struct {
|
||||||
@@ -19,10 +19,16 @@ func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
|||||||
if o.PublicKey != "" {
|
if o.PublicKey != "" {
|
||||||
config := new(tlsC.RealityConfig)
|
config := new(tlsC.RealityConfig)
|
||||||
|
|
||||||
n, err := base64.RawURLEncoding.Decode(config.PublicKey[:], []byte(o.PublicKey))
|
const x25519ScalarSize = 32
|
||||||
if err != nil || n != curve25519.ScalarSize {
|
var publicKey [x25519ScalarSize]byte
|
||||||
|
n, err := base64.RawURLEncoding.Decode(publicKey[:], []byte(o.PublicKey))
|
||||||
|
if err != nil || n != x25519ScalarSize {
|
||||||
return nil, errors.New("invalid REALITY public key")
|
return nil, errors.New("invalid REALITY public key")
|
||||||
}
|
}
|
||||||
|
config.PublicKey, err = ecdh.X25519().NewPublicKey(publicKey[:])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fail to create REALITY public key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
||||||
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
||||||
|
|||||||
@@ -6,13 +6,14 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
|
drop bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type RejectOption struct {
|
type RejectOption struct {
|
||||||
@@ -21,12 +22,15 @@ type RejectOption struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
if r.drop {
|
||||||
|
return NewConn(dropConn{}, r), nil
|
||||||
|
}
|
||||||
return NewConn(nopConn{}, r), nil
|
return NewConn(nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return newPacketConn(nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRejectWithOption(option RejectOption) *Reject {
|
func NewRejectWithOption(option RejectOption) *Reject {
|
||||||
@@ -50,6 +54,18 @@ func NewReject() *Reject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewRejectDrop() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT-DROP",
|
||||||
|
tp: C.RejectDrop,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
drop: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func NewPass() *Reject {
|
func NewPass() *Reject {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@@ -63,35 +79,29 @@ func NewPass() *Reject {
|
|||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw nopConn) Read(b []byte) (int, error) {
|
func (rw nopConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
return io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw nopConn) Write(b []byte) (int, error) {
|
func (rw nopConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
||||||
return 0, io.EOF
|
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
}
|
func (rw nopConn) Close() error { return nil }
|
||||||
|
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
||||||
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
return io.EOF
|
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
}
|
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) Close() error { return nil }
|
|
||||||
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
|
||||||
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
return len(b), nil
|
||||||
|
}
|
||||||
|
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
return 0, nil, io.EOF
|
||||||
|
}
|
||||||
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||||
return nil, nil, nil, io.EOF
|
return nil, nil, nil, io.EOF
|
||||||
}
|
}
|
||||||
@@ -100,3 +110,19 @@ func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4U
|
|||||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
type dropConn struct{}
|
||||||
|
|
||||||
|
func (rw dropConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
||||||
|
func (rw dropConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
time.Sleep(C.DefaultDropTime)
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
func (rw dropConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
||||||
|
func (rw dropConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
|
func (rw dropConn) Close() error { return nil }
|
||||||
|
func (rw dropConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (rw dropConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw dropConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw dropConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw dropConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|||||||
@@ -7,19 +7,20 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/restls"
|
"github.com/metacubex/mihomo/transport/restls"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin"
|
||||||
|
|
||||||
restlsC "github.com/3andne/restls-client-go"
|
restlsC "github.com/3andne/restls-client-go"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/common/uot"
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
@@ -58,15 +59,16 @@ type simpleObfsOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type v2rayObfsOption struct {
|
type v2rayObfsOption struct {
|
||||||
Mode string `obfs:"mode"`
|
Mode string `obfs:"mode"`
|
||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
Path string `obfs:"path,omitempty"`
|
Path string `obfs:"path,omitempty"`
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
|
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
|
||||||
|
V2rayHttpUpgradeFastOpen bool `obfs:"v2ray-http-upgrade-fast-open,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type shadowTLSOption struct {
|
type shadowTLSOption struct {
|
||||||
@@ -164,12 +166,6 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -177,6 +173,12 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
}
|
}
|
||||||
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
||||||
}
|
}
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -186,7 +188,7 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(N.NewBindPacketConn(pc, addr))
|
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
|
||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,9 +211,9 @@ func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn,
|
|||||||
|
|
||||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||||
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
return newPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
|
||||||
} else {
|
} else {
|
||||||
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, C.ErrNotSupport
|
return nil, C.ErrNotSupport
|
||||||
@@ -260,16 +262,18 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
}
|
}
|
||||||
obfsMode = opts.Mode
|
obfsMode = opts.Mode
|
||||||
v2rayOption = &v2rayObfs.Option{
|
v2rayOption = &v2rayObfs.Option{
|
||||||
Host: opts.Host,
|
Host: opts.Host,
|
||||||
Path: opts.Path,
|
Path: opts.Path,
|
||||||
Headers: opts.Headers,
|
Headers: opts.Headers,
|
||||||
Mux: opts.Mux,
|
Mux: opts.Mux,
|
||||||
V2rayHttpUpgrade: opts.V2rayHttpUpgrade,
|
V2rayHttpUpgrade: opts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: opts.V2rayHttpUpgradeFastOpen,
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.TLS {
|
if opts.TLS {
|
||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
|
v2rayOption.Fingerprint = opts.Fingerprint
|
||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
obfsMode = shadowtls.Mode
|
obfsMode = shadowtls.Mode
|
||||||
|
|||||||
@@ -7,16 +7,16 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
"github.com/metacubex/mihomo/transport/shadowsocks/shadowstream"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/metacubex/mihomo/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/metacubex/mihomo/transport/ssr/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
@@ -125,7 +125,7 @@ func (ssr *ShadowSocksR) SupportWithDialer() C.NetWork {
|
|||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
// SSR protocol compatibility
|
// SSR protocol compatibility
|
||||||
// https://github.com/Dreamacro/clash/pull/2056
|
// https://github.com/metacubex/mihomo/pull/2056
|
||||||
if option.Cipher == "none" {
|
if option.Cipher == "none" {
|
||||||
option.Cipher = "dummy"
|
option.Cipher = "dummy"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
mux "github.com/sagernet/sing-mux"
|
mux "github.com/sagernet/sing-mux"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
@@ -25,14 +26,21 @@ type SingMux struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SingMuxOption struct {
|
type SingMuxOption struct {
|
||||||
Enabled bool `proxy:"enabled,omitempty"`
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||||
MinStreams int `proxy:"min-streams,omitempty"`
|
MinStreams int `proxy:"min-streams,omitempty"`
|
||||||
MaxStreams int `proxy:"max-streams,omitempty"`
|
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||||
Padding bool `proxy:"padding,omitempty"`
|
Padding bool `proxy:"padding,omitempty"`
|
||||||
Statistic bool `proxy:"statistic,omitempty"`
|
Statistic bool `proxy:"statistic,omitempty"`
|
||||||
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
||||||
|
BrutalOpts BrutalOption `proxy:"brutal-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BrutalOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Up string `proxy:"up,omitempty"`
|
||||||
|
Down string `proxy:"down,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProxyBase interface {
|
type ProxyBase interface {
|
||||||
@@ -94,14 +102,23 @@ func closeSingMux(s *SingMux) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
||||||
|
// TODO
|
||||||
|
// "TCP Brutal is only supported on Linux-based systems"
|
||||||
|
|
||||||
singDialer := proxydialer.NewSingDialer(proxy, dialer.NewDialer(), option.Statistic)
|
singDialer := proxydialer.NewSingDialer(proxy, dialer.NewDialer(), option.Statistic)
|
||||||
client, err := mux.NewClient(mux.Options{
|
client, err := mux.NewClient(mux.Options{
|
||||||
Dialer: singDialer,
|
Dialer: singDialer,
|
||||||
|
Logger: log.SingLogger,
|
||||||
Protocol: option.Protocol,
|
Protocol: option.Protocol,
|
||||||
MaxConnections: option.MaxConnections,
|
MaxConnections: option.MaxConnections,
|
||||||
MinStreams: option.MinStreams,
|
MinStreams: option.MinStreams,
|
||||||
MaxStreams: option.MaxStreams,
|
MaxStreams: option.MaxStreams,
|
||||||
Padding: option.Padding,
|
Padding: option.Padding,
|
||||||
|
Brutal: mux.BrutalOptions{
|
||||||
|
Enabled: option.BrutalOpts.Enabled,
|
||||||
|
SendBPS: StringToBps(option.BrutalOpts.Up),
|
||||||
|
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/snell"
|
"github.com/metacubex/mihomo/transport/snell"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Snell struct {
|
type Snell struct {
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
|
|||||||
208
adapter/outbound/ssh.go
Normal file
208
adapter/outbound/ssh.go
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Ssh struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
option *SshOption
|
||||||
|
client *sshClient // using a standalone struct to avoid its inner loop invalidate the Finalizer
|
||||||
|
}
|
||||||
|
|
||||||
|
type SshOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
PrivateKeyPassphrase string `proxy:"private-key-passphrase,omitempty"`
|
||||||
|
HostKey []string `proxy:"host-key,omitempty"`
|
||||||
|
HostKeyAlgorithms []string `proxy:"host-key-algorithms,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Ssh) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions(opts...)...)
|
||||||
|
if len(s.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client, err := s.client.connect(ctx, cDialer, s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := client.DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(N.NewRefConn(c, s), s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type sshClient struct {
|
||||||
|
config *ssh.ClientConfig
|
||||||
|
client *ssh.Client
|
||||||
|
cMutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *sshClient) connect(ctx context.Context, cDialer C.Dialer, addr string) (client *ssh.Client, err error) {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client, nil
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
N.TCPKeepAlive(c)
|
||||||
|
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
client = ssh.NewClient(clientConn, chans, reqs)
|
||||||
|
|
||||||
|
s.client = client
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_ = client.Wait() // wait shutdown
|
||||||
|
_ = client.Close()
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client == client {
|
||||||
|
s.client = nil
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *sshClient) Close() error {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeSsh(s *Ssh) {
|
||||||
|
_ = s.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSsh(option SshOption) (*Ssh, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
config := ssh.ClientConfig{
|
||||||
|
User: option.UserName,
|
||||||
|
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||||
|
HostKeyAlgorithms: option.HostKeyAlgorithms,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.PrivateKey != "" {
|
||||||
|
var b []byte
|
||||||
|
var err error
|
||||||
|
if strings.Contains(option.PrivateKey, "PRIVATE KEY") {
|
||||||
|
b = []byte(option.PrivateKey)
|
||||||
|
} else {
|
||||||
|
b, err = os.ReadFile(C.Path.Resolve(option.PrivateKey))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var pKey ssh.Signer
|
||||||
|
if option.PrivateKeyPassphrase != "" {
|
||||||
|
pKey, err = ssh.ParsePrivateKeyWithPassphrase(b, []byte(option.PrivateKeyPassphrase))
|
||||||
|
} else {
|
||||||
|
pKey, err = ssh.ParsePrivateKey(b)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
config.Auth = append(config.Auth, ssh.PublicKeys(pKey))
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Password != "" {
|
||||||
|
config.Auth = append(config.Auth, ssh.Password(option.Password))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.HostKey) != 0 {
|
||||||
|
keys := make([]ssh.PublicKey, len(option.HostKey))
|
||||||
|
for i, hostKey := range option.HostKey {
|
||||||
|
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse host key :%s", key)
|
||||||
|
}
|
||||||
|
keys[i] = key
|
||||||
|
}
|
||||||
|
config.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||||
|
serverKey := key.Marshal()
|
||||||
|
for _, hostKey := range keys {
|
||||||
|
if bytes.Equal(serverKey, hostKey.Marshal()) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("host key mismatch, server send :%s %s", key.Type(), base64.StdEncoding.EncodeToString(serverKey))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
version := "SSH-2.0-OpenSSH_"
|
||||||
|
if fastrand.Intn(2) == 0 {
|
||||||
|
version += "7." + strconv.Itoa(fastrand.Intn(10))
|
||||||
|
} else {
|
||||||
|
version += "8." + strconv.Itoa(fastrand.Intn(9))
|
||||||
|
}
|
||||||
|
config.ClientVersion = version
|
||||||
|
|
||||||
|
outbound := &Ssh{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Ssh,
|
||||||
|
udp: false,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
client: &sshClient{
|
||||||
|
config: &config,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeSsh)
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
@@ -8,14 +8,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/metacubex/mihomo/transport/trojan"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@@ -53,10 +53,12 @@ func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error)
|
|||||||
if t.option.Network == "ws" {
|
if t.option.Network == "ws" {
|
||||||
host, port, _ := net.SplitHostPort(t.addr)
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
wsOpts := &trojan.WebsocketOption{
|
wsOpts := &trojan.WebsocketOption{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: t.option.WSOpts.Path,
|
Path: t.option.WSOpts.Path,
|
||||||
V2rayHttpUpgrade: t.option.WSOpts.V2rayHttpUpgrade,
|
V2rayHttpUpgrade: t.option.WSOpts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: t.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.SNI != "" {
|
if t.option.SNI != "" {
|
||||||
@@ -64,11 +66,9 @@ func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(t.option.WSOpts.Headers) != 0 {
|
if len(t.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range t.option.WSOpts.Headers {
|
for key, value := range t.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
"github.com/metacubex/mihomo/transport/tuic"
|
||||||
|
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/metacubex/quic-go"
|
"github.com/metacubex/quic-go"
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -140,24 +140,25 @@ func StringToBps(s string) uint64 {
|
|||||||
if m == nil {
|
if m == nil {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
var n uint64
|
var n uint64 = 1
|
||||||
switch m[2] {
|
switch m[2] {
|
||||||
case "K":
|
|
||||||
n = 1 << 10
|
|
||||||
case "M":
|
|
||||||
n = 1 << 20
|
|
||||||
case "G":
|
|
||||||
n = 1 << 30
|
|
||||||
case "T":
|
case "T":
|
||||||
n = 1 << 40
|
n *= 1000
|
||||||
default:
|
fallthrough
|
||||||
n = 1
|
case "G":
|
||||||
|
n *= 1000
|
||||||
|
fallthrough
|
||||||
|
case "M":
|
||||||
|
n *= 1000
|
||||||
|
fallthrough
|
||||||
|
case "K":
|
||||||
|
n *= 1000
|
||||||
}
|
}
|
||||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
n = v * n
|
n *= v
|
||||||
if m[3] == "b" {
|
if m[3] == "b" {
|
||||||
// Bits, need to convert to bytes
|
// Bits, need to convert to bytes
|
||||||
n = n >> 3
|
n /= 8
|
||||||
}
|
}
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,20 +12,20 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/metacubex/mihomo/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
vmessSing "github.com/metacubex/sing-vmess"
|
vmessSing "github.com/metacubex/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
@@ -88,14 +88,15 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
case "ws":
|
case "ws":
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
Headers: http.Header{},
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
@@ -372,7 +373,7 @@ func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metada
|
|||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
), v), nil
|
), v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(N.NewThreadSafePacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
|||||||
@@ -11,17 +11,17 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/ntp"
|
"github.com/metacubex/mihomo/ntp"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
vmess "github.com/metacubex/sing-vmess"
|
vmess "github.com/metacubex/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
@@ -87,11 +87,12 @@ type GrpcOptions struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type WSOptions struct {
|
type WSOptions struct {
|
||||||
Path string `proxy:"path,omitempty"`
|
Path string `proxy:"path,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
V2rayHttpUpgrade bool `proxy:"v2ray-http-upgrade,omitempty"`
|
V2rayHttpUpgrade bool `proxy:"v2ray-http-upgrade,omitempty"`
|
||||||
|
V2rayHttpUpgradeFastOpen bool `proxy:"v2ray-http-upgrade-fast-open,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
@@ -105,15 +106,16 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &clashVMess.WebsocketConfig{
|
wsOpts := &mihomoVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
Headers: http.Header{},
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
@@ -141,12 +143,12 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
@@ -157,26 +159,27 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &clashVMess.HTTPConfig{
|
httpOpts := &mihomoVMess.HTTPConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Method: v.option.HTTPOpts.Method,
|
Method: v.option.HTTPOpts.Method,
|
||||||
Path: v.option.HTTPOpts.Path,
|
Path: v.option.HTTPOpts.Path,
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
}
|
}
|
||||||
|
|
||||||
c = clashVMess.StreamHTTPConn(c, httpOpts)
|
c = mihomoVMess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := clashVMess.TLSConfig{
|
tlsOpts := mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
@@ -186,26 +189,27 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &clashVMess.H2Config{
|
h2Opts := &mihomoVMess.H2Config{
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
c, err = mihomoVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
Reality: v.realityConfig,
|
||||||
NextProtos: v.option.ALPN,
|
NextProtos: v.option.ALPN,
|
||||||
@@ -215,7 +219,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,13 +13,15 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
CN "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/metacubex/mihomo/component/slowdown"
|
||||||
"github.com/Dreamacro/clash/log"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/dns"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
@@ -36,16 +38,25 @@ type WireGuard struct {
|
|||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer proxydialer.SingDialer
|
dialer proxydialer.SingDialer
|
||||||
startOnce sync.Once
|
|
||||||
startErr error
|
|
||||||
resolver *dns.Resolver
|
resolver *dns.Resolver
|
||||||
refP *refProxyAdapter
|
refP *refProxyAdapter
|
||||||
|
|
||||||
|
initOk atomic.Bool
|
||||||
|
initMutex sync.Mutex
|
||||||
|
initErr error
|
||||||
|
option WireGuardOption
|
||||||
|
connectAddr M.Socksaddr
|
||||||
|
localPrefixes []netip.Prefix
|
||||||
|
|
||||||
|
closeCh chan struct{} // for test
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardOption struct {
|
type WireGuardOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
WireGuardPeerOption
|
WireGuardPeerOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
PrivateKey string `proxy:"private-key"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
Workers int `proxy:"workers,omitempty"`
|
Workers int `proxy:"workers,omitempty"`
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
@@ -61,8 +72,6 @@ type WireGuardOption struct {
|
|||||||
type WireGuardPeerOption struct {
|
type WireGuardPeerOption struct {
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PublicKey string `proxy:"public-key,omitempty"`
|
PublicKey string `proxy:"public-key,omitempty"`
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
@@ -97,7 +106,7 @@ func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
|||||||
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (option WireGuardPeerOption) Prefixes() ([]netip.Prefix, error) {
|
func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
if len(option.Ip) > 0 {
|
if len(option.Ip) > 0 {
|
||||||
if !strings.Contains(option.Ip, "/") {
|
if !strings.Contains(option.Ip, "/") {
|
||||||
@@ -136,7 +145,7 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
dialer: proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer()),
|
dialer: proxydialer.NewSlowDownSingDialer(proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer()), slowdown.New()),
|
||||||
}
|
}
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
@@ -148,125 +157,83 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
copy(reserved[:], option.Reserved)
|
copy(reserved[:], option.Reserved)
|
||||||
}
|
}
|
||||||
var isConnect bool
|
var isConnect bool
|
||||||
var connectAddr M.Socksaddr
|
|
||||||
if len(option.Peers) < 2 {
|
if len(option.Peers) < 2 {
|
||||||
isConnect = true
|
isConnect = true
|
||||||
if len(option.Peers) == 1 {
|
if len(option.Peers) == 1 {
|
||||||
connectAddr = option.Peers[0].Addr()
|
outbound.connectAddr = option.Peers[0].Addr()
|
||||||
} else {
|
} else {
|
||||||
connectAddr = option.Addr()
|
outbound.connectAddr = option.Addr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
|
||||||
|
|
||||||
var localPrefixes []netip.Prefix
|
var err error
|
||||||
|
outbound.localPrefixes, err = option.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var privateKey string
|
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode private key")
|
return nil, E.Cause(err, "decode private key")
|
||||||
}
|
}
|
||||||
privateKey = hex.EncodeToString(bytes)
|
option.PrivateKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
ipcConf := "private_key=" + privateKey
|
|
||||||
if peersLen := len(option.Peers); peersLen > 0 {
|
if len(option.Peers) > 0 {
|
||||||
localPrefixes = make([]netip.Prefix, 0, peersLen*2)
|
for i := range option.Peers {
|
||||||
for i, peer := range option.Peers {
|
peer := &option.Peers[i] // we need modify option here
|
||||||
var peerPublicKey, preSharedKey string
|
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
||||||
{
|
if err != nil {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
return nil, E.Cause(err, "decode public key for peer ", i)
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode public key for peer ", i)
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
}
|
||||||
|
peer.PublicKey = hex.EncodeToString(bytes)
|
||||||
|
|
||||||
if peer.PreSharedKey != "" {
|
if peer.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
||||||
}
|
}
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
peer.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
}
|
|
||||||
destination := peer.Addr()
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + destination.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(peer.AllowedIPs) == 0 {
|
if len(peer.AllowedIPs) == 0 {
|
||||||
return nil, E.New("missing allowed_ips for peer ", i)
|
return nil, E.New("missing allowed_ips for peer ", i)
|
||||||
}
|
}
|
||||||
for _, allowedIP := range peer.AllowedIPs {
|
|
||||||
ipcConf += "\nallowed_ip=" + allowedIP
|
|
||||||
}
|
|
||||||
if len(peer.Reserved) > 0 {
|
if len(peer.Reserved) > 0 {
|
||||||
if len(peer.Reserved) != 3 {
|
if len(peer.Reserved) != 3 {
|
||||||
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
||||||
}
|
}
|
||||||
copy(reserved[:], option.Reserved)
|
|
||||||
outbound.bind.SetReservedForEndpoint(destination, reserved)
|
|
||||||
}
|
}
|
||||||
prefixes, err := peer.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
localPrefixes = append(localPrefixes, prefixes...)
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var peerPublicKey, preSharedKey string
|
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
}
|
}
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
option.PublicKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
if option.PreSharedKey != "" {
|
if option.PreSharedKey != "" {
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
}
|
}
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
option.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
}
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + connectAddr.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
localPrefixes, err = option.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
outbound.option = option
|
||||||
|
|
||||||
if option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
mtu := option.MTU
|
mtu := option.MTU
|
||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
if len(localPrefixes) == 0 {
|
if len(outbound.localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
var err error
|
outbound.tunDevice, err = wireguard.NewStackDevice(outbound.localPrefixes, uint32(mtu))
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
}
|
}
|
||||||
@@ -278,17 +245,9 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
}, option.Workers)
|
}, option.Workers)
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
|
||||||
}
|
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
|
||||||
}
|
|
||||||
//err = outbound.tunDevice.Start()
|
|
||||||
|
|
||||||
var has6 bool
|
var has6 bool
|
||||||
for _, address := range localPrefixes {
|
for _, address := range outbound.localPrefixes {
|
||||||
if !address.Addr().Unmap().Is4() {
|
if !address.Addr().Unmap().Is4() {
|
||||||
has6 = true
|
has6 = true
|
||||||
break
|
break
|
||||||
@@ -314,22 +273,125 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) resolve(ctx context.Context, address M.Socksaddr) (netip.AddrPort, error) {
|
||||||
|
if address.Addr.IsValid() {
|
||||||
|
return address.AddrPort(), nil
|
||||||
|
}
|
||||||
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", address.String(), w.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return netip.AddrPort{}, err
|
||||||
|
}
|
||||||
|
// net.ResolveUDPAddr maybe return 4in6 address, so unmap at here
|
||||||
|
addrPort := udpAddr.AddrPort()
|
||||||
|
return netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) init(ctx context.Context) error {
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w.initMutex.Lock()
|
||||||
|
defer w.initMutex.Unlock()
|
||||||
|
// double check like sync.Once
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if w.initErr != nil {
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.bind.ResetReservedForEndpoint()
|
||||||
|
ipcConf := "private_key=" + w.option.PrivateKey
|
||||||
|
if len(w.option.Peers) > 0 {
|
||||||
|
for i, peer := range w.option.Peers {
|
||||||
|
destination, err := w.resolve(ctx, peer.Addr())
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return E.Cause(err, "resolve endpoint domain for peer ", i)
|
||||||
|
}
|
||||||
|
ipcConf += "\npublic_key=" + peer.PublicKey
|
||||||
|
ipcConf += "\nendpoint=" + destination.String()
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + peer.PreSharedKey
|
||||||
|
}
|
||||||
|
for _, allowedIP := range peer.AllowedIPs {
|
||||||
|
ipcConf += "\nallowed_ip=" + allowedIP
|
||||||
|
}
|
||||||
|
if len(peer.Reserved) > 0 {
|
||||||
|
var reserved [3]uint8
|
||||||
|
copy(reserved[:], w.option.Reserved)
|
||||||
|
w.bind.SetReservedForEndpoint(destination, reserved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ipcConf += "\npublic_key=" + w.option.PublicKey
|
||||||
|
destination, err := w.resolve(ctx, w.connectAddr)
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return E.Cause(err, "resolve endpoint domain")
|
||||||
|
}
|
||||||
|
w.bind.SetConnectAddr(destination)
|
||||||
|
ipcConf += "\nendpoint=" + destination.String()
|
||||||
|
if w.option.PreSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + w.option.PreSharedKey
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range w.localPrefixes {
|
||||||
|
if address.Addr().Is4() {
|
||||||
|
has4 = true
|
||||||
|
} else {
|
||||||
|
has6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has4 {
|
||||||
|
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
||||||
|
}
|
||||||
|
if has6 {
|
||||||
|
ipcConf += "\nallowed_ip=::/0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", w.option.Name, ipcConf))
|
||||||
|
}
|
||||||
|
err := w.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = E.Cause(err, "setup wireguard")
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = err
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.initOk.Store(true)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func closeWireGuard(w *WireGuard) {
|
func closeWireGuard(w *WireGuard) {
|
||||||
if w.device != nil {
|
if w.device != nil {
|
||||||
w.device.Close()
|
w.device.Close()
|
||||||
}
|
}
|
||||||
_ = common.Close(w.tunDevice)
|
_ = common.Close(w.tunDevice)
|
||||||
|
if w.closeCh != nil {
|
||||||
|
close(w.closeCh)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
w.startOnce.Do(func() {
|
if err = w.init(ctx); err != nil {
|
||||||
w.startErr = w.tunDevice.Start()
|
return nil, err
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() || w.resolver != nil {
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
r := resolver.DefaultResolver
|
r := resolver.DefaultResolver
|
||||||
@@ -357,13 +419,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
options := w.Base.DialOptions(opts...)
|
options := w.Base.DialOptions(opts...)
|
||||||
w.dialer.SetDialer(dialer.NewDialer(options...))
|
w.dialer.SetDialer(dialer.NewDialer(options...))
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
w.startOnce.Do(func() {
|
if err = w.init(ctx); err != nil {
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
|
|||||||
44
adapter/outbound/wireguard_test.go
Normal file
44
adapter/outbound/wireguard_test.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
//go:build with_gvisor
|
||||||
|
|
||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWireGuardGC(t *testing.T) {
|
||||||
|
option := WireGuardOption{}
|
||||||
|
option.Server = "162.159.192.1"
|
||||||
|
option.Port = 2408
|
||||||
|
option.PrivateKey = "iOx7749AdqH3IqluG7+0YbGKd0m1mcEXAfGRzpy9rG8="
|
||||||
|
option.PublicKey = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
|
||||||
|
option.Ip = "172.16.0.2"
|
||||||
|
option.Ipv6 = "2606:4700:110:8d29:be92:3a6a:f4:c437"
|
||||||
|
option.Reserved = []uint8{51, 69, 125}
|
||||||
|
wg, err := NewWireGuard(option)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
closeCh := make(chan struct{})
|
||||||
|
wg.closeCh = closeCh
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||||
|
defer cancel()
|
||||||
|
err = wg.init(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
// must do a small sleep before test GC
|
||||||
|
// because it maybe deadlocks if w.device.Close call too fast after w.device.Start
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
wg = nil
|
||||||
|
runtime.GC()
|
||||||
|
select {
|
||||||
|
case <-closeCh:
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Error("timeout not GC")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
@@ -21,6 +21,8 @@ type Fallback struct {
|
|||||||
testUrl string
|
testUrl string
|
||||||
selected string
|
selected string
|
||||||
expectedStatus string
|
expectedStatus string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@@ -84,11 +86,14 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": f.testUrl,
|
"testUrl": f.testUrl,
|
||||||
"expected": f.expectedStatus,
|
"expectedStatus": f.expectedStatus,
|
||||||
|
"fixed": f.selected,
|
||||||
|
"hidden": f.Hidden,
|
||||||
|
"icon": f.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,13 +107,11 @@ func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
|||||||
proxies := f.GetProxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if len(f.selected) == 0 {
|
if len(f.selected) == 0 {
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if proxy.Name() == f.selected {
|
if proxy.Name() == f.selected {
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
return proxy
|
return proxy
|
||||||
} else {
|
} else {
|
||||||
@@ -135,12 +138,11 @@ func (f *Fallback) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
f.selected = name
|
f.selected = name
|
||||||
// if !p.Alive() {
|
|
||||||
if !p.AliveForTestUrl(f.testUrl) {
|
if !p.AliveForTestUrl(f.testUrl) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
defer cancel()
|
defer cancel()
|
||||||
expectedStatus, _ := utils.NewIntRanges[uint16](f.expectedStatus)
|
expectedStatus, _ := utils.NewUnsignedRanges[uint16](f.expectedStatus)
|
||||||
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus, C.ExtraHistory)
|
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -162,10 +164,14 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/metacubex/mihomo/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
@@ -31,20 +31,24 @@ type GroupBase struct {
|
|||||||
failedTesting atomic.Bool
|
failedTesting atomic.Bool
|
||||||
proxies [][]C.Proxy
|
proxies [][]C.Proxy
|
||||||
versions []atomic.Uint32
|
versions []atomic.Uint32
|
||||||
|
TestTimeout int
|
||||||
|
maxFailedTimes int
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
excludeFilter string
|
||||||
excludeType string
|
excludeType string
|
||||||
providers []provider.ProxyProvider
|
TestTimeout int
|
||||||
|
maxFailedTimes int
|
||||||
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var excludeFilterReg *regexp2.Regexp
|
var excludeFilterReg *regexp2.Regexp
|
||||||
if opt.excludeFilter != "" {
|
if opt.excludeFilter != "" {
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, regexp2.None)
|
||||||
}
|
}
|
||||||
var excludeTypeArray []string
|
var excludeTypeArray []string
|
||||||
if opt.excludeType != "" {
|
if opt.excludeType != "" {
|
||||||
@@ -54,7 +58,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
for _, filter := range strings.Split(opt.filter, "`") {
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
filterReg := regexp2.MustCompile(filter, 0)
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
filterRegs = append(filterRegs, filterReg)
|
filterRegs = append(filterRegs, filterReg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,6 +70,15 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
excludeTypeArray: excludeTypeArray,
|
excludeTypeArray: excludeTypeArray,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
|
TestTimeout: opt.TestTimeout,
|
||||||
|
maxFailedTimes: opt.maxFailedTimes,
|
||||||
|
}
|
||||||
|
|
||||||
|
if gb.TestTimeout == 0 {
|
||||||
|
gb.TestTimeout = 5000
|
||||||
|
}
|
||||||
|
if gb.maxFailedTimes == 0 {
|
||||||
|
gb.maxFailedTimes = 5
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
@@ -113,7 +126,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -137,7 +150,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for _, filterReg := range gb.filterRegs {
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -178,7 +191,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
name := p.Name()
|
name := p.Name()
|
||||||
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := gb.excludeFilterReg.MatchString(name); mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
@@ -202,7 +215,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus uti
|
|||||||
proxy := proxy
|
proxy := proxy
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
delay, err := proxy.URLTest(ctx, url, expectedStatus, C.DropHistory)
|
delay, err := proxy.URLTest(ctx, url, expectedStatus)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
lock.Lock()
|
lock.Lock()
|
||||||
mp[proxy.Name()] = delay
|
mp[proxy.Name()] = delay
|
||||||
@@ -222,7 +235,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus uti
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
||||||
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass || adapterType == C.RejectDrop {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,13 +253,13 @@ func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
|||||||
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||||
gb.failedTime = time.Now()
|
gb.failedTime = time.Now()
|
||||||
} else {
|
} else {
|
||||||
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
if time.Since(gb.failedTime) > time.Duration(gb.TestTimeout)*time.Millisecond {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
if gb.failedTimes >= gb.maxFailedTimes {
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
gb.healthCheck()
|
gb.healthCheck()
|
||||||
}
|
}
|
||||||
@@ -275,20 +288,8 @@ func (gb *GroupBase) healthCheck() {
|
|||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
|
||||||
return 5 * time.Second.Milliseconds()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) onDialSuccess() {
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
if !gb.failedTesting.Load() {
|
if !gb.failedTesting.Load() {
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) maxFailedTimes() int {
|
|
||||||
return 5
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
|
||||||
return 5 * time.Second
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/metacubex/mihomo/common/lru"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
@@ -29,6 +29,8 @@ type LoadBalance struct {
|
|||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
testUrl string
|
testUrl string
|
||||||
expectedStatus string
|
expectedStatus string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
@@ -150,7 +152,6 @@ func strategyRoundRobin(url string) strategyFn {
|
|||||||
for ; i < length; i++ {
|
for ; i < length; i++ {
|
||||||
id := (idx + i) % length
|
id := (idx + i) % length
|
||||||
proxy := proxies[id]
|
proxy := proxies[id]
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
i++
|
i++
|
||||||
return proxy
|
return proxy
|
||||||
@@ -169,7 +170,6 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := proxies[idx]
|
proxy := proxies[idx]
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
@@ -177,7 +177,6 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
|
|
||||||
// when availability is poor, traverse the entire list to get the available nodes
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
@@ -190,9 +189,9 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
func strategyStickySessions(url string) strategyFn {
|
func strategyStickySessions(url string) strategyFn {
|
||||||
ttl := time.Minute * 10
|
ttl := time.Minute * 10
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
lruCache := cache.New[uint64, int](
|
lruCache := lru.New[uint64, int](
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
lru.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
cache.WithSize[uint64, int](1000))
|
lru.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
@@ -204,7 +203,6 @@ func strategyStickySessions(url string) strategyFn {
|
|||||||
nowIdx := idx
|
nowIdx := idx
|
||||||
for i := 1; i < maxRetry; i++ {
|
for i := 1; i < maxRetry; i++ {
|
||||||
proxy := proxies[nowIdx]
|
proxy := proxies[nowIdx]
|
||||||
// if proxy.Alive() {
|
|
||||||
if proxy.AliveForTestUrl(url) {
|
if proxy.AliveForTestUrl(url) {
|
||||||
if nowIdx != idx {
|
if nowIdx != idx {
|
||||||
lruCache.Delete(key)
|
lruCache.Delete(key)
|
||||||
@@ -240,6 +238,8 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": lb.testUrl,
|
"testUrl": lb.testUrl,
|
||||||
"expectedStatus": lb.expectedStatus,
|
"expectedStatus": lb.expectedStatus,
|
||||||
|
"hidden": lb.Hidden,
|
||||||
|
"icon": lb.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -266,11 +266,15 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,12 +5,14 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/dlclark/regexp2"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/adapter/provider"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -22,21 +24,28 @@ var (
|
|||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
outbound.BasicOption
|
outbound.BasicOption
|
||||||
Name string `group:"name"`
|
Name string `group:"name"`
|
||||||
Type string `group:"type"`
|
Type string `group:"type"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
Use []string `group:"use,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
TestTimeout int `group:"timeout,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
ExcludeType string `group:"exclude-type,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExpectedStatus string `group:"expected-status,omitempty"`
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
|
ExcludeType string `group:"exclude-type,omitempty"`
|
||||||
|
ExpectedStatus string `group:"expected-status,omitempty"`
|
||||||
|
IncludeAll bool `group:"include-all,omitempty"`
|
||||||
|
IncludeAllProxies bool `group:"include-all-proxies,omitempty"`
|
||||||
|
IncludeAllProviders bool `group:"include-all-providers,omitempty"`
|
||||||
|
Hidden bool `group:"hidden,omitempty"`
|
||||||
|
Icon string `group:"icon,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
@@ -54,11 +63,38 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
|
if groupOption.IncludeAll {
|
||||||
|
groupOption.IncludeAllProviders = true
|
||||||
|
groupOption.IncludeAllProxies = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.IncludeAllProviders {
|
||||||
|
groupOption.Use = append(groupOption.Use, AllProviders...)
|
||||||
|
}
|
||||||
|
if groupOption.IncludeAllProxies {
|
||||||
|
if groupOption.Filter != "" {
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(groupOption.Filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
for _, p := range AllProxies {
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
|
if mat, _ := filterReg.MatchString(p); mat {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewIntRanges[uint16](groupOption.ExpectedStatus)
|
expectedStatus, err := utils.NewUnsignedRanges[uint16](groupOption.ExpectedStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
@@ -68,7 +104,29 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
status = "*"
|
status = "*"
|
||||||
}
|
}
|
||||||
groupOption.ExpectedStatus = status
|
groupOption.ExpectedStatus = status
|
||||||
testUrl := groupOption.URL
|
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
PDs, err := getProviders(providersMap, groupOption.Use)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// if test URL is empty, use the first health check URL of providers
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
for _, pd := range PDs {
|
||||||
|
if pd.HealthCheckURL() != "" {
|
||||||
|
groupOption.URL = pd.HealthCheckURL()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addTestUrlToProviders(PDs, groupOption.URL, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
||||||
|
}
|
||||||
|
providers = append(providers, PDs...)
|
||||||
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
@@ -80,47 +138,28 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
var url string
|
if groupOption.URL == "" {
|
||||||
var interval uint
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
}
|
||||||
|
|
||||||
// select don't need health check
|
// select don't need auto health check
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||||
if groupOption.URL == "" {
|
|
||||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
groupOption.Interval = 300
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
|
|
||||||
url = groupOption.URL
|
|
||||||
interval = uint(groupOption.Interval)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, url, interval, true, expectedStatus)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
||||||
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append([]types.ProxyProvider{pd}, providers...)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
|
||||||
list, err := getProviders(providersMap, groupOption.Use)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// different proxy groups use different test URL
|
|
||||||
addTestUrlToProviders(list, testUrl, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
|
||||||
|
|
||||||
providers = append(providers, list...)
|
|
||||||
} else {
|
|
||||||
groupOption.Filter = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
switch groupOption.Type {
|
switch groupOption.Type {
|
||||||
case "url-test":
|
case "url-test":
|
||||||
|
|||||||
64
adapter/outboundgroup/patch_android.go
Normal file
64
adapter/outboundgroup/patch_android.go
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
//go:build android && cmfa
|
||||||
|
|
||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProxyGroup interface {
|
||||||
|
C.ProxyAdapter
|
||||||
|
|
||||||
|
Providers() []provider.ProxyProvider
|
||||||
|
Proxies() []C.Proxy
|
||||||
|
Now() string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Providers() []provider.ProxyProvider {
|
||||||
|
return f.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Providers() []provider.ProxyProvider {
|
||||||
|
return lb.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Proxies() []C.Proxy {
|
||||||
|
return f.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Proxies() []C.Proxy {
|
||||||
|
return lb.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Now() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) Providers() []provider.ProxyProvider {
|
||||||
|
return r.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) Proxies() []C.Proxy {
|
||||||
|
return r.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) Now() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Providers() []provider.ProxyProvider {
|
||||||
|
return s.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Proxies() []C.Proxy {
|
||||||
|
return s.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Providers() []provider.ProxyProvider {
|
||||||
|
return u.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Proxies() []C.Proxy {
|
||||||
|
return u.GetProxies(false)
|
||||||
|
}
|
||||||
@@ -3,15 +3,18 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -106,8 +109,10 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": r.Type().String(),
|
"type": r.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"hidden": r.Hidden,
|
||||||
|
"icon": r.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,7 +160,11 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
|
5000,
|
||||||
|
5,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,16 +5,18 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
selected string
|
selected string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@@ -57,9 +59,11 @@ func (s *Selector) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"hidden": s.Hidden,
|
||||||
|
"icon": s.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,9 +114,13 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,18 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type urlTestOption func(*URLTest)
|
type urlTestOption func(*URLTest)
|
||||||
@@ -30,6 +33,8 @@ type URLTest struct {
|
|||||||
expectedStatus string
|
expectedStatus string
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
}
|
}
|
||||||
@@ -101,7 +106,7 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
if u.selected != "" {
|
if u.selected != "" {
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if !proxy.Alive() {
|
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if proxy.Name() == u.selected {
|
if proxy.Name() == u.selected {
|
||||||
@@ -113,8 +118,7 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
// min := fast.LastDelay()
|
minDelay := fast.LastDelayForTestUrl(u.testUrl)
|
||||||
min := fast.LastDelayForTestUrl(u.testUrl)
|
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
@@ -122,21 +126,18 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
fastNotExist = false
|
fastNotExist = false
|
||||||
}
|
}
|
||||||
|
|
||||||
// if !proxy.Alive() {
|
|
||||||
if !proxy.AliveForTestUrl(u.testUrl) {
|
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// delay := proxy.LastDelay()
|
|
||||||
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
||||||
if delay < min {
|
if delay < minDelay {
|
||||||
fast = proxy
|
fast = proxy
|
||||||
min = delay
|
minDelay = delay
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// tolerance
|
// tolerance
|
||||||
// if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
|
||||||
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
@@ -169,14 +170,45 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": u.testUrl,
|
"testUrl": u.testUrl,
|
||||||
"expected": u.expectedStatus,
|
"expectedStatus": u.expectedStatus,
|
||||||
|
"fixed": u.selected,
|
||||||
|
"hidden": u.Hidden,
|
||||||
|
"icon": u.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (map[string]uint16, error) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var lock sync.Mutex
|
||||||
|
mp := map[string]uint16{}
|
||||||
|
proxies := u.GetProxies(false)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
proxy := proxy
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
delay, err := proxy.URLTest(ctx, u.testUrl, expectedStatus)
|
||||||
|
if err == nil {
|
||||||
|
lock.Lock()
|
||||||
|
mp[proxy.Name()] = delay
|
||||||
|
lock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
if len(mp) == 0 {
|
||||||
|
return mp, fmt.Errorf("get delay: all proxies timeout")
|
||||||
|
} else {
|
||||||
|
return mp, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
@@ -203,12 +235,16 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
option.ExcludeType,
|
||||||
|
option.TestTimeout,
|
||||||
|
option.MaxFailedTimes,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
@@ -120,6 +120,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewDirectWithOption(*directOption)
|
proxy = outbound.NewDirectWithOption(*directOption)
|
||||||
|
case "dns":
|
||||||
|
dnsOptions := &outbound.DnsOption{}
|
||||||
|
err = decoder.Decode(mapping, dnsOptions)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewDnsWithOption(*dnsOptions)
|
||||||
case "reject":
|
case "reject":
|
||||||
rejectOption := &outbound.RejectOption{}
|
rejectOption := &outbound.RejectOption{}
|
||||||
err = decoder.Decode(mapping, rejectOption)
|
err = decoder.Decode(mapping, rejectOption)
|
||||||
@@ -127,6 +134,13 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewRejectWithOption(*rejectOption)
|
proxy = outbound.NewRejectWithOption(*rejectOption)
|
||||||
|
case "ssh":
|
||||||
|
sshOption := &outbound.SshOption{}
|
||||||
|
err = decoder.Decode(mapping, sshOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSsh(*sshOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,20 +6,16 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/metacubex/mihomo/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
defaultURLTestTimeout = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
type HealthCheckOption struct {
|
type HealthCheckOption struct {
|
||||||
URL string
|
URL string
|
||||||
Interval uint
|
Interval uint
|
||||||
@@ -42,6 +38,7 @@ type HealthCheck struct {
|
|||||||
lastTouch atomic.TypedValue[time.Time]
|
lastTouch atomic.TypedValue[time.Time]
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
singleDo *singledo.Single[struct{}]
|
singleDo *singledo.Single[struct{}]
|
||||||
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
@@ -104,12 +101,6 @@ func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// due to the time-consuming nature of health checks, a maximum of defaultMaxTestURLNum URLs can be set for testing
|
|
||||||
if len(hc.extra) > C.DefaultMaxHealthCheckUrlNum {
|
|
||||||
log.Debugln("skip add url: %s to health check because it has reached the maximum limit: %d", url, C.DefaultMaxHealthCheckUrlNum)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
||||||
splitAndAddFiltersToExtra(filter, option)
|
splitAndAddFiltersToExtra(filter, option)
|
||||||
hc.extra[url] = option
|
hc.extra[url] = option
|
||||||
@@ -148,6 +139,10 @@ func (hc *HealthCheck) stop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
|
if len(hc.proxies) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
id := utils.NewUUIDV4().String()
|
id := utils.NewUUIDV4().String()
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
@@ -177,13 +172,8 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
}
|
}
|
||||||
|
|
||||||
var filterReg *regexp2.Regexp
|
var filterReg *regexp2.Regexp
|
||||||
var store = C.OriginalHistory
|
|
||||||
var expectedStatus utils.IntRanges[uint16]
|
var expectedStatus utils.IntRanges[uint16]
|
||||||
if option != nil {
|
if option != nil {
|
||||||
if url != hc.url {
|
|
||||||
store = C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
expectedStatus = option.expectedStatus
|
expectedStatus = option.expectedStatus
|
||||||
if len(option.filters) != 0 {
|
if len(option.filters) != 0 {
|
||||||
filters := make([]string, 0, len(option.filters))
|
filters := make([]string, 0, len(option.filters))
|
||||||
@@ -191,24 +181,24 @@ func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *ex
|
|||||||
filters = append(filters, filter)
|
filters = append(filters, filter)
|
||||||
}
|
}
|
||||||
|
|
||||||
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), 0)
|
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), regexp2.None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
// skip proxies that do not require health check
|
// skip proxies that do not require health check
|
||||||
if filterReg != nil {
|
if filterReg != nil {
|
||||||
if match, _ := filterReg.FindStringMatch(proxy.Name()); match == nil {
|
if match, _ := filterReg.MatchString(proxy.Name()); !match {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), hc.timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
||||||
_, _ = p.URLTest(ctx, url, expectedStatus, store)
|
_, _ = p.URLTest(ctx, url, expectedStatus)
|
||||||
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
@@ -219,15 +209,19 @@ func (hc *HealthCheck) close() {
|
|||||||
hc.done <- struct{}{}
|
hc.done <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
func NewHealthCheck(proxies []C.Proxy, url string, timeout uint, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
||||||
if len(url) == 0 {
|
if url == "" {
|
||||||
interval = 0
|
|
||||||
expectedStatus = nil
|
expectedStatus = nil
|
||||||
|
interval = 0
|
||||||
|
}
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = 5000
|
||||||
}
|
}
|
||||||
|
|
||||||
return &HealthCheck{
|
return &HealthCheck{
|
||||||
proxies: proxies,
|
proxies: proxies,
|
||||||
url: url,
|
url: url,
|
||||||
|
timeout: time.Duration(timeout) * time.Millisecond,
|
||||||
extra: map[string]*extraOption{},
|
extra: map[string]*extraOption{},
|
||||||
interval: time.Duration(interval) * time.Second,
|
interval: time.Duration(interval) * time.Second,
|
||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/constant/features"
|
||||||
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -21,20 +22,38 @@ type healthCheckSchema struct {
|
|||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
URL string `provider:"url"`
|
URL string `provider:"url"`
|
||||||
Interval int `provider:"interval"`
|
Interval int `provider:"interval"`
|
||||||
|
TestTimeout int `provider:"timeout,omitempty"`
|
||||||
Lazy bool `provider:"lazy,omitempty"`
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
ExpectedStatus string `provider:"expected-status,omitempty"`
|
ExpectedStatus string `provider:"expected-status,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type OverrideSchema struct {
|
||||||
|
UDP *bool `provider:"udp,omitempty"`
|
||||||
|
Up *string `provider:"up,omitempty"`
|
||||||
|
Down *string `provider:"down,omitempty"`
|
||||||
|
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||||
|
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||||
|
Interface *string `provider:"interface-name,omitempty"`
|
||||||
|
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||||
|
IPVersion *string `provider:"ip-version,omitempty"`
|
||||||
|
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
||||||
|
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path,omitempty"`
|
Path string `provider:"path,omitempty"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Proxy string `provider:"proxy,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||||
|
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
Override OverrideSchema `provider:"override,omitempty"`
|
||||||
|
Header map[string][]string `provider:"header,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@@ -49,16 +68,19 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewIntRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
expectedStatus, err := utils.NewUnsignedRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var hcInterval uint
|
var hcInterval uint
|
||||||
if schema.HealthCheck.Enable {
|
if schema.HealthCheck.Enable {
|
||||||
|
if schema.HealthCheck.Interval == 0 {
|
||||||
|
schema.HealthCheck.Interval = 300
|
||||||
|
}
|
||||||
hcInterval = uint(schema.HealthCheck.Interval)
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
}
|
}
|
||||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||||
|
|
||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
@@ -66,16 +88,14 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
path := C.Path.Resolve(schema.Path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
vehicle = resource.NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
|
path := C.Path.GetPathByHash("proxies", schema.URL)
|
||||||
if schema.Path != "" {
|
if schema.Path != "" {
|
||||||
path := C.Path.Resolve(schema.Path)
|
path = C.Path.Resolve(schema.Path)
|
||||||
if !C.Path.IsSafePath(path) {
|
if !features.CMFA && !C.Path.IsSafePath(path) {
|
||||||
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
||||||
}
|
}
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
|
||||||
} else {
|
|
||||||
path := C.Path.GetPathByHash("proxies", schema.URL)
|
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
|
||||||
}
|
}
|
||||||
|
vehicle = resource.NewHTTPVehicle(schema.URL, path, schema.Proxy, schema.Header)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
@@ -85,6 +105,7 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
excludeFilter := schema.ExcludeFilter
|
excludeFilter := schema.ExcludeFilter
|
||||||
excludeType := schema.ExcludeType
|
excludeType := schema.ExcludeType
|
||||||
dialerProxy := schema.DialerProxy
|
dialerProxy := schema.DialerProxy
|
||||||
|
override := schema.Override
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, vehicle, hc)
|
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, override, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
|||||||
36
adapter/provider/patch_android.go
Normal file
36
adapter/provider/patch_android.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
//go:build android && cmfa
|
||||||
|
|
||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
suspended bool
|
||||||
|
)
|
||||||
|
|
||||||
|
type UpdatableProvider interface {
|
||||||
|
UpdatedAt() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) UpdatedAt() time.Time {
|
||||||
|
return pp.Fetcher.UpdatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Close() error {
|
||||||
|
pp.healthCheck.close()
|
||||||
|
pp.Fetcher.Destroy()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Close() error {
|
||||||
|
cp.healthCheck.close()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Suspend(s bool) {
|
||||||
|
suspended = s
|
||||||
|
}
|
||||||
@@ -10,15 +10,15 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/metacubex/mihomo/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
mihomoHttp "github.com/metacubex/mihomo/component/http"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/metacubex/mihomo/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
"github.com/Dreamacro/clash/tunnel/statistic"
|
"github.com/metacubex/mihomo/tunnel/statistic"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@@ -52,6 +52,7 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"testUrl": pp.healthCheck.url,
|
"testUrl": pp.healthCheck.url,
|
||||||
|
"expectedStatus": pp.healthCheck.expectedStatus.String(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
@@ -100,6 +101,10 @@ func (pp *proxySetProvider) Touch() {
|
|||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) HealthCheckURL() string {
|
||||||
|
return pp.healthCheck.url
|
||||||
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
@@ -119,8 +124,8 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp, err := mihomoHttp.HttpRequestWithProxy(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {C.UA}}, nil, pp.Vehicle().Proxy())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -128,8 +133,8 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
|
|
||||||
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
if userInfoStr == "" {
|
if userInfoStr == "" {
|
||||||
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
resp2, err := mihomoHttp.HttpRequestWithProxy(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil, pp.Vehicle().Proxy())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -163,8 +168,8 @@ func stopProxyProvider(pd *ProxySetProvider) {
|
|||||||
_ = pd.Fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, override OverrideSchema, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -175,7 +180,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
filterReg, err := regexp2.Compile(filter, regexp2.None)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
@@ -191,7 +196,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg, dialerProxy), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg, dialerProxy, override), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
@@ -212,11 +217,12 @@ type compatibleProvider struct {
|
|||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": cp.Name(),
|
"name": cp.Name(),
|
||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
"proxies": cp.Proxies(),
|
"proxies": cp.Proxies(),
|
||||||
"testUrl": cp.healthCheck.url,
|
"testUrl": cp.healthCheck.url,
|
||||||
|
"expectedStatus": cp.healthCheck.expectedStatus.String(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,6 +243,9 @@ func (cp *compatibleProvider) Update() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Initial() error {
|
func (cp *compatibleProvider) Initial() error {
|
||||||
|
if cp.healthCheck.interval != 0 && cp.healthCheck.url != "" {
|
||||||
|
cp.HealthCheck()
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,6 +265,10 @@ func (cp *compatibleProvider) Touch() {
|
|||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) HealthCheckURL() string {
|
||||||
|
return cp.healthCheck.url
|
||||||
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
}
|
}
|
||||||
@@ -292,7 +305,7 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string, override OverrideSchema) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@@ -343,25 +356,61 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(excludeFilter) > 0 {
|
if len(excludeFilter) > 0 {
|
||||||
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
if mat, _ := filterReg.MatchString(name); !mat {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, ok := proxiesSet[name]; ok {
|
if _, ok := proxiesSet[name]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(dialerProxy) > 0 {
|
if len(dialerProxy) > 0 {
|
||||||
mapping["dialer-proxy"] = dialerProxy
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if override.UDP != nil {
|
||||||
|
mapping["udp"] = *override.UDP
|
||||||
|
}
|
||||||
|
if override.Up != nil {
|
||||||
|
mapping["up"] = *override.Up
|
||||||
|
}
|
||||||
|
if override.Down != nil {
|
||||||
|
mapping["down"] = *override.Down
|
||||||
|
}
|
||||||
|
if override.DialerProxy != nil {
|
||||||
|
mapping["dialer-proxy"] = *override.DialerProxy
|
||||||
|
}
|
||||||
|
if override.SkipCertVerify != nil {
|
||||||
|
mapping["skip-cert-verify"] = *override.SkipCertVerify
|
||||||
|
}
|
||||||
|
if override.Interface != nil {
|
||||||
|
mapping["interface-name"] = *override.Interface
|
||||||
|
}
|
||||||
|
if override.RoutingMark != nil {
|
||||||
|
mapping["routing-mark"] = *override.RoutingMark
|
||||||
|
}
|
||||||
|
if override.IPVersion != nil {
|
||||||
|
mapping["ip-version"] = *override.IPVersion
|
||||||
|
}
|
||||||
|
if override.AdditionalPrefix != nil {
|
||||||
|
name := mapping["name"].(string)
|
||||||
|
mapping["name"] = *override.AdditionalPrefix + name
|
||||||
|
}
|
||||||
|
if override.AdditionalSuffix != nil {
|
||||||
|
name := mapping["name"].(string)
|
||||||
|
mapping["name"] = name + *override.AdditionalSuffix
|
||||||
|
}
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
proxiesSet[name] = struct{}{}
|
proxiesSet[name] = struct{}{}
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,11 @@ func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo, err error) {
|
|||||||
case "total":
|
case "total":
|
||||||
si.Total, err = strconv.ParseInt(value, 10, 64)
|
si.Total, err = strconv.ParseInt(value, 10, 64)
|
||||||
case "expire":
|
case "expire":
|
||||||
si.Expire, err = strconv.ParseInt(value, 10, 64)
|
if value == "" {
|
||||||
|
si.Expire = 0
|
||||||
|
} else {
|
||||||
|
si.Expire, err = strconv.ParseInt(value, 10, 64)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
21
android_tz.go
Normal file
21
android_tz.go
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
// Copyright 2014 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// kanged from https://github.com/golang/mobile/blob/c713f31d574bb632a93f169b2cc99c9e753fef0e/app/android.go#L89
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// #include <time.h>
|
||||||
|
import "C"
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
var currentT C.time_t
|
||||||
|
var currentTM C.struct_tm
|
||||||
|
C.time(¤tT)
|
||||||
|
C.localtime_r(¤tT, ¤tTM)
|
||||||
|
tzOffset := int(currentTM.tm_gmtoff)
|
||||||
|
tz := C.GoString(currentTM.tm_zone)
|
||||||
|
time.Local = time.FixedZone(tz, tzOffset)
|
||||||
|
}
|
||||||
235
common/arc/arc.go
Normal file
235
common/arc/arc.go
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
"github.com/samber/lo"
|
||||||
|
)
|
||||||
|
|
||||||
|
//modify from https://github.com/alexanderGugel/arc
|
||||||
|
|
||||||
|
// Option is part of Functional Options Pattern
|
||||||
|
type Option[K comparable, V any] func(*ARC[K, V])
|
||||||
|
|
||||||
|
func WithSize[K comparable, V any](maxSize int) Option[K, V] {
|
||||||
|
return func(a *ARC[K, V]) {
|
||||||
|
a.c = maxSize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ARC[K comparable, V any] struct {
|
||||||
|
p int
|
||||||
|
c int
|
||||||
|
t1 *list.List[*entry[K, V]]
|
||||||
|
b1 *list.List[*entry[K, V]]
|
||||||
|
t2 *list.List[*entry[K, V]]
|
||||||
|
b2 *list.List[*entry[K, V]]
|
||||||
|
mutex sync.Mutex
|
||||||
|
len int
|
||||||
|
cache map[K]*entry[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a new Adaptive Replacement Cache (ARC).
|
||||||
|
func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
||||||
|
arc := &ARC[K, V]{
|
||||||
|
p: 0,
|
||||||
|
t1: list.New[*entry[K, V]](),
|
||||||
|
b1: list.New[*entry[K, V]](),
|
||||||
|
t2: list.New[*entry[K, V]](),
|
||||||
|
b2: list.New[*entry[K, V]](),
|
||||||
|
len: 0,
|
||||||
|
cache: make(map[K]*entry[K, V]),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(arc)
|
||||||
|
}
|
||||||
|
return arc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set inserts a new key-value pair into the cache.
|
||||||
|
// This optimizes future access to this entry (side effect).
|
||||||
|
func (a *ARC[K, V]) Set(key K, value V) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
a.set(key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) set(key K, value V) {
|
||||||
|
a.setWithExpire(key, value, time.Unix(0, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetWithExpire stores any representation of a response for a given key and given expires.
|
||||||
|
// The expires time will round to second.
|
||||||
|
func (a *ARC[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
a.setWithExpire(key, value, expires)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
||||||
|
ent, ok := a.cache[key]
|
||||||
|
if !ok {
|
||||||
|
a.len++
|
||||||
|
ent := &entry[K, V]{key: key, value: value, ghost: false, expires: expires.Unix()}
|
||||||
|
a.req(ent)
|
||||||
|
a.cache[key] = ent
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ent.ghost {
|
||||||
|
a.len++
|
||||||
|
}
|
||||||
|
|
||||||
|
ent.value = value
|
||||||
|
ent.ghost = false
|
||||||
|
ent.expires = expires.Unix()
|
||||||
|
a.req(ent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a previously via Set inserted entry.
|
||||||
|
// This optimizes future access to this entry (side effect).
|
||||||
|
func (a *ARC[K, V]) Get(key K) (value V, ok bool) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
ent, ok := a.get(key)
|
||||||
|
if !ok {
|
||||||
|
return lo.Empty[V](), false
|
||||||
|
}
|
||||||
|
return ent.value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
|
||||||
|
ent, ok := a.cache[key]
|
||||||
|
if !ok {
|
||||||
|
return ent, false
|
||||||
|
}
|
||||||
|
a.req(ent)
|
||||||
|
return ent, !ent.ghost
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire returns any representation of a cached response,
|
||||||
|
// a time.Time Give expected expires,
|
||||||
|
// and a bool set to true if the key was found.
|
||||||
|
// This method will NOT update the expires.
|
||||||
|
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
ent, ok := a.get(key)
|
||||||
|
if !ok {
|
||||||
|
return lo.Empty[V](), time.Time{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ent.value, time.Unix(ent.expires, 0), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len determines the number of currently cached entries.
|
||||||
|
// This method is side-effect free in the sense that it does not attempt to optimize random cache access.
|
||||||
|
func (a *ARC[K, V]) Len() int {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
return a.len
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
||||||
|
switch {
|
||||||
|
case ent.ll == a.t1 || ent.ll == a.t2:
|
||||||
|
// Case I
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == a.b1:
|
||||||
|
// Case II
|
||||||
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
|
// Adaptation
|
||||||
|
var d int
|
||||||
|
if a.b1.Len() >= a.b2.Len() {
|
||||||
|
d = 1
|
||||||
|
} else {
|
||||||
|
d = a.b2.Len() / a.b1.Len()
|
||||||
|
}
|
||||||
|
a.p = min(a.p+d, a.c)
|
||||||
|
|
||||||
|
a.replace(ent)
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == a.b2:
|
||||||
|
// Case III
|
||||||
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
|
// Adaptation
|
||||||
|
var d int
|
||||||
|
if a.b2.Len() >= a.b1.Len() {
|
||||||
|
d = 1
|
||||||
|
} else {
|
||||||
|
d = a.b1.Len() / a.b2.Len()
|
||||||
|
}
|
||||||
|
a.p = max(a.p-d, 0)
|
||||||
|
|
||||||
|
a.replace(ent)
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == nil && a.t1.Len()+a.b1.Len() == a.c:
|
||||||
|
// Case IV A
|
||||||
|
if a.t1.Len() < a.c {
|
||||||
|
a.delLRU(a.b1)
|
||||||
|
a.replace(ent)
|
||||||
|
} else {
|
||||||
|
a.delLRU(a.t1)
|
||||||
|
}
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
case ent.ll == nil && a.t1.Len()+a.b1.Len() < a.c:
|
||||||
|
// Case IV B
|
||||||
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() >= a.c {
|
||||||
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() == 2*a.c {
|
||||||
|
a.delLRU(a.b2)
|
||||||
|
}
|
||||||
|
a.replace(ent)
|
||||||
|
}
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
case ent.ll == nil:
|
||||||
|
// Case IV, not A nor B
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) delLRU(list *list.List[*entry[K, V]]) {
|
||||||
|
lru := list.Back()
|
||||||
|
list.Remove(lru)
|
||||||
|
a.len--
|
||||||
|
delete(a.cache, lru.Value.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) replace(ent *entry[K, V]) {
|
||||||
|
if a.t1.Len() > 0 && ((a.t1.Len() > a.p) || (ent.ll == a.b2 && a.t1.Len() == a.p)) {
|
||||||
|
lru := a.t1.Back().Value
|
||||||
|
lru.value = lo.Empty[V]()
|
||||||
|
lru.ghost = true
|
||||||
|
a.len--
|
||||||
|
lru.setMRU(a.b1)
|
||||||
|
} else {
|
||||||
|
lru := a.t2.Back().Value
|
||||||
|
lru.value = lo.Empty[V]()
|
||||||
|
lru.ghost = true
|
||||||
|
a.len--
|
||||||
|
lru.setMRU(a.b2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a int, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
}
|
||||||
105
common/arc/arc_test.go
Normal file
105
common/arc/arc_test.go
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInsertion(t *testing.T) {
|
||||||
|
cache := New[string, string](WithSize[string, string](3))
|
||||||
|
if got, want := cache.Len(), 0; got != want {
|
||||||
|
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
k1 = "Hello"
|
||||||
|
k2 = "Hallo"
|
||||||
|
k3 = "Ciao"
|
||||||
|
k4 = "Salut"
|
||||||
|
|
||||||
|
v1 = "World"
|
||||||
|
v2 = "Worlds"
|
||||||
|
v3 = "Welt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Insert the first value
|
||||||
|
cache.Set(k1, v1)
|
||||||
|
if got, want := cache.Len(), 1; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v1 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace existing value for a given key
|
||||||
|
cache.Set(k1, v2)
|
||||||
|
if got, want := cache.Len(), 1; got != want {
|
||||||
|
t.Errorf("re-insertion: cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v2 {
|
||||||
|
t.Errorf("re-insertion: cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a second different key
|
||||||
|
cache.Set(k2, v3)
|
||||||
|
if got, want := cache.Len(), 2; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v2 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k2); !ok || got != v3 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k2, got, ok, v3)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill cache
|
||||||
|
cache.Set(k3, v1)
|
||||||
|
if got, want := cache.Len(), 3; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exceed size, this should not exceed size:
|
||||||
|
cache.Set(k4, v1)
|
||||||
|
if got, want := cache.Len(), 3; got != want {
|
||||||
|
t.Errorf("insertion of key out of size: cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEviction(t *testing.T) {
|
||||||
|
size := 3
|
||||||
|
cache := New[string, string](WithSize[string, string](size))
|
||||||
|
if got, want := cache.Len(), 0; got != want {
|
||||||
|
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
k, v string
|
||||||
|
}{
|
||||||
|
{"k1", "v1"},
|
||||||
|
{"k2", "v2"},
|
||||||
|
{"k3", "v3"},
|
||||||
|
{"k4", "v4"},
|
||||||
|
}
|
||||||
|
for i, tt := range tests[:size] {
|
||||||
|
cache.Set(tt.k, tt.v)
|
||||||
|
if got, want := cache.Len(), i+1; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exceed size and check we don't outgrow it:
|
||||||
|
cache.Set(tests[size].k, tests[size].v)
|
||||||
|
if got := cache.Len(); got != size {
|
||||||
|
t.Errorf("insertion of overflow key #%d: cache.Len(): got %d want %d", 4, cache.Len(), size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that LRU got evicted:
|
||||||
|
if got, ok := cache.Get(tests[0].k); ok || got != "" {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (<nil>,true)", tests[0].k, got, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests[1:] {
|
||||||
|
if got, ok := cache.Get(tt.k); !ok || got != tt.v {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", tt.k, got, ok, tt.v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
32
common/arc/entry.go
Normal file
32
common/arc/entry.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type entry[K comparable, V any] struct {
|
||||||
|
key K
|
||||||
|
value V
|
||||||
|
ll *list.List[*entry[K, V]]
|
||||||
|
el *list.Element[*entry[K, V]]
|
||||||
|
ghost bool
|
||||||
|
expires int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) setLRU(list *list.List[*entry[K, V]]) {
|
||||||
|
e.detach()
|
||||||
|
e.ll = list
|
||||||
|
e.el = e.ll.PushBack(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) setMRU(list *list.List[*entry[K, V]]) {
|
||||||
|
e.detach()
|
||||||
|
e.ll = list
|
||||||
|
e.el = e.ll.PushFront(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) detach() {
|
||||||
|
if e.ll != nil {
|
||||||
|
e.ll.Remove(e.el)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,8 +11,19 @@ func DefaultValue[T any]() T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TypedValue[T any] struct {
|
type TypedValue[T any] struct {
|
||||||
value atomic.Value
|
|
||||||
_ noCopy
|
_ noCopy
|
||||||
|
value atomic.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
// tValue is a struct with determined type to resolve atomic.Value usages with interface types
|
||||||
|
// https://github.com/golang/go/issues/22550
|
||||||
|
//
|
||||||
|
// The intention to have an atomic value store for errors. However, running this code panics:
|
||||||
|
// panic: sync/atomic: store of inconsistently typed value into Value
|
||||||
|
// This is because atomic.Value requires that the underlying concrete type be the same (which is a reasonable expectation for its implementation).
|
||||||
|
// When going through the atomic.Value.Store method call, the fact that both these are of the error interface is lost.
|
||||||
|
type tValue[T any] struct {
|
||||||
|
value T
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Load() T {
|
func (t *TypedValue[T]) Load() T {
|
||||||
@@ -20,23 +31,23 @@ func (t *TypedValue[T]) Load() T {
|
|||||||
if value == nil {
|
if value == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return value.(T)
|
return value.(tValue[T]).value
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Store(value T) {
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
t.value.Store(value)
|
t.value.Store(tValue[T]{value})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) Swap(new T) T {
|
func (t *TypedValue[T]) Swap(new T) T {
|
||||||
old := t.value.Swap(new)
|
old := t.value.Swap(tValue[T]{new})
|
||||||
if old == nil {
|
if old == nil {
|
||||||
return DefaultValue[T]()
|
return DefaultValue[T]()
|
||||||
}
|
}
|
||||||
return old.(T)
|
return old.(tValue[T]).value
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
return t.value.CompareAndSwap(old, new)
|
return t.value.CompareAndSwap(tValue[T]{old}, tValue[T]{new})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package callback
|
package callback
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type firstWriteCallBackConn struct {
|
type firstWriteCallBackConn struct {
|
||||||
|
|||||||
61
common/callback/close_callback.go
Normal file
61
common/callback/close_callback.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package callback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type closeCallbackConn struct {
|
||||||
|
C.Conn
|
||||||
|
closeFunc func()
|
||||||
|
closeOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) Close() error {
|
||||||
|
w.closeOnce.Do(w.closeFunc)
|
||||||
|
return w.Conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) Upstream() any {
|
||||||
|
return w.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCloseCallbackConn(conn C.Conn, callback func()) C.Conn {
|
||||||
|
return &closeCallbackConn{Conn: conn, closeFunc: callback}
|
||||||
|
}
|
||||||
|
|
||||||
|
type closeCallbackPacketConn struct {
|
||||||
|
C.PacketConn
|
||||||
|
closeFunc func()
|
||||||
|
closeOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) Close() error {
|
||||||
|
w.closeOnce.Do(w.closeFunc)
|
||||||
|
return w.PacketConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) Upstream() any {
|
||||||
|
return w.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCloseCallbackPacketConn(conn C.PacketConn, callback func()) C.PacketConn {
|
||||||
|
return &closeCallbackPacketConn{PacketConn: conn, closeFunc: callback}
|
||||||
|
}
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package collections
|
|
||||||
|
|
||||||
import "sync"
|
|
||||||
|
|
||||||
type (
|
|
||||||
stack struct {
|
|
||||||
top *node
|
|
||||||
length int
|
|
||||||
lock *sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
node struct {
|
|
||||||
value interface{}
|
|
||||||
prev *node
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewStack Create a new stack
|
|
||||||
func NewStack() *stack {
|
|
||||||
return &stack{nil, 0, &sync.RWMutex{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len Return the number of items in the stack
|
|
||||||
func (this *stack) Len() int {
|
|
||||||
return this.length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Peek View the top item on the stack
|
|
||||||
func (this *stack) Peek() interface{} {
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return this.top.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pop the top item of the stack and return it
|
|
||||||
func (this *stack) Pop() interface{} {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
n := this.top
|
|
||||||
this.top = n.prev
|
|
||||||
this.length--
|
|
||||||
return n.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Push a value onto the top of the stack
|
|
||||||
func (this *stack) Push(value interface{}) {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
n := &node{value, this.top}
|
|
||||||
this.top = n
|
|
||||||
this.length++
|
|
||||||
}
|
|
||||||
@@ -9,10 +9,10 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to mihomo proxies config
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
data := DecodeBase64(buf)
|
data := DecodeBase64(buf)
|
||||||
|
|
||||||
@@ -68,7 +68,8 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
proxies = append(proxies, hysteria)
|
||||||
case "hysteria2":
|
|
||||||
|
case "hysteria2", "hy2":
|
||||||
urlHysteria2, err := url.Parse(line)
|
urlHysteria2, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -79,7 +80,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria2 := make(map[string]any, 20)
|
hysteria2 := make(map[string]any, 20)
|
||||||
|
|
||||||
hysteria2["name"] = name
|
hysteria2["name"] = name
|
||||||
hysteria2["type"] = scheme
|
hysteria2["type"] = "hysteria2"
|
||||||
hysteria2["server"] = urlHysteria2.Hostname()
|
hysteria2["server"] = urlHysteria2.Hostname()
|
||||||
if port := urlHysteria2.Port(); port != "" {
|
if port := urlHysteria2.Port(); port != "" {
|
||||||
hysteria2["port"] = port
|
hysteria2["port"] = port
|
||||||
@@ -101,6 +102,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria2["up"] = query.Get("up")
|
hysteria2["up"] = query.Get("up")
|
||||||
|
|
||||||
proxies = append(proxies, hysteria2)
|
proxies = append(proxies, hysteria2)
|
||||||
|
|
||||||
case "tuic":
|
case "tuic":
|
||||||
// A temporary unofficial TUIC share link standard
|
// A temporary unofficial TUIC share link standard
|
||||||
// Modified from https://github.com/daeuniverse/dae/discussions/182
|
// Modified from https://github.com/daeuniverse/dae/discussions/182
|
||||||
@@ -142,6 +144,8 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
tuic["udp-relay-mode"] = udpRelayMode
|
tuic["udp-relay-mode"] = udpRelayMode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, tuic)
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -326,7 +330,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
vmess["h2-opts"] = h2Opts
|
vmess["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws":
|
case "ws", "httpupgrade":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
wsOpts["path"] = []string{"/"}
|
wsOpts["path"] = []string{"/"}
|
||||||
@@ -334,7 +338,30 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
headers["Host"] = host.(string)
|
headers["Host"] = host.(string)
|
||||||
}
|
}
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
wsOpts["path"] = path.(string)
|
path := path.(string)
|
||||||
|
pathURL, err := url.Parse(path)
|
||||||
|
if err == nil {
|
||||||
|
query := pathURL.Query()
|
||||||
|
if earlyData := query.Get("ed"); earlyData != "" {
|
||||||
|
med, err := strconv.Atoi(earlyData)
|
||||||
|
if err == nil {
|
||||||
|
switch network {
|
||||||
|
case "ws":
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
||||||
|
case "httpupgrade":
|
||||||
|
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
||||||
|
}
|
||||||
|
query.Del("ed")
|
||||||
|
pathURL.RawQuery = query.Encode()
|
||||||
|
path = pathURL.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wsOpts["path"] = path
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
vmess["ws-opts"] = wsOpts
|
vmess["ws-opts"] = wsOpts
|
||||||
@@ -403,14 +430,27 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
||||||
ss["udp-over-tcp"] = true
|
ss["udp-over-tcp"] = true
|
||||||
}
|
}
|
||||||
if strings.Contains(query.Get("plugin"), "obfs") {
|
plugin := query.Get("plugin")
|
||||||
obfsParams := strings.Split(query.Get("plugin"), ";")
|
if strings.Contains(plugin, ";") {
|
||||||
ss["plugin"] = "obfs"
|
pluginInfo, _ := url.ParseQuery("pluginName=" + strings.ReplaceAll(plugin, ";", "&"))
|
||||||
ss["plugin-opts"] = map[string]any{
|
pluginName := pluginInfo.Get("pluginName")
|
||||||
"host": obfsParams[2][10:],
|
if strings.Contains(pluginName, "obfs") {
|
||||||
"mode": obfsParams[1][5:],
|
ss["plugin"] = "obfs"
|
||||||
|
ss["plugin-opts"] = map[string]any{
|
||||||
|
"mode": pluginInfo.Get("obfs"),
|
||||||
|
"host": pluginInfo.Get("obfs-host"),
|
||||||
|
}
|
||||||
|
} else if strings.Contains(pluginName, "v2ray-plugin") {
|
||||||
|
ss["plugin"] = "v2ray-plugin"
|
||||||
|
ss["plugin-opts"] = map[string]any{
|
||||||
|
"mode": pluginInfo.Get("mode"),
|
||||||
|
"host": pluginInfo.Get("host"),
|
||||||
|
"path": pluginInfo.Get("path"),
|
||||||
|
"tls": strings.Contains(plugin, "tls"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
|
|
||||||
case "ssr":
|
case "ssr":
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
"github.com/zhangyunhao116/fastrand"
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
h2Opts["headers"] = headers
|
h2Opts["headers"] = headers
|
||||||
proxy["h2-opts"] = h2Opts
|
proxy["h2-opts"] = h2Opts
|
||||||
|
|
||||||
case "ws":
|
case "ws", "httpupgrade":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
@@ -113,7 +113,13 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
||||||
}
|
}
|
||||||
wsOpts["max-early-data"] = med
|
switch network {
|
||||||
|
case "ws":
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
wsOpts["early-data-header-name"] = "Sec-WebSocket-Protocol"
|
||||||
|
case "httpupgrade":
|
||||||
|
wsOpts["v2ray-http-upgrade-fast-open"] = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
|||||||
@@ -1,235 +0,0 @@
|
|||||||
// Copyright 2009 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// Package list implements a doubly linked list.
|
|
||||||
//
|
|
||||||
// To iterate over a list (where l is a *List):
|
|
||||||
//
|
|
||||||
// for e := l.Front(); e != nil; e = e.Next() {
|
|
||||||
// // do something with e.Value
|
|
||||||
// }
|
|
||||||
package list
|
|
||||||
|
|
||||||
// Element is an element of a linked list.
|
|
||||||
type Element[T any] struct {
|
|
||||||
// Next and previous pointers in the doubly-linked list of elements.
|
|
||||||
// To simplify the implementation, internally a list l is implemented
|
|
||||||
// as a ring, such that &l.root is both the next element of the last
|
|
||||||
// list element (l.Back()) and the previous element of the first list
|
|
||||||
// element (l.Front()).
|
|
||||||
next, prev *Element[T]
|
|
||||||
|
|
||||||
// The list to which this element belongs.
|
|
||||||
list *List[T]
|
|
||||||
|
|
||||||
// The value stored with this element.
|
|
||||||
Value T
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next returns the next list element or nil.
|
|
||||||
func (e *Element[T]) Next() *Element[T] {
|
|
||||||
if p := e.next; e.list != nil && p != &e.list.root {
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prev returns the previous list element or nil.
|
|
||||||
func (e *Element[T]) Prev() *Element[T] {
|
|
||||||
if p := e.prev; e.list != nil && p != &e.list.root {
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// List represents a doubly linked list.
|
|
||||||
// The zero value for List is an empty list ready to use.
|
|
||||||
type List[T any] struct {
|
|
||||||
root Element[T] // sentinel list element, only &root, root.prev, and root.next are used
|
|
||||||
len int // current list length excluding (this) sentinel element
|
|
||||||
}
|
|
||||||
|
|
||||||
// Init initializes or clears list l.
|
|
||||||
func (l *List[T]) Init() *List[T] {
|
|
||||||
l.root.next = &l.root
|
|
||||||
l.root.prev = &l.root
|
|
||||||
l.len = 0
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns an initialized list.
|
|
||||||
func New[T any]() *List[T] { return new(List[T]).Init() }
|
|
||||||
|
|
||||||
// Len returns the number of elements of list l.
|
|
||||||
// The complexity is O(1).
|
|
||||||
func (l *List[T]) Len() int { return l.len }
|
|
||||||
|
|
||||||
// Front returns the first element of list l or nil if the list is empty.
|
|
||||||
func (l *List[T]) Front() *Element[T] {
|
|
||||||
if l.len == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return l.root.next
|
|
||||||
}
|
|
||||||
|
|
||||||
// Back returns the last element of list l or nil if the list is empty.
|
|
||||||
func (l *List[T]) Back() *Element[T] {
|
|
||||||
if l.len == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return l.root.prev
|
|
||||||
}
|
|
||||||
|
|
||||||
// lazyInit lazily initializes a zero List value.
|
|
||||||
func (l *List[T]) lazyInit() {
|
|
||||||
if l.root.next == nil {
|
|
||||||
l.Init()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// insert inserts e after at, increments l.len, and returns e.
|
|
||||||
func (l *List[T]) insert(e, at *Element[T]) *Element[T] {
|
|
||||||
e.prev = at
|
|
||||||
e.next = at.next
|
|
||||||
e.prev.next = e
|
|
||||||
e.next.prev = e
|
|
||||||
e.list = l
|
|
||||||
l.len++
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
|
|
||||||
// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
|
|
||||||
func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] {
|
|
||||||
return l.insert(&Element[T]{Value: v}, at)
|
|
||||||
}
|
|
||||||
|
|
||||||
// remove removes e from its list, decrements l.len
|
|
||||||
func (l *List[T]) remove(e *Element[T]) {
|
|
||||||
e.prev.next = e.next
|
|
||||||
e.next.prev = e.prev
|
|
||||||
e.next = nil // avoid memory leaks
|
|
||||||
e.prev = nil // avoid memory leaks
|
|
||||||
e.list = nil
|
|
||||||
l.len--
|
|
||||||
}
|
|
||||||
|
|
||||||
// move moves e to next to at.
|
|
||||||
func (l *List[T]) move(e, at *Element[T]) {
|
|
||||||
if e == at {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
e.prev.next = e.next
|
|
||||||
e.next.prev = e.prev
|
|
||||||
|
|
||||||
e.prev = at
|
|
||||||
e.next = at.next
|
|
||||||
e.prev.next = e
|
|
||||||
e.next.prev = e
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove removes e from l if e is an element of list l.
|
|
||||||
// It returns the element value e.Value.
|
|
||||||
// The element must not be nil.
|
|
||||||
func (l *List[T]) Remove(e *Element[T]) T {
|
|
||||||
if e.list == l {
|
|
||||||
// if e.list == l, l must have been initialized when e was inserted
|
|
||||||
// in l or l == nil (e is a zero Element) and l.remove will crash
|
|
||||||
l.remove(e)
|
|
||||||
}
|
|
||||||
return e.Value
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushFront inserts a new element e with value v at the front of list l and returns e.
|
|
||||||
func (l *List[T]) PushFront(v T) *Element[T] {
|
|
||||||
l.lazyInit()
|
|
||||||
return l.insertValue(v, &l.root)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushBack inserts a new element e with value v at the back of list l and returns e.
|
|
||||||
func (l *List[T]) PushBack(v T) *Element[T] {
|
|
||||||
l.lazyInit()
|
|
||||||
return l.insertValue(v, l.root.prev)
|
|
||||||
}
|
|
||||||
|
|
||||||
// InsertBefore inserts a new element e with value v immediately before mark and returns e.
|
|
||||||
// If mark is not an element of l, the list is not modified.
|
|
||||||
// The mark must not be nil.
|
|
||||||
func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] {
|
|
||||||
if mark.list != l {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// see comment in List.Remove about initialization of l
|
|
||||||
return l.insertValue(v, mark.prev)
|
|
||||||
}
|
|
||||||
|
|
||||||
// InsertAfter inserts a new element e with value v immediately after mark and returns e.
|
|
||||||
// If mark is not an element of l, the list is not modified.
|
|
||||||
// The mark must not be nil.
|
|
||||||
func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] {
|
|
||||||
if mark.list != l {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// see comment in List.Remove about initialization of l
|
|
||||||
return l.insertValue(v, mark)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveToFront moves element e to the front of list l.
|
|
||||||
// If e is not an element of l, the list is not modified.
|
|
||||||
// The element must not be nil.
|
|
||||||
func (l *List[T]) MoveToFront(e *Element[T]) {
|
|
||||||
if e.list != l || l.root.next == e {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// see comment in List.Remove about initialization of l
|
|
||||||
l.move(e, &l.root)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveToBack moves element e to the back of list l.
|
|
||||||
// If e is not an element of l, the list is not modified.
|
|
||||||
// The element must not be nil.
|
|
||||||
func (l *List[T]) MoveToBack(e *Element[T]) {
|
|
||||||
if e.list != l || l.root.prev == e {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// see comment in List.Remove about initialization of l
|
|
||||||
l.move(e, l.root.prev)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveBefore moves element e to its new position before mark.
|
|
||||||
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
|
||||||
// The element and mark must not be nil.
|
|
||||||
func (l *List[T]) MoveBefore(e, mark *Element[T]) {
|
|
||||||
if e.list != l || e == mark || mark.list != l {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.move(e, mark.prev)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveAfter moves element e to its new position after mark.
|
|
||||||
// If e or mark is not an element of l, or e == mark, the list is not modified.
|
|
||||||
// The element and mark must not be nil.
|
|
||||||
func (l *List[T]) MoveAfter(e, mark *Element[T]) {
|
|
||||||
if e.list != l || e == mark || mark.list != l {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.move(e, mark)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushBackList inserts a copy of another list at the back of list l.
|
|
||||||
// The lists l and other may be the same. They must not be nil.
|
|
||||||
func (l *List[T]) PushBackList(other *List[T]) {
|
|
||||||
l.lazyInit()
|
|
||||||
for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
|
|
||||||
l.insertValue(e.Value, l.root.prev)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PushFrontList inserts a copy of another list at the front of list l.
|
|
||||||
// The lists l and other may be the same. They must not be nil.
|
|
||||||
func (l *List[T]) PushFrontList(other *List[T]) {
|
|
||||||
l.lazyInit()
|
|
||||||
for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
|
|
||||||
l.insertValue(e.Value, &l.root)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package cache
|
package lru
|
||||||
|
|
||||||
// Modified by https://github.com/die-net/lrucache
|
// Modified by https://github.com/die-net/lrucache
|
||||||
|
|
||||||
@@ -6,8 +6,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/generics/list"
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
"github.com/samber/lo"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -81,7 +80,7 @@ func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
|||||||
return lc
|
return lc
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the any representation of a cached response and a bool
|
// Get returns any representation of a cached response and a bool
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -111,7 +110,7 @@ func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
|
|||||||
return value, true
|
return value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWithExpire returns the any representation of a cached response,
|
// GetWithExpire returns any representation of a cached response,
|
||||||
// a time.Time Give expected expires,
|
// a time.Time Give expected expires,
|
||||||
// and a bool set to true if the key was found.
|
// and a bool set to true if the key was found.
|
||||||
// This method will NOT check the maxAge of element and will NOT update the expires.
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
@@ -136,7 +135,7 @@ func (c *LruCache[K, V]) Exist(key K) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set stores the any representation of a response for a given key.
|
// Set stores any representation of a response for a given key.
|
||||||
func (c *LruCache[K, V]) Set(key K, value V) {
|
func (c *LruCache[K, V]) Set(key K, value V) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
@@ -152,7 +151,7 @@ func (c *LruCache[K, V]) set(key K, value V) {
|
|||||||
c.setWithExpire(key, value, time.Unix(expires, 0))
|
c.setWithExpire(key, value, time.Unix(expires, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
// SetWithExpire stores any representation of a response for a given key and given expires.
|
||||||
// The expires time will round to second.
|
// The expires time will round to second.
|
||||||
func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package cache
|
package lru
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ ExtendedConn = (*BufferedConn)(nil)
|
var _ ExtendedConn = (*BufferedConn)(nil)
|
||||||
@@ -84,9 +84,9 @@ func (c *BufferedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.C
|
|||||||
length := c.r.Buffered()
|
length := c.r.Buffered()
|
||||||
b, _ := c.r.Peek(length)
|
b, _ := c.r.Peek(length)
|
||||||
_, _ = c.r.Discard(length)
|
_, _ = c.r.Discard(length)
|
||||||
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
|
||||||
return buf.As(b)
|
return buf.As(b)
|
||||||
}
|
}
|
||||||
|
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
34
common/net/bufconn_unsafe.go
Normal file
34
common/net/bufconn_unsafe.go
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bufioReader copy from stdlib bufio/bufio.go
|
||||||
|
// This structure has remained unchanged from go1.5 to go1.21.
|
||||||
|
type bufioReader struct {
|
||||||
|
buf []byte
|
||||||
|
rd io.Reader // reader provided by the client
|
||||||
|
r, w int // buf read and write positions
|
||||||
|
err error
|
||||||
|
lastByte int // last byte read for UnreadByte; -1 means invalid
|
||||||
|
lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) AppendData(buf []byte) (ok bool) {
|
||||||
|
b := (*bufioReader)(unsafe.Pointer(c.r))
|
||||||
|
pos := len(b.buf) - b.w - len(buf)
|
||||||
|
if pos >= -b.r { // len(b.buf)-(b.w - b.r) >= len(buf)
|
||||||
|
if pos < 0 { // len(b.buf)-b.w < len(buf)
|
||||||
|
// Slide existing data to beginning.
|
||||||
|
copy(b.buf, b.buf[b.r:b.w])
|
||||||
|
b.w -= b.r
|
||||||
|
b.r = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
b.w += copy(b.buf[b.w:], buf)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ package net
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ ExtendedConn = (*CachedConn)(nil)
|
var _ ExtendedConn = (*CachedConn)(nil)
|
||||||
|
|||||||
154
common/net/deadline/conn.go
Normal file
154
common/net/deadline/conn.go
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
package deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
"github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type connReadResult struct {
|
||||||
|
buffer []byte
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Conn struct {
|
||||||
|
network.ExtendedConn
|
||||||
|
deadline atomic.TypedValue[time.Time]
|
||||||
|
pipeDeadline pipeDeadline
|
||||||
|
disablePipe atomic.Bool
|
||||||
|
inRead atomic.Bool
|
||||||
|
resultCh chan *connReadResult
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsConn(conn any) bool {
|
||||||
|
_, ok := conn.(*Conn)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConn(conn net.Conn) *Conn {
|
||||||
|
c := &Conn{
|
||||||
|
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||||
|
pipeDeadline: makePipeDeadline(),
|
||||||
|
resultCh: make(chan *connReadResult, 1),
|
||||||
|
}
|
||||||
|
c.resultCh <- nil
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) Read(p []byte) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case result := <-c.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
n = copy(p, result.buffer)
|
||||||
|
err = result.err
|
||||||
|
if n >= len(result.buffer) {
|
||||||
|
c.resultCh <- nil // finish cache read
|
||||||
|
} else {
|
||||||
|
result.buffer = result.buffer[n:]
|
||||||
|
c.resultCh <- result // push back for next call
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
c.resultCh <- nil
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case <-c.pipeDeadline.wait():
|
||||||
|
return 0, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.disablePipe.Load() {
|
||||||
|
return c.ExtendedConn.Read(p)
|
||||||
|
} else if c.deadline.Load().IsZero() {
|
||||||
|
c.inRead.Store(true)
|
||||||
|
defer c.inRead.Store(false)
|
||||||
|
return c.ExtendedConn.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.resultCh
|
||||||
|
go c.pipeRead(len(p))
|
||||||
|
|
||||||
|
return c.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) pipeRead(size int) {
|
||||||
|
buffer := make([]byte, size)
|
||||||
|
n, err := c.ExtendedConn.Read(buffer)
|
||||||
|
buffer = buffer[:n]
|
||||||
|
c.resultCh <- &connReadResult{
|
||||||
|
buffer: buffer,
|
||||||
|
err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||||
|
select {
|
||||||
|
case result := <-c.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
n, _ := buffer.Write(result.buffer)
|
||||||
|
err = result.err
|
||||||
|
|
||||||
|
if n >= len(result.buffer) {
|
||||||
|
c.resultCh <- nil // finish cache read
|
||||||
|
} else {
|
||||||
|
result.buffer = result.buffer[n:]
|
||||||
|
c.resultCh <- result // push back for next call
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
c.resultCh <- nil
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case <-c.pipeDeadline.wait():
|
||||||
|
return os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.disablePipe.Load() {
|
||||||
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
} else if c.deadline.Load().IsZero() {
|
||||||
|
c.inRead.Store(true)
|
||||||
|
defer c.inRead.Store(false)
|
||||||
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.resultCh
|
||||||
|
go c.pipeRead(buffer.FreeLen())
|
||||||
|
|
||||||
|
return c.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) SetReadDeadline(t time.Time) error {
|
||||||
|
if c.disablePipe.Load() {
|
||||||
|
return c.ExtendedConn.SetReadDeadline(t)
|
||||||
|
} else if c.inRead.Load() {
|
||||||
|
c.disablePipe.Store(true)
|
||||||
|
return c.ExtendedConn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
c.deadline.Store(t)
|
||||||
|
c.pipeDeadline.set(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) ReaderReplaceable() bool {
|
||||||
|
select {
|
||||||
|
case result := <-c.resultCh:
|
||||||
|
c.resultCh <- result
|
||||||
|
if result != nil {
|
||||||
|
return false // cache reading
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return false // pipe reading
|
||||||
|
}
|
||||||
|
return c.disablePipe.Load() || c.deadline.Load().IsZero()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) Upstream() any {
|
||||||
|
return c.ExtendedConn
|
||||||
|
}
|
||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
"github.com/metacubex/mihomo/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type readResult struct {
|
type readResult struct {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
"github.com/metacubex/mihomo/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EnhancePacketConn struct {
|
type EnhancePacketConn struct {
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
"github.com/metacubex/mihomo/common/net/packet"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
@@ -121,17 +122,18 @@ type singPacketReadWaiter struct {
|
|||||||
|
|
||||||
type singWaitReadResult singReadResult
|
type singWaitReadResult singReadResult
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) InitializeReadWaiter(newBuffer func() *buf.Buffer) {
|
func (c *singPacketReadWaiter) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
|
||||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
return c.packetReadWaiter.InitializeReadWaiter(options)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) WaitReadPacket() (destination M.Socksaddr, err error) {
|
func (c *singPacketReadWaiter) WaitReadPacket() (buffer *buf.Buffer, destination M.Socksaddr, err error) {
|
||||||
FOR:
|
FOR:
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case result := <-c.netPacketConn.resultCh:
|
case result := <-c.netPacketConn.resultCh:
|
||||||
if result != nil {
|
if result != nil {
|
||||||
if result, ok := result.(*singWaitReadResult); ok {
|
if result, ok := result.(*singWaitReadResult); ok {
|
||||||
|
buffer = result.buffer
|
||||||
destination = result.destination
|
destination = result.destination
|
||||||
err = result.err
|
err = result.err
|
||||||
c.netPacketConn.resultCh <- nil // finish cache read
|
c.netPacketConn.resultCh <- nil // finish cache read
|
||||||
@@ -145,7 +147,7 @@ FOR:
|
|||||||
break FOR
|
break FOR
|
||||||
}
|
}
|
||||||
case <-c.netPacketConn.pipeDeadline.wait():
|
case <-c.netPacketConn.pipeDeadline.wait():
|
||||||
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
return nil, M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,8 +156,7 @@ FOR:
|
|||||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||||
c.netPacketConn.inRead.Store(true)
|
c.netPacketConn.inRead.Store(true)
|
||||||
defer c.netPacketConn.inRead.Store(false)
|
defer c.netPacketConn.inRead.Store(false)
|
||||||
destination, err = c.packetReadWaiter.WaitReadPacket()
|
return c.packetReadWaiter.WaitReadPacket()
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
<-c.netPacketConn.resultCh
|
<-c.netPacketConn.resultCh
|
||||||
@@ -165,8 +166,9 @@ FOR:
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
||||||
destination, err := c.packetReadWaiter.WaitReadPacket()
|
buffer, destination, err := c.packetReadWaiter.WaitReadPacket()
|
||||||
result := &singWaitReadResult{}
|
result := &singWaitReadResult{}
|
||||||
|
result.buffer = buffer
|
||||||
result.destination = destination
|
result.destination = destination
|
||||||
result.err = err
|
result.err = err
|
||||||
c.netPacketConn.resultCh <- result
|
c.netPacketConn.resultCh <- result
|
||||||
|
|||||||
222
common/net/deadline/pipe_sing.go
Normal file
222
common/net/deadline/pipe_sing.go
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
package deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type pipeAddr struct{}
|
||||||
|
|
||||||
|
func (pipeAddr) Network() string { return "pipe" }
|
||||||
|
func (pipeAddr) String() string { return "pipe" }
|
||||||
|
|
||||||
|
type pipe struct {
|
||||||
|
wrMu sync.Mutex // Serialize Write operations
|
||||||
|
|
||||||
|
// Used by local Read to interact with remote Write.
|
||||||
|
// Successful receive on rdRx is always followed by send on rdTx.
|
||||||
|
rdRx <-chan []byte
|
||||||
|
rdTx chan<- int
|
||||||
|
|
||||||
|
// Used by local Write to interact with remote Read.
|
||||||
|
// Successful send on wrTx is always followed by receive on wrRx.
|
||||||
|
wrTx chan<- []byte
|
||||||
|
wrRx <-chan int
|
||||||
|
|
||||||
|
once sync.Once // Protects closing localDone
|
||||||
|
localDone chan struct{}
|
||||||
|
remoteDone <-chan struct{}
|
||||||
|
|
||||||
|
readDeadline pipeDeadline
|
||||||
|
writeDeadline pipeDeadline
|
||||||
|
|
||||||
|
readWaitOptions N.ReadWaitOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pipe creates a synchronous, in-memory, full duplex
|
||||||
|
// network connection; both ends implement the Conn interface.
|
||||||
|
// Reads on one end are matched with writes on the other,
|
||||||
|
// copying data directly between the two; there is no internal
|
||||||
|
// buffering.
|
||||||
|
func Pipe() (net.Conn, net.Conn) {
|
||||||
|
cb1 := make(chan []byte)
|
||||||
|
cb2 := make(chan []byte)
|
||||||
|
cn1 := make(chan int)
|
||||||
|
cn2 := make(chan int)
|
||||||
|
done1 := make(chan struct{})
|
||||||
|
done2 := make(chan struct{})
|
||||||
|
|
||||||
|
p1 := &pipe{
|
||||||
|
rdRx: cb1, rdTx: cn1,
|
||||||
|
wrTx: cb2, wrRx: cn2,
|
||||||
|
localDone: done1, remoteDone: done2,
|
||||||
|
readDeadline: makePipeDeadline(),
|
||||||
|
writeDeadline: makePipeDeadline(),
|
||||||
|
}
|
||||||
|
p2 := &pipe{
|
||||||
|
rdRx: cb2, rdTx: cn2,
|
||||||
|
wrTx: cb1, wrRx: cn1,
|
||||||
|
localDone: done2, remoteDone: done1,
|
||||||
|
readDeadline: makePipeDeadline(),
|
||||||
|
writeDeadline: makePipeDeadline(),
|
||||||
|
}
|
||||||
|
return p1, p2
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*pipe) LocalAddr() net.Addr { return pipeAddr{} }
|
||||||
|
func (*pipe) RemoteAddr() net.Addr { return pipeAddr{} }
|
||||||
|
|
||||||
|
func (p *pipe) Read(b []byte) (int, error) {
|
||||||
|
n, err := p.read(b)
|
||||||
|
if err != nil && err != io.EOF && err != io.ErrClosedPipe {
|
||||||
|
err = &net.OpError{Op: "read", Net: "pipe", Err: err}
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) read(b []byte) (n int, err error) {
|
||||||
|
switch {
|
||||||
|
case isClosedChan(p.localDone):
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
case isClosedChan(p.remoteDone):
|
||||||
|
return 0, io.EOF
|
||||||
|
case isClosedChan(p.readDeadline.wait()):
|
||||||
|
return 0, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case bw := <-p.rdRx:
|
||||||
|
nr := copy(b, bw)
|
||||||
|
p.rdTx <- nr
|
||||||
|
return nr, nil
|
||||||
|
case <-p.localDone:
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
case <-p.remoteDone:
|
||||||
|
return 0, io.EOF
|
||||||
|
case <-p.readDeadline.wait():
|
||||||
|
return 0, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) Write(b []byte) (int, error) {
|
||||||
|
n, err := p.write(b)
|
||||||
|
if err != nil && err != io.ErrClosedPipe {
|
||||||
|
err = &net.OpError{Op: "write", Net: "pipe", Err: err}
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) write(b []byte) (n int, err error) {
|
||||||
|
switch {
|
||||||
|
case isClosedChan(p.localDone):
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
case isClosedChan(p.remoteDone):
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
case isClosedChan(p.writeDeadline.wait()):
|
||||||
|
return 0, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
p.wrMu.Lock() // Ensure entirety of b is written together
|
||||||
|
defer p.wrMu.Unlock()
|
||||||
|
for once := true; once || len(b) > 0; once = false {
|
||||||
|
select {
|
||||||
|
case p.wrTx <- b:
|
||||||
|
nw := <-p.wrRx
|
||||||
|
b = b[nw:]
|
||||||
|
n += nw
|
||||||
|
case <-p.localDone:
|
||||||
|
return n, io.ErrClosedPipe
|
||||||
|
case <-p.remoteDone:
|
||||||
|
return n, io.ErrClosedPipe
|
||||||
|
case <-p.writeDeadline.wait():
|
||||||
|
return n, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) SetDeadline(t time.Time) error {
|
||||||
|
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
p.readDeadline.set(t)
|
||||||
|
p.writeDeadline.set(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) SetReadDeadline(t time.Time) error {
|
||||||
|
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
p.readDeadline.set(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) SetWriteDeadline(t time.Time) error {
|
||||||
|
if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
p.writeDeadline.set(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) Close() error {
|
||||||
|
p.once.Do(func() { close(p.localDone) })
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.ReadWaiter = (*pipe)(nil)
|
||||||
|
|
||||||
|
func (p *pipe) InitializeReadWaiter(options N.ReadWaitOptions) (needCopy bool) {
|
||||||
|
p.readWaitOptions = options
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) WaitReadBuffer() (buffer *buf.Buffer, err error) {
|
||||||
|
buffer, err = p.waitReadBuffer()
|
||||||
|
if err != nil && err != io.EOF && err != io.ErrClosedPipe {
|
||||||
|
err = &net.OpError{Op: "read", Net: "pipe", Err: err}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pipe) waitReadBuffer() (buffer *buf.Buffer, err error) {
|
||||||
|
switch {
|
||||||
|
case isClosedChan(p.localDone):
|
||||||
|
return nil, io.ErrClosedPipe
|
||||||
|
case isClosedChan(p.remoteDone):
|
||||||
|
return nil, io.EOF
|
||||||
|
case isClosedChan(p.readDeadline.wait()):
|
||||||
|
return nil, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case bw := <-p.rdRx:
|
||||||
|
buffer = p.readWaitOptions.NewBuffer()
|
||||||
|
var nr int
|
||||||
|
nr, err = buffer.Write(bw)
|
||||||
|
if err != nil {
|
||||||
|
buffer.Release()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.readWaitOptions.PostReturn(buffer)
|
||||||
|
p.rdTx <- nr
|
||||||
|
return
|
||||||
|
case <-p.localDone:
|
||||||
|
return nil, io.ErrClosedPipe
|
||||||
|
case <-p.remoteDone:
|
||||||
|
return nil, io.EOF
|
||||||
|
case <-p.readDeadline.wait():
|
||||||
|
return nil, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsPipe(conn any) bool {
|
||||||
|
_, ok := conn.(*pipe)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
65
common/net/earlyconn.go
Normal file
65
common/net/earlyconn.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
|
"github.com/metacubex/mihomo/common/once"
|
||||||
|
)
|
||||||
|
|
||||||
|
type earlyConn struct {
|
||||||
|
ExtendedConn // only expose standard N.ExtendedConn function to outside
|
||||||
|
resFunc func() error
|
||||||
|
resOnce sync.Once
|
||||||
|
resErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) Response() error {
|
||||||
|
conn.resOnce.Do(func() {
|
||||||
|
conn.resErr = conn.resFunc()
|
||||||
|
})
|
||||||
|
return conn.resErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) Read(b []byte) (n int, err error) {
|
||||||
|
err = conn.Response()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return conn.ExtendedConn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||||
|
err = conn.Response()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return conn.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) Upstream() any {
|
||||||
|
return conn.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) Success() bool {
|
||||||
|
return once.Done(&conn.resOnce) && conn.resErr == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) ReaderReplaceable() bool {
|
||||||
|
return conn.Success()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) ReaderPossiblyReplaceable() bool {
|
||||||
|
return !conn.Success()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conn *earlyConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ ExtendedConn = (*earlyConn)(nil)
|
||||||
|
|
||||||
|
func NewEarlyConn(c net.Conn, f func() error) net.Conn {
|
||||||
|
return &earlyConn{ExtendedConn: NewExtendedConn(c), resFunc: f}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/net/deadline"
|
"github.com/metacubex/mihomo/common/net/deadline"
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
"github.com/metacubex/mihomo/common/net/packet"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EnhancePacketConn = packet.EnhancePacketConn
|
type EnhancePacketConn = packet.EnhancePacketConn
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package packet
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type WaitReadFrom interface {
|
type WaitReadFrom interface {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
type enhanceUDPConn struct {
|
||||||
|
|||||||
@@ -24,16 +24,16 @@ type enhanceSingPacketConn struct {
|
|||||||
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
var buff *buf.Buffer
|
var buff *buf.Buffer
|
||||||
var dest M.Socksaddr
|
var dest M.Socksaddr
|
||||||
newBuffer := func() *buf.Buffer {
|
rwOptions := N.ReadWaitOptions{}
|
||||||
buff = buf.NewPacket() // do not use stack buffer
|
|
||||||
return buff
|
|
||||||
}
|
|
||||||
if c.packetReadWaiter != nil {
|
if c.packetReadWaiter != nil {
|
||||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
c.packetReadWaiter.InitializeReadWaiter(rwOptions)
|
||||||
defer c.packetReadWaiter.InitializeReadWaiter(nil)
|
buff, dest, err = c.packetReadWaiter.WaitReadPacket()
|
||||||
dest, err = c.packetReadWaiter.WaitReadPacket()
|
|
||||||
} else {
|
} else {
|
||||||
dest, err = c.SingPacketConn.ReadPacket(newBuffer())
|
buff = rwOptions.NewPacketBuffer()
|
||||||
|
dest, err = c.SingPacketConn.ReadPacket(buff)
|
||||||
|
if buff != nil {
|
||||||
|
rwOptions.PostReturn(buff)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if dest.IsFqdn() {
|
if dest.IsFqdn() {
|
||||||
addr = dest
|
addr = dest
|
||||||
@@ -41,9 +41,7 @@ func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr ne
|
|||||||
addr = dest.UDPAddr()
|
addr = dest.UDPAddr()
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if buff != nil {
|
buff.Release()
|
||||||
buff.Release()
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if buff == nil {
|
if buff == nil {
|
||||||
|
|||||||
@@ -4,12 +4,72 @@ package packet
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
type enhanceUDPConn struct {
|
||||||
*net.UDPConn
|
*net.UDPConn
|
||||||
|
rawConn syscall.RawConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
return waitReadFrom(c.UDPConn)
|
if c.rawConn == nil {
|
||||||
|
c.rawConn, _ = c.UDPConn.SyscallConn()
|
||||||
|
}
|
||||||
|
var readErr error
|
||||||
|
hasData := false
|
||||||
|
err = c.rawConn.Read(func(fd uintptr) (done bool) {
|
||||||
|
if !hasData {
|
||||||
|
hasData = true
|
||||||
|
// golang's internal/poll.FD.RawRead will Use a zero-byte read as a way to get notified when this
|
||||||
|
// socket is readable if we return false. So the `recvfrom` syscall will not block the system thread.
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
readBuf := pool.Get(pool.UDPBufferSize)
|
||||||
|
put = func() {
|
||||||
|
_ = pool.Put(readBuf)
|
||||||
|
}
|
||||||
|
var readFrom windows.Sockaddr
|
||||||
|
var readN int
|
||||||
|
readN, readFrom, readErr = windows.Recvfrom(windows.Handle(fd), readBuf, 0)
|
||||||
|
if readN > 0 {
|
||||||
|
data = readBuf[:readN]
|
||||||
|
} else {
|
||||||
|
put()
|
||||||
|
put = nil
|
||||||
|
data = nil
|
||||||
|
}
|
||||||
|
if readErr == windows.WSAEWOULDBLOCK {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if readFrom != nil {
|
||||||
|
switch from := readFrom.(type) {
|
||||||
|
case *windows.SockaddrInet4:
|
||||||
|
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 4 bytes
|
||||||
|
addr = &net.UDPAddr{IP: ip[:], Port: from.Port}
|
||||||
|
case *windows.SockaddrInet6:
|
||||||
|
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 16 bytes
|
||||||
|
addr = &net.UDPAddr{IP: ip[:], Port: from.Port, Zone: strconv.FormatInt(int64(from.ZoneId), 10)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// udp should not convert readN == 0 to io.EOF
|
||||||
|
//if readN == 0 {
|
||||||
|
// readErr = io.EOF
|
||||||
|
//}
|
||||||
|
hasData = false
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if readErr != nil {
|
||||||
|
err = readErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
type refConn struct {
|
type refConn struct {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ package net
|
|||||||
//
|
//
|
||||||
// go func() {
|
// go func() {
|
||||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// // See also https://github.com/Dreamacro/clash/pull/1209
|
// // See also https://github.com/metacubex/mihomo/pull/1209
|
||||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
// leftConn.SetReadDeadline(time.Now())
|
// leftConn.SetReadDeadline(time.Now())
|
||||||
// ch <- err
|
// ch <- err
|
||||||
|
|||||||
@@ -5,9 +5,10 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/net/deadline"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
"github.com/sagernet/sing/common/bufio/deadline"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
"github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,8 +20,16 @@ type ExtendedConn = network.ExtendedConn
|
|||||||
type ExtendedWriter = network.ExtendedWriter
|
type ExtendedWriter = network.ExtendedWriter
|
||||||
type ExtendedReader = network.ExtendedReader
|
type ExtendedReader = network.ExtendedReader
|
||||||
|
|
||||||
|
var WriteBuffer = bufio.WriteBuffer
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||||
return deadline.NewFallbackConn(conn)
|
if deadline.IsPipe(conn) || deadline.IsPipe(network.UnwrapReader(conn)) {
|
||||||
|
return NewExtendedConn(conn) // pipe always have correctly deadline implement
|
||||||
|
}
|
||||||
|
if deadline.IsConn(conn) || deadline.IsConn(network.UnwrapReader(conn)) {
|
||||||
|
return NewExtendedConn(conn) // was a *deadline.Conn
|
||||||
|
}
|
||||||
|
return deadline.NewConn(conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NeedHandshake(conn any) bool {
|
func NeedHandshake(conn any) bool {
|
||||||
@@ -32,6 +41,8 @@ func NeedHandshake(conn any) bool {
|
|||||||
|
|
||||||
type CountFunc = network.CountFunc
|
type CountFunc = network.CountFunc
|
||||||
|
|
||||||
|
var Pipe = deadline.Pipe
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
// Relay copies between left and right bidirectionally.
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
defer runtime.KeepAlive(leftConn)
|
defer runtime.KeepAlive(leftConn)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|||||||
26
common/once/once_go120.go
Normal file
26
common/once/once_go120.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
//go:build !go1.22
|
||||||
|
|
||||||
|
package once
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Once struct {
|
||||||
|
done uint32
|
||||||
|
m sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func Done(once *sync.Once) bool {
|
||||||
|
// atomic visit sync.Once.done
|
||||||
|
return atomic.LoadUint32((*uint32)(unsafe.Pointer(once))) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func Reset(once *sync.Once) {
|
||||||
|
o := (*Once)(unsafe.Pointer(once))
|
||||||
|
o.m.Lock()
|
||||||
|
defer o.m.Unlock()
|
||||||
|
atomic.StoreUint32(&o.done, 0)
|
||||||
|
}
|
||||||
26
common/once/once_go122.go
Normal file
26
common/once/once_go122.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
//go:build go1.22
|
||||||
|
|
||||||
|
package once
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Once struct {
|
||||||
|
done atomic.Uint32
|
||||||
|
m sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func Done(once *sync.Once) bool {
|
||||||
|
// atomic visit sync.Once.done
|
||||||
|
return (*atomic.Uint32)(unsafe.Pointer(once)).Load() == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func Reset(once *sync.Once) {
|
||||||
|
o := (*Once)(unsafe.Pointer(once))
|
||||||
|
o.m.Lock()
|
||||||
|
defer o.m.Unlock()
|
||||||
|
o.done.Store(0)
|
||||||
|
}
|
||||||
@@ -12,22 +12,28 @@ var defaultAllocator = NewAllocator()
|
|||||||
|
|
||||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
type Allocator struct {
|
type Allocator struct {
|
||||||
buffers []sync.Pool
|
buffers [11]sync.Pool
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
|
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
|
||||||
// the waste(memory fragmentation) of space allocation is guaranteed to be
|
// the waste(memory fragmentation) of space allocation is guaranteed to be
|
||||||
// no more than 50%.
|
// no more than 50%.
|
||||||
func NewAllocator() *Allocator {
|
func NewAllocator() *Allocator {
|
||||||
alloc := new(Allocator)
|
return &Allocator{
|
||||||
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
|
buffers: [...]sync.Pool{ // 64B -> 64K
|
||||||
for k := range alloc.buffers {
|
{New: func() any { return new([1 << 6]byte) }},
|
||||||
i := k
|
{New: func() any { return new([1 << 7]byte) }},
|
||||||
alloc.buffers[k].New = func() any {
|
{New: func() any { return new([1 << 8]byte) }},
|
||||||
return make([]byte, 1<<uint32(i))
|
{New: func() any { return new([1 << 9]byte) }},
|
||||||
}
|
{New: func() any { return new([1 << 10]byte) }},
|
||||||
|
{New: func() any { return new([1 << 11]byte) }},
|
||||||
|
{New: func() any { return new([1 << 12]byte) }},
|
||||||
|
{New: func() any { return new([1 << 13]byte) }},
|
||||||
|
{New: func() any { return new([1 << 14]byte) }},
|
||||||
|
{New: func() any { return new([1 << 15]byte) }},
|
||||||
|
{New: func() any { return new([1 << 16]byte) }},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
return alloc
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get a []byte from pool with most appropriate cap
|
// Get a []byte from pool with most appropriate cap
|
||||||
@@ -40,12 +46,42 @@ func (alloc *Allocator) Get(size int) []byte {
|
|||||||
case size > 65536:
|
case size > 65536:
|
||||||
return make([]byte, size)
|
return make([]byte, size)
|
||||||
default:
|
default:
|
||||||
bits := msb(size)
|
var index uint16
|
||||||
if size == 1<<bits {
|
if size > 64 {
|
||||||
return alloc.buffers[bits].Get().([]byte)[:size]
|
index = msb(size)
|
||||||
|
if size != 1<<index {
|
||||||
|
index += 1
|
||||||
|
}
|
||||||
|
index -= 6
|
||||||
}
|
}
|
||||||
|
|
||||||
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
buffer := alloc.buffers[index].Get()
|
||||||
|
switch index {
|
||||||
|
case 0:
|
||||||
|
return buffer.(*[1 << 6]byte)[:size]
|
||||||
|
case 1:
|
||||||
|
return buffer.(*[1 << 7]byte)[:size]
|
||||||
|
case 2:
|
||||||
|
return buffer.(*[1 << 8]byte)[:size]
|
||||||
|
case 3:
|
||||||
|
return buffer.(*[1 << 9]byte)[:size]
|
||||||
|
case 4:
|
||||||
|
return buffer.(*[1 << 10]byte)[:size]
|
||||||
|
case 5:
|
||||||
|
return buffer.(*[1 << 11]byte)[:size]
|
||||||
|
case 6:
|
||||||
|
return buffer.(*[1 << 12]byte)[:size]
|
||||||
|
case 7:
|
||||||
|
return buffer.(*[1 << 13]byte)[:size]
|
||||||
|
case 8:
|
||||||
|
return buffer.(*[1 << 14]byte)[:size]
|
||||||
|
case 9:
|
||||||
|
return buffer.(*[1 << 15]byte)[:size]
|
||||||
|
case 10:
|
||||||
|
return buffer.(*[1 << 16]byte)[:size]
|
||||||
|
default:
|
||||||
|
panic("invalid pool index")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,15 +91,45 @@ func (alloc *Allocator) Put(buf []byte) error {
|
|||||||
if cap(buf) == 0 || cap(buf) > 65536 {
|
if cap(buf) == 0 || cap(buf) > 65536 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
bits := msb(cap(buf))
|
bits := msb(cap(buf))
|
||||||
if cap(buf) != 1<<bits {
|
if cap(buf) != 1<<bits {
|
||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
if cap(buf) < 1<<6 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
bits -= 6
|
||||||
|
buf = buf[:cap(buf)]
|
||||||
|
|
||||||
//nolint
|
//nolint
|
||||||
//lint:ignore SA6002 ignore temporarily
|
//lint:ignore SA6002 ignore temporarily
|
||||||
alloc.buffers[bits].Put(buf)
|
switch bits {
|
||||||
|
case 0:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 6]byte)(buf))
|
||||||
|
case 1:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 7]byte)(buf))
|
||||||
|
case 2:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 8]byte)(buf))
|
||||||
|
case 3:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 9]byte)(buf))
|
||||||
|
case 4:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 10]byte)(buf))
|
||||||
|
case 5:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 11]byte)(buf))
|
||||||
|
case 6:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 12]byte)(buf))
|
||||||
|
case 7:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 13]byte)(buf))
|
||||||
|
case 8:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 14]byte)(buf))
|
||||||
|
case 9:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 15]byte)(buf))
|
||||||
|
case 10:
|
||||||
|
alloc.buffers[bits].Put((*[1 << 16]byte)(buf))
|
||||||
|
default:
|
||||||
|
panic("invalid pool index")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ func TestAllocGet(t *testing.T) {
|
|||||||
assert.Equal(t, 1, len(alloc.Get(1)))
|
assert.Equal(t, 1, len(alloc.Get(1)))
|
||||||
assert.Equal(t, 2, len(alloc.Get(2)))
|
assert.Equal(t, 2, len(alloc.Get(2)))
|
||||||
assert.Equal(t, 3, len(alloc.Get(3)))
|
assert.Equal(t, 3, len(alloc.Get(3)))
|
||||||
assert.Equal(t, 4, cap(alloc.Get(3)))
|
assert.Equal(t, 64, cap(alloc.Get(3)))
|
||||||
assert.Equal(t, 4, cap(alloc.Get(4)))
|
assert.Equal(t, 64, cap(alloc.Get(4)))
|
||||||
assert.Equal(t, 1023, len(alloc.Get(1023)))
|
assert.Equal(t, 1023, len(alloc.Get(1023)))
|
||||||
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||||
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package util
|
package utils
|
||||||
|
|
||||||
import "github.com/samber/lo"
|
import "github.com/samber/lo"
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user