Compare commits
486 Commits
Author | SHA1 | Date | |
---|---|---|---|
47ad8e08be | |||
e1af4ddda3 | |||
58e05c42c9 | |||
880cc90e10 | |||
7fa3d3aa0b | |||
1120c8185d | |||
41af94ea66 | |||
36539bb670 | |||
8e88e0b9f5 | |||
097f3e250c | |||
9c2972afb0 | |||
7aae781569 | |||
92f71fd25f | |||
f44ba26f0c | |||
73140ab826 | |||
4971b9d804 | |||
654e76d91e | |||
984bf27d9b | |||
546b2bc24b | |||
d4e4f6d2d7 | |||
b047ca0294 | |||
2b1e69153b | |||
ae8d42fb82 | |||
89ae640487 | |||
6e0c3a368f | |||
033f902ace | |||
6b1a4385b2 | |||
e552b5475f | |||
8b631f11b8 | |||
1a9104c003 | |||
872a28a5eb | |||
c7557b8e48 | |||
c6fed3e97f | |||
ed17478961 | |||
b674983034 | |||
a22b1cd69e | |||
f1be9b3f4a | |||
534282839c | |||
8dd7632d0a | |||
51e9f3598e | |||
76caab19bf | |||
234f7dbd3b | |||
e404695a0d | |||
75cd72385a | |||
d9fa051dd8 | |||
98394095e4 | |||
c58400572c | |||
3b291d3fbf | |||
15a8d7c473 | |||
67b9314693 | |||
99f7c4f821 | |||
0cb594dd5d | |||
bd431fbf49 | |||
8c0168d3a8 | |||
7ae3e78b15 | |||
d61a5af335 | |||
f90066f286 | |||
463da578dd | |||
1eefa71e1f | |||
969c235490 | |||
f35ff24d0c | |||
94f990da31 | |||
d6931ec491 | |||
19b403da86 | |||
6ecd1c31e5 | |||
a4334e1d52 | |||
a7233f6036 | |||
3ba94842cc | |||
a266589faf | |||
898f10ca96 | |||
d9319ec09a | |||
87d2d08a8f | |||
928dcf9af9 | |||
e4f762822a | |||
573216befb | |||
070f8f8949 | |||
30f93debc4 | |||
a1b6d6050f | |||
eceea72a56 | |||
888c233e9c | |||
8db030d36e | |||
d8db25ee89 | |||
e1af1abcc2 | |||
787e5ea28d | |||
7bb5da3005 | |||
efcb278f61 | |||
72a67ac534 | |||
7f1b7e7521 | |||
0c61057551 | |||
0c146bd04c | |||
7ca4b64a2b | |||
aa6fa7f1e3 | |||
40da1911d9 | |||
c6ecbb25dc | |||
00939da40f | |||
7513761540 | |||
ec234ac0a8 | |||
31095e4a8c | |||
dd60baf9d4 | |||
4ef99294e7 | |||
47df97322d | |||
f100ce6a04 | |||
cae9cf44cf | |||
495033270c | |||
4a0d097fe9 | |||
8e5dbc7382 | |||
c2d1f71305 | |||
81bef30ae0 | |||
e4926c8364 | |||
bf3c6a044c | |||
b3794ffdd8 | |||
394889258c | |||
38a85272c2 | |||
dbffbca6f5 | |||
cd42e9832c | |||
cb0c9e5caf | |||
aaf534427e | |||
5d7fd47cf9 | |||
42721f3b75 | |||
836615aac9 | |||
e745755a46 | |||
20eb168315 | |||
17922dc857 | |||
fda8857ec8 | |||
bad7340a4e | |||
7beb09153e | |||
90f95d7c78 | |||
92cc268209 | |||
ab3fce29ab | |||
ecdde647b1 | |||
304b4d9bcb | |||
4d12ed491c | |||
9afcb7071f | |||
2c48d2da3f | |||
87b9e3d977 | |||
1dbefc40c8 | |||
6c76312e5c | |||
20b0af9a03 | |||
9e6b4dca97 | |||
99dfa4c73a | |||
8e8cddf462 | |||
e9c9d17a9b | |||
2c09ce44f6 | |||
89d5695b7f | |||
8fb2c68722 | |||
c4c7c56684 | |||
76340cc99c | |||
eecd8fff71 | |||
36b3581389 | |||
eb07aafce8 | |||
8ab70d76e7 | |||
f92f34bb20 | |||
ae722bb1a0 | |||
d6d2d90502 | |||
ee5c4cb83b | |||
bf31abee22 | |||
2fc37501f5 | |||
7308c6c2a9 | |||
99f84b8a66 | |||
2ff0f94262 | |||
affc453b6e | |||
526ac3906d | |||
cd95cf4849 | |||
4af4935e7e | |||
9442880a5a | |||
9d7a78e1ef | |||
54c2fa98b4 | |||
54cad53f5f | |||
cfd03a99c2 | |||
a1d0f4c6ee | |||
d569d8186d | |||
9b7aab1fc7 | |||
3c717097cb | |||
991de009be | |||
2fef329319 | |||
db7623968d | |||
7c80c88feb | |||
2c7153cd7a | |||
d730feecb4 | |||
1fdd1f702e | |||
34c91e5fe0 | |||
6d40de2179 | |||
6ca14c814e | |||
545cbeeec0 | |||
431dcfa914 | |||
4d30788738 | |||
e4364cc985 | |||
99ede63a9a | |||
291b5be986 | |||
a7944f1369 | |||
7e10d78d53 | |||
fd0580bfdd | |||
5737fbc23c | |||
e026ac6a2a | |||
e7bb1f42b1 | |||
a22000c41b | |||
0336435ebc | |||
154fbb34ea | |||
3e47bfacf0 | |||
9316c1293e | |||
f6f02bb5eb | |||
84967ace53 | |||
c7362fce9c | |||
8cb67b6480 | |||
3ae4285702 | |||
998d407d44 | |||
520cc807d6 | |||
7404bfdc44 | |||
e8d4f8ae7b | |||
f7610ce2ad | |||
516c219580 | |||
5d0efb5472 | |||
9d9bd245f3 | |||
53928eb895 | |||
8dda9fdb70 | |||
cf7520ec22 | |||
68d7a6da7f | |||
09c53e7cb7 | |||
0f24c2f849 | |||
88116d9032 | |||
6ba82c6d85 | |||
5816dc2955 | |||
f4251e58a5 | |||
2fef00d2a8 | |||
2f992e9863 | |||
13111081be | |||
5de043acc6 | |||
7d230139a0 | |||
0a6c848c9e | |||
074fee2b48 | |||
7f588935ea | |||
4b72ae7aab | |||
09b4a7ff15 | |||
7944522188 | |||
ae4d114802 | |||
07f3cd2ae5 | |||
035d878a9f | |||
913ed62095 | |||
8c135e4a91 | |||
5bcfe1a6c6 | |||
2ccef31f75 | |||
2c4783ff8b | |||
7cc1c1b561 | |||
d309c6311d | |||
e7f9072911 | |||
fe298bd53f | |||
6fe7f4641e | |||
9ae0bd9c2b | |||
dca98b7aa1 | |||
c0fc5d142f | |||
a973a6c7d2 | |||
a454a7f736 | |||
bae61a8152 | |||
0c984644b4 | |||
921b2c3aa4 | |||
8ba7ce73d8 | |||
76a8fe3839 | |||
1e6f0f28f6 | |||
6040803b60 | |||
04ae812a11 | |||
a0ad12c45b | |||
9cc7fdaca9 | |||
545a79d406 | |||
7c34964f87 | |||
6a97ab9ecb | |||
ad6336231c | |||
2f36c9d66d | |||
ae966833a4 | |||
3b037acb01 | |||
8771fa5c17 | |||
bccc6aa8d1 | |||
da27be6de5 | |||
838c5c7770 | |||
02395413ba | |||
4c1682b365 | |||
e7613e4f8b | |||
685fd49dd7 | |||
6061f3d4fa | |||
d55025ecae | |||
e3e0e9796b | |||
ecb2a5f3c6 | |||
76ccebf099 | |||
78100aa963 | |||
0b56fc7598 | |||
c1199f1a8a | |||
c8c078e78a | |||
d36f9c2ac8 | |||
e1dd4ac9e7 | |||
e6a35199e0 | |||
3cd1c92162 | |||
be5ce6249f | |||
0321fe93cf | |||
2cbfac2c89 | |||
0a6705f43e | |||
97e14337e3 | |||
5e7d644efd | |||
40ae019e1d | |||
efbde4a179 | |||
f565edd76d | |||
a3b8c9c233 | |||
de92bc0234 | |||
e6377eac9b | |||
22726c1de8 | |||
bce3aeb218 | |||
81722610d5 | |||
5bfad04b41 | |||
880664c6ab | |||
8f0c61ed14 | |||
7d524668e0 | |||
75680c5866 | |||
a1d008e6f0 | |||
d5d62a4ffd | |||
b72bd5bb37 | |||
7fecd20a1d | |||
f586f22ce3 | |||
21848d6bf1 | |||
28c57c4144 | |||
4a6ebff473 | |||
5c8d955f61 | |||
baaf509637 | |||
db3e1b9ed5 | |||
1a1e3345f4 | |||
8293b7fdae | |||
0ba415866e | |||
527fc2790b | |||
cd7d9fc4f5 | |||
a61685ce01 | |||
b9e63d3f7d | |||
cc3a9dd553 | |||
6a89cc15c3 | |||
fc50392ec7 | |||
59cd89a9c9 | |||
d6ff5f7d96 | |||
8e4dfbd10d | |||
b2d1cea759 | |||
6fe1766c83 | |||
e59c35a308 | |||
b50071ed37 | |||
28c7de6185 | |||
6fb4ebba15 | |||
d00d83abd4 | |||
e6d16e458f | |||
ae42d35184 | |||
ce8929d153 | |||
cc2a775271 | |||
83d719cf79 | |||
4643b5835e | |||
a991bf9045 | |||
3fd3d83029 | |||
24419551a9 | |||
c83eb2e0c9 | |||
929b1675e3 | |||
db54b438e6 | |||
967254d9ca | |||
2d806df9b9 | |||
4fe798ec3b | |||
3555ff5f4e | |||
05ca819823 | |||
c8b8b60b93 | |||
287986d524 | |||
4c25f5e73b | |||
cbc217e80a | |||
fe348e89c5 | |||
e1e1984d3e | |||
99662b616f | |||
857d6e419f | |||
a298b9ea01 | |||
61097d0826 | |||
2ee0f634e6 | |||
61b3b4f775 | |||
dc4b9753d3 | |||
f1ef6c2096 | |||
872c915cf7 | |||
fb9f09c97f | |||
884db8a8b5 | |||
53b41ca166 | |||
ee21b7bc37 | |||
32c53b9584 | |||
4e5f3fbe84 | |||
2ce193877b | |||
e52d599326 | |||
2cf66f41cb | |||
a06b387acc | |||
03520e0d6f | |||
a6a72a5b54 | |||
85db58aeb5 | |||
596bf32caa | |||
2b2644a76f | |||
02684a868f | |||
1924b308fd | |||
0d62e42c50 | |||
d3193cf8b7 | |||
f7538568c0 | |||
4629ecb8ee | |||
5bcea37d59 | |||
6decaef050 | |||
248578086f | |||
87553c6aa0 | |||
a2aa267e43 | |||
a563e9375e | |||
9a4be1fbec | |||
80f48518ca | |||
16c4b55e31 | |||
023a96a6d3 | |||
39394e49ae | |||
b54ddc3aa9 | |||
97537bd185 | |||
1225173a43 | |||
096bb8d439 | |||
df1f6e2b99 | |||
d1f5bef25d | |||
d426db43ec | |||
3bace07948 | |||
24e31d0a40 | |||
fb623c0929 | |||
4f641ce12d | |||
8cd1e40fb3 | |||
8a7027e8d6 | |||
5bbf73e3b5 | |||
106a58779d | |||
fa5b5ca02d | |||
ba6163574e | |||
37eca8af24 | |||
421c91a58c | |||
c90bf1c6e2 | |||
5b1de296af | |||
f4414566d3 | |||
db4f3eda55 | |||
f3b76df13b | |||
bb79272020 | |||
926ef9e33d | |||
ead21f37d7 | |||
49a2602329 | |||
e88bddc24f | |||
a5821e5785 | |||
4e4d741075 | |||
bec66e9e69 | |||
50832aab47 | |||
643fdd0bce | |||
d1565bb46f | |||
8fa66c13a9 | |||
c0ffa06b95 | |||
3b53f5bca3 | |||
2c80155c6f | |||
8a9b3b3d59 | |||
5dd691aa95 | |||
27ceae580a | |||
b6b6413d04 | |||
2095f4f670 | |||
606e8948c0 | |||
3b6fc1c496 | |||
f96bf65557 | |||
804cff8c55 | |||
8a75f78e63 | |||
d9692c6366 | |||
f4b0062dfc | |||
633b9c0426 | |||
b9ffc82e53 | |||
78aaea6a45 | |||
7d6991dd65 | |||
95247154d6 | |||
be6142aa43 | |||
0069513780 | |||
0c9a23a53c | |||
0035fc2313 | |||
6f62d4d5c1 | |||
51f9b34a7c | |||
337be9124f | |||
dd4e4d7559 | |||
0f29c267be | |||
d38ceb78c9 | |||
0c354c748a | |||
3a8e7c8899 | |||
261b8a1d06 | |||
01d8b224db | |||
e9a7e104c0 | |||
b4503908df | |||
3645fbf161 | |||
a1d0f22132 | |||
fd48c6df8a | |||
cd7134e309 | |||
5fa6777239 | |||
908d0b0007 | |||
8e6989758e | |||
29b72df14c | |||
f100a33d98 |
82
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
82
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
name: Bug report
|
||||||
|
description: Create a report to help us improve
|
||||||
|
title: "[Bug] "
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
确保你使用的是**本仓库**最新的的 clash 或 clash Alpha 版本
|
||||||
|
Ensure you are using the latest version of Clash or Clash Premium from **this repository**.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
如果你可以自己 debug 并解决的话,提交 PR 吧
|
||||||
|
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||||
|
"
|
||||||
|
required: false
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||||
|
I have searched on the [issue tracker](……/) for a related issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经使用 Alpha 分支版本测试过,问题依旧存在
|
||||||
|
I have tested using the dev branch, and the issue still exists.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
||||||
|
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: Clash version
|
||||||
|
description: "use `clash -v`"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: What OS are you seeing the problem on?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- macOS
|
||||||
|
- Windows
|
||||||
|
- Linux
|
||||||
|
- OpenBSD/FreeBSD
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: yaml
|
||||||
|
label: "Clash config"
|
||||||
|
description: "
|
||||||
|
在下方附上 Clash 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)
|
||||||
|
"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: shell
|
||||||
|
label: Clash log
|
||||||
|
description: "
|
||||||
|
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
||||||
|
Paste the Clash core log below with the log level set to `DEBUG`.
|
||||||
|
"
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
validations:
|
||||||
|
required: true
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature] "
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
||||||
|
I have searched on the [issue tracker](……/) for a related feature request.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法找到这个功能
|
||||||
|
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Possible Solution
|
||||||
|
description: "
|
||||||
|
此项非必须,但是如果你有想法的话欢迎提出。
|
||||||
|
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
||||||
|
"
|
1
.github/genReleaseNote.sh
vendored
Executable file
1
.github/genReleaseNote.sh
vendored
Executable file
@ -0,0 +1 @@
|
|||||||
|
git log --pretty=format:"* %s by @%an" v1.14.x..v1.14.y | sort -f | uniq > release.md
|
26
.github/release.sh
vendored
Normal file
26
.github/release.sh
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
||||||
|
gzip -S ".gz" $FILENAME
|
||||||
|
elif [[ $FILENAME =~ ".exe" ]];then
|
||||||
|
zip -m ${FILENAME%.*}.zip $FILENAME
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ ".zip" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.zip
|
||||||
|
elif [[ $FILENAME =~ ".gz" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.gz
|
||||||
|
else
|
||||||
|
echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
35
.github/rename-cgo.sh
vendored
Normal file
35
.github/rename-cgo.sh
vendored
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||||
|
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-darwin-arm64-cgo
|
||||||
|
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||||
|
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-darwin-amd64-cgo
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||||
|
echo "rename windows 386 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-windows-386-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
|
echo "rename windows amd64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-5" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv5-cgo
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv6-cgo
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv7-cgo
|
||||||
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
|
echo "rename linux $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
elif [[ $FILENAME =~ "android" ]];then
|
||||||
|
echo "rename android $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
22
.github/workflows/build.yaml
vendored
22
.github/workflows/build.yaml
vendored
@ -1,22 +0,0 @@
|
|||||||
name: Build All
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
- name: Build
|
|
||||||
run: make all
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
349
.github/workflows/build.yml
vendored
Normal file
349
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,349 @@
|
|||||||
|
name: Build
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
- ".github/ISSUE_TEMPLATE/**"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request_target:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.ref }}-${{ github.workflow }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
permissions: write-all
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
job:
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-amd64 linux-amd64-compatible",
|
||||||
|
id: "1",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-armv5 linux-armv6 linux-armv7",
|
||||||
|
id: "2",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-arm64 linux-mips64 linux-mips64le",
|
||||||
|
id: "3",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||||
|
id: "4",
|
||||||
|
}
|
||||||
|
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
|
id: "6",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
|
id: "7",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-arm64 windows-arm32v7",
|
||||||
|
id: "8",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
|
id: "9",
|
||||||
|
}
|
||||||
|
- { type: "WithCGO", target: "windows/*", id: "1" }
|
||||||
|
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||||
|
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
||||||
|
- { 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:
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Alpha'}}
|
||||||
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Beta'}}
|
||||||
|
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Meta'}}
|
||||||
|
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
||||||
|
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set ENV
|
||||||
|
run: |
|
||||||
|
sudo timedatectl set-timezone "Asia/Shanghai"
|
||||||
|
echo "NAME=clash.meta" >> $GITHUB_ENV
|
||||||
|
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||||
|
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
||||||
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
|
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set ENV
|
||||||
|
run: |
|
||||||
|
echo "TAGS=with_gvisor,with_lwip" >> $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
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: "1.20"
|
||||||
|
check-latest: true
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
if: ${{ matrix.job.id=='1' && matrix.job.type=='WithoutCGO' }}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build WithoutCGO
|
||||||
|
if: ${{ matrix.job.type=='WithoutCGO' }}
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
||||||
|
|
||||||
|
- uses: nttld/setup-ndk@v1
|
||||||
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
|
id: setup-ndk
|
||||||
|
with:
|
||||||
|
ndk-version: r25b
|
||||||
|
add-to-path: false
|
||||||
|
local-cache: true
|
||||||
|
|
||||||
|
- name: Build Android
|
||||||
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
|
env:
|
||||||
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
|
run: |
|
||||||
|
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
|
||||||
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
|
run: |
|
||||||
|
docker pull techknowlogick/xgo:latest
|
||||||
|
go install src.techknowlogick.com/xgo@latest
|
||||||
|
|
||||||
|
- name: Build by xgo
|
||||||
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||||
|
env:
|
||||||
|
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||||
|
run: |
|
||||||
|
mkdir bin
|
||||||
|
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
||||||
|
|
||||||
|
- name: Rename
|
||||||
|
if: ${{ matrix.job.type=='WithCGO' }}
|
||||||
|
run: |
|
||||||
|
cd bin
|
||||||
|
ls -la
|
||||||
|
cp ../.github/rename-cgo.sh ./
|
||||||
|
bash ./rename-cgo.sh
|
||||||
|
rm ./rename-cgo.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
- name: Zip
|
||||||
|
if: ${{ success() }}
|
||||||
|
run: |
|
||||||
|
cd bin
|
||||||
|
ls -la
|
||||||
|
chmod +x *
|
||||||
|
cp ../.github/release.sh ./
|
||||||
|
bash ./release.sh
|
||||||
|
rm ./release.sh
|
||||||
|
ls -la
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
- name: Save version
|
||||||
|
run: echo ${VERSION} > bin/version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
Upload-Prerelease:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.ref_type=='branch' }}
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
|
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: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
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:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.ref_type=='tag' }}
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
|
generate_release_notes: true
|
||||||
|
|
||||||
|
Docker:
|
||||||
|
permissions: write-all
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
|
- name: Setup Docker buildx
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v4
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||||
|
- name: Show files
|
||||||
|
run: |
|
||||||
|
ls .
|
||||||
|
ls bin/
|
||||||
|
- name: Log into registry
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
|
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64/v8
|
||||||
|
linux/arm/v7
|
||||||
|
# linux/riscv64
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
15
.github/workflows/delete.yml
vendored
Normal file
15
.github/workflows/delete.yml
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
name: Delete old workflow runs
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * SUN"
|
||||||
|
|
||||||
|
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
|
61
.github/workflows/docker.yaml
vendored
61
.github/workflows/docker.yaml
vendored
@ -1,61 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Beta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
61
.github/workflows/prerelease.yml
vendored
61
.github/workflows/prerelease.yml
vendored
@ -1,61 +0,0 @@
|
|||||||
name: Prerelease
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: mknejp/delete-release-assets@v1
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
assets: |
|
|
||||||
*.zip
|
|
||||||
*.gz
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Alpha
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
36
.github/workflows/release.yaml
vendored
36
.github/workflows/release.yaml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -24,4 +24,5 @@ vendor
|
|||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
/output
|
||||||
/.vscode
|
.vscode/
|
||||||
|
.fleet/
|
21
Dockerfile
21
Dockerfile
@ -1,18 +1,19 @@
|
|||||||
FROM golang:alpine as builder
|
FROM alpine:latest as builder
|
||||||
|
ARG TARGETPLATFORM
|
||||||
|
RUN echo "I'm building for $TARGETPLATFORM"
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /clash-config && \
|
mkdir /clash-config && \
|
||||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
|
|
||||||
|
COPY docker/file-name.sh /clash/file-name.sh
|
||||||
COPY . /clash-src
|
WORKDIR /clash
|
||||||
WORKDIR /clash-src
|
COPY bin/ bin/
|
||||||
RUN go mod download &&\
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
make docker &&\
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
||||||
mv ./bin/Clash.Meta-docker /clash
|
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-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/Clash.Meta"
|
||||||
|
|
||||||
@ -21,6 +22,6 @@ RUN apk add --no-cache ca-certificates tzdata iptables
|
|||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
COPY --from=builder /clash /clash
|
COPY --from=builder /clash/clash /clash
|
||||||
RUN chmod +x /clash
|
RUN chmod +x /clash
|
||||||
ENTRYPOINT [ "/clash" ]
|
ENTRYPOINT [ "/clash" ]
|
||||||
|
18
Makefile
18
Makefile
@ -1,4 +1,4 @@
|
|||||||
NAME=Clash.Meta
|
NAME=clash.meta
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
@ -47,14 +47,17 @@ all:linux-amd64 linux-arm64\
|
|||||||
darwin-amd64 darwin-arm64\
|
darwin-amd64 darwin-arm64\
|
||||||
windows-amd64 windows-arm64\
|
windows-amd64 windows-arm64\
|
||||||
|
|
||||||
|
|
||||||
|
darwin-all: darwin-amd64 darwin-arm64
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64-compatible:
|
darwin-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -66,7 +69,7 @@ linux-amd64:
|
|||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64-compatible:
|
linux-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -98,6 +101,9 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-riscv64:
|
||||||
|
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
android-arm64:
|
android-arm64:
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -117,7 +123,7 @@ windows-amd64:
|
|||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64-compatible:
|
windows-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
@ -154,4 +160,4 @@ CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
|||||||
ebpf: export BPF_CLANG := $(CLANG)
|
ebpf: export BPF_CLANG := $(CLANG)
|
||||||
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||||
ebpf:
|
ebpf:
|
||||||
cd component/ebpf/ && go generate ./...
|
cd component/ebpf/ && go generate ./...
|
||||||
|
105
README.md
105
README.md
@ -29,32 +29,41 @@
|
|||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Getting Started
|
## Wiki
|
||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
Configuration examples can be found at [/docs/config.yaml](https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml), while documentation can be found [Clash.Meta Wiki](https://clash-meta.wiki).
|
||||||
|
|
||||||
## Advanced usage for this branch
|
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
You should install [golang](https://go.dev) first.
|
You should install [golang](https://go.dev) first.
|
||||||
|
|
||||||
Then get the source code of Clash.Meta:
|
Then get the source code of Clash.Meta:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||||
cd Clash.Meta && go mod download
|
cd Clash.Meta && go mod download
|
||||||
```
|
```
|
||||||
|
|
||||||
If you can't visit github,you should set proxy first:
|
If you can't visit github,you should set proxy first:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
```
|
```
|
||||||
|
|
||||||
So now you can build it:
|
Now you can build it:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go build
|
go build
|
||||||
```
|
```
|
||||||
|
|
||||||
### DNS configuration
|
If you need gvisor for tun stack, build with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go build -tags with_gvisor
|
||||||
|
```
|
||||||
|
|
||||||
|
<!-- ## Advanced usage of this fork -->
|
||||||
|
|
||||||
|
<!-- ### DNS configuration
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
@ -64,7 +73,6 @@ Support resolve ip with a `Proxy Tunnel`.
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: DNS
|
- name: DNS
|
||||||
type: url-test
|
type: url-test
|
||||||
use:
|
use:
|
||||||
@ -73,6 +81,7 @@ proxy-groups:
|
|||||||
interval: 180
|
interval: 180
|
||||||
lazy: true
|
lazy: true
|
||||||
```
|
```
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
@ -88,12 +97,12 @@ dns:
|
|||||||
- https://doh.pub/dns-query
|
- https://doh.pub/dns-query
|
||||||
- tls://223.5.5.5:853
|
- tls://223.5.5.5:853
|
||||||
fallback:
|
fallback:
|
||||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
- "https://1.0.0.1/dns-query#DNS" # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||||
- 'tls://8.8.4.4:853#DNS'
|
- "tls://8.8.4.4:853#DNS"
|
||||||
fallback-filter:
|
fallback-filter:
|
||||||
geoip: false
|
geoip: false
|
||||||
geosite:
|
geosite:
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||||
domain:
|
domain:
|
||||||
- +.example.com
|
- +.example.com
|
||||||
ipcidr:
|
ipcidr:
|
||||||
@ -110,28 +119,30 @@ Built-in [Wintun](https://www.wintun.net) driver.
|
|||||||
# Enable the TUN listener
|
# Enable the TUN listener
|
||||||
tun:
|
tun:
|
||||||
enable: true
|
enable: true
|
||||||
stack: gvisor # only gvisor
|
stack: system # system/gvisor
|
||||||
dns-hijack:
|
dns-hijack:
|
||||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||||
auto-route: true # auto set global route
|
auto-route: true # auto set global route
|
||||||
```
|
```
|
||||||
|
|
||||||
### Rules configuration
|
### Rules configuration
|
||||||
|
|
||||||
- Support rule `GEOSITE`.
|
- Support rule `GEOSITE`.
|
||||||
- Support rule-providers `RULE-SET`.
|
- Support rule-providers `RULE-SET`.
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
- Support `network` condition for all rules.
|
- Support `network` condition for all rules.
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
rules:
|
rules:
|
||||||
|
|
||||||
# network(tcp/udp) condition for all rules
|
# network(tcp/udp) condition for all rules
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
# rule GEOSITE
|
# rule GEOSITE
|
||||||
- GEOSITE,category-ads-all,REJECT
|
- GEOSITE,category-ads-all,REJECT
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
@ -142,18 +153,17 @@ rules:
|
|||||||
- GEOSITE,youtube,PROXY
|
- GEOSITE,youtube,PROXY
|
||||||
- GEOSITE,geolocation-cn,DIRECT
|
- GEOSITE,geolocation-cn,DIRECT
|
||||||
- GEOSITE,geolocation-!cn,PROXY
|
- GEOSITE,geolocation-!cn,PROXY
|
||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
- GEOIP,private,DIRECT,no-resolve
|
- GEOIP,private,DIRECT,no-resolve
|
||||||
- GEOIP,cn,DIRECT
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Proxies configuration
|
### Proxies configuration
|
||||||
|
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||||
@ -162,18 +172,17 @@ Support `Policy Group Filter`
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: 🚀 HK Group
|
- name: 🚀 HK Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: 'HK'
|
filter: "HK"
|
||||||
|
|
||||||
- name: 🚀 US Group
|
- name: 🚀 US Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: 'US'
|
filter: "US"
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
ALL:
|
ALL:
|
||||||
@ -185,14 +194,12 @@ proxy-providers:
|
|||||||
enable: true
|
enable: true
|
||||||
interval: 600
|
interval: 600
|
||||||
url: http://www.gstatic.com/generate_204
|
url: http://www.gstatic.com/generate_204
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
Support outbound transport protocol `VLESS`.
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "vless"
|
- name: "vless"
|
||||||
@ -203,7 +210,7 @@ proxies:
|
|||||||
servername: example.com # AKA SNI
|
servername: example.com # AKA SNI
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
|
|
||||||
- name: "vless-ws"
|
- name: "vless-ws"
|
||||||
type: vless
|
type: vless
|
||||||
server: server
|
server: server
|
||||||
@ -228,12 +235,12 @@ proxies:
|
|||||||
network: grpc
|
network: grpc
|
||||||
servername: example.com # priority over wss host
|
servername: example.com # priority over wss host
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
grpc-opts:
|
grpc-opts:
|
||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `Wireguard`
|
Support outbound transport protocol `Wireguard`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "wg"
|
- name: "wg"
|
||||||
@ -248,6 +255,7 @@ proxies:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `Tuic`
|
Support outbound transport protocol `Tuic`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "tuic"
|
- name: "tuic"
|
||||||
@ -266,11 +274,11 @@ proxies:
|
|||||||
# max-udp-relay-packet-size: 1500
|
# max-udp-relay-packet-size: 1500
|
||||||
# fast-open: true
|
# fast-open: true
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
|
``` -->
|
||||||
```
|
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
Work on Linux OS who's supported `iptables`
|
|
||||||
|
Work on Linux OS which supported `iptables`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@ -281,17 +289,15 @@ iptables:
|
|||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### General installation guide for Linux
|
||||||
|
|
||||||
### General installation guide for Linux
|
- Create user given name `clash-meta`
|
||||||
+ Create user given name `clash-meta`
|
|
||||||
|
|
||||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
|
||||||
|
|
||||||
+ Create folder `/etc/Clash-Meta/` as working directory
|
|
||||||
|
|
||||||
|
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||||
|
|
||||||
|
- Create folder `/etc/Clash-Meta/` as working directory
|
||||||
|
|
||||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||||
|
|
||||||
@ -317,10 +323,13 @@ ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ systemctl enable Clash-Meta
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
@ -331,23 +340,29 @@ $ systemctl start Clash-Meta
|
|||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
|
|
||||||
To display process name in GUI please use [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
To display process name in GUI please use [Razord-meta](https://github.com/MetaCubeX/Razord-meta).
|
||||||
|
|
||||||

|
### Dashboard
|
||||||
|
|
||||||
|
We also made a custom fork of yacd provide better support for this project, check it out at [Yacd-meta](https://github.com/MetaCubeX/Yacd-meta)
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
If you want to build an application that uses clash as a library, check out the
|
If you want to build an application that uses clash as a library, check out the
|
||||||
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
||||||
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
* [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -4,16 +4,16 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
@ -92,6 +92,7 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
mapping["tfo"] = p.SupportTFO()
|
mapping["tfo"] = p.SupportTFO()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,12 @@ func WithInName(name string) Addition {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithInUser(user string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.InUser = user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func WithSpecialRules(specialRules string) Addition {
|
func WithSpecialRules(specialRules string) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
metadata.SpecialRules = specialRules
|
metadata.SpecialRules = specialRules
|
||||||
|
@ -16,11 +16,11 @@ func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Ad
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
if ip, port, err := parseAddr(source); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@ func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *cont
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/database64128/tfo-go/v2"
|
"github.com/sagernet/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -24,12 +24,12 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
if ip, port, err := parseAddr(p.InAddr().String()); err == nil {
|
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -18,40 +18,30 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
|||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
remoteAddr := conn.RemoteAddr()
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
// Filter when net.Addr interface is nil
|
metadata.SrcPort = port
|
||||||
if remoteAddr != nil {
|
|
||||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
localAddr := conn.LocalAddr()
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
// Filter when net.Addr interface is nil
|
metadata.InIP = ip
|
||||||
if localAddr != nil {
|
metadata.InPort = port
|
||||||
if ip, port, err := parseAddr(localAddr.String()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
func NewInner(conn net.Conn, address string) *context.ConnContext {
|
||||||
metadata := &C.Metadata{}
|
metadata := &C.Metadata{}
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.INNER
|
metadata.Type = C.INNER
|
||||||
metadata.DNSMode = C.DNSMapping
|
metadata.DNSMode = C.DNSNormal
|
||||||
metadata.Host = host
|
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
if h, port, err := net.SplitHostPort(address); err == nil {
|
||||||
metadata.DstPort = port
|
metadata.DstPort = port
|
||||||
if host == "" {
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
metadata.DstIP = ip
|
||||||
metadata.DstIP = ip
|
} else {
|
||||||
}
|
metadata.Host = h
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -57,8 +58,19 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr string) (netip.Addr, string, error) {
|
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||||
host, port, err := net.SplitHostPort(addr)
|
// Filter when net.Addr interface is nil
|
||||||
|
if addr == nil {
|
||||||
|
return netip.Addr{}, "", errors.New("nil addr")
|
||||||
|
}
|
||||||
|
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
||||||
|
ip, port, err := parseAddr(rawAddr.RawAddr())
|
||||||
|
if err == nil {
|
||||||
|
return ip, port, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addrStr := addr.String()
|
||||||
|
host, port, err := net.SplitHostPort(addrStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return netip.Addr{}, "", err
|
return netip.Addr{}, "", err
|
||||||
}
|
}
|
||||||
|
@ -3,11 +3,12 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -18,6 +19,7 @@ type Base struct {
|
|||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
|
xudp bool
|
||||||
tfo bool
|
tfo bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
@ -32,12 +34,7 @@ func (b *Base) Name() string {
|
|||||||
// Id implements C.ProxyAdapter
|
// Id implements C.ProxyAdapter
|
||||||
func (b *Base) Id() string {
|
func (b *Base) Id() string {
|
||||||
if b.id == "" {
|
if b.id == "" {
|
||||||
id, err := uuid.NewV6()
|
b.id = utils.NewUUIDV6().String()
|
||||||
if err != nil {
|
|
||||||
b.id = b.name
|
|
||||||
} else {
|
|
||||||
b.id = id.String()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return b.id
|
return b.id
|
||||||
@ -48,33 +45,33 @@ func (b *Base) Type() C.AdapterType {
|
|||||||
return b.tp
|
return b.tp
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (b *Base) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return c, errors.New("no support")
|
return c, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) SupportWithDialer() bool {
|
func (b *Base) SupportWithDialer() C.NetWork {
|
||||||
return false
|
return C.InvalidNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -87,11 +84,21 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportXUDP implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportXUDP() bool {
|
||||||
|
return b.xudp
|
||||||
|
}
|
||||||
|
|
||||||
// SupportTFO implements C.ProxyAdapter
|
// SupportTFO implements C.ProxyAdapter
|
||||||
func (b *Base) SupportTFO() bool {
|
func (b *Base) SupportTFO() bool {
|
||||||
return b.tfo
|
return b.tfo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (b *Base) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
@ -132,13 +139,19 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if b.tfo {
|
||||||
|
opts = append(opts, dialer.WithTFO(true))
|
||||||
|
}
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
|
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||||
|
DialerProxy string `proxy:"dialer-proxy,omitempty"` // don't apply this option into groups, but can set a group name in a proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@ -146,6 +159,7 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
|
XUDP bool
|
||||||
TFO bool
|
TFO bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
@ -158,6 +172,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
|
xudp: opt.XUDP,
|
||||||
tfo: opt.TFO,
|
tfo: opt.TFO,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
@ -166,7 +181,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
N.ExtendedConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
@ -185,13 +200,30 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *conn) Upstream() any {
|
||||||
|
return c.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
|
||||||
|
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
||||||
|
}
|
||||||
|
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
N.EnhancePacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
adapterName string
|
||||||
|
connID string
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,8 +241,29 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) LocalAddr() net.Addr {
|
||||||
|
lAddr := c.EnhancePacketConn.LocalAddr()
|
||||||
|
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) Upstream() any {
|
||||||
|
return c.EnhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
epc := N.NewEnhancePacketConn(pc)
|
||||||
|
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
||||||
|
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
||||||
|
}
|
||||||
|
return &packetConn{epc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
|
@ -2,8 +2,7 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -26,16 +25,19 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// 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) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(&directPacketConn{pc}, d), nil
|
return newPacketConn(pc, d), nil
|
||||||
}
|
|
||||||
|
|
||||||
type directPacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
|
@ -7,14 +7,14 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -40,12 +40,10 @@ type HttpOption struct {
|
|||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -66,6 +64,12 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(h.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(h.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
@ -76,7 +80,7 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -85,40 +89,42 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (h *Http) SupportWithDialer() bool {
|
func (h *Http) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.TCP
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
req := &http.Request{
|
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
||||||
Method: http.MethodConnect,
|
tempHeaders := map[string]string{
|
||||||
URL: &url.URL{
|
"Host": addr,
|
||||||
Host: addr,
|
"User-Agent": "Go-http-client/1.1",
|
||||||
},
|
"Proxy-Connection": "Keep-Alive",
|
||||||
Host: addr,
|
|
||||||
Header: http.Header{
|
|
||||||
"Proxy-Connection": []string{"Keep-Alive"},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//增加headers
|
for key, value := range h.option.Headers {
|
||||||
if len(h.option.Headers) != 0 {
|
tempHeaders[key] = value
|
||||||
for key, value := range h.option.Headers {
|
|
||||||
req.Header.Add(key, value)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := req.Write(rw); err != nil {
|
for key, value := range tempHeaders {
|
||||||
|
HeaderString += key + ": " + value + "\r\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
HeaderString += "\r\n"
|
||||||
|
|
||||||
|
_, err := rw.Write([]byte(HeaderString))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
resp, err := http.ReadResponse(bufio.NewReader(rw), nil)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -150,7 +156,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
})
|
})
|
||||||
@ -170,6 +176,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -20,6 +20,7 @@ import (
|
|||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
@ -28,6 +29,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -46,21 +48,12 @@ var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
|||||||
type Hysteria struct {
|
type Hysteria struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
|
option *HysteriaOption
|
||||||
client *core.Client
|
client *core.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
hdc := hyDialerWithContext{
|
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), h.genHdc(ctx, opts...))
|
||||||
ctx: context.Background(),
|
|
||||||
hyDialer: func(network string) (net.PacketConn, error) {
|
|
||||||
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
|
||||||
},
|
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), &hdc)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -69,20 +62,32 @@ func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
hdc := hyDialerWithContext{
|
udpConn, err := h.client.DialUDP(h.genHdc(ctx, opts...))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.PacketDialer {
|
||||||
|
return &hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func(network string) (net.PacketConn, error) {
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
var err error
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(h.Base.DialOptions(opts...)...)
|
||||||
|
if len(h.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(h.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rAddrPort, _ := netip.ParseAddrPort(h.Addr())
|
||||||
|
return cDialer.ListenPacket(ctx, network, "", rAddrPort)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
udpConn, err := h.client.DialUDP(&hdc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HysteriaOption struct {
|
type HysteriaOption struct {
|
||||||
@ -178,7 +183,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
@ -258,6 +263,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
client: client,
|
client: client,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@ -312,6 +318,16 @@ func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data = b
|
||||||
|
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
35
adapter/outbound/reality.go
Normal file
35
adapter/outbound/reality.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/curve25519"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RealityOptions struct {
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
ShortID string `proxy:"short-id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
||||||
|
if o.PublicKey != "" {
|
||||||
|
config := new(tlsC.RealityConfig)
|
||||||
|
|
||||||
|
n, err := base64.RawURLEncoding.Decode(config.PublicKey[:], []byte(o.PublicKey))
|
||||||
|
if err != nil || n != curve25519.ScalarSize {
|
||||||
|
return nil, errors.New("invalid REALITY public key")
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
||||||
|
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
||||||
|
return nil, errors.New("invalid REALITY short ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
@ -6,6 +6,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -16,12 +17,12 @@ type Reject 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) {
|
||||||
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 NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
@ -48,27 +49,40 @@ 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) Write(b []byte) (int, error) {
|
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw nopConn) Write(b []byte) (int, error) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw *nopConn) Close() error { return nil }
|
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
return io.EOF
|
||||||
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) Close() error { return nil }
|
||||||
func (rw *nopConn) SetWriteDeadline(time.Time) 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}
|
||||||
|
|
||||||
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) { return len(b), nil }
|
||||||
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
func (npc *nopPacketConn) Close() error { return nil }
|
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||||
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
return nil, nil, nil, io.EOF
|
||||||
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
}
|
||||||
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) Close() error { return nil }
|
||||||
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||||
|
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
@ -7,16 +7,19 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/restls"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
"github.com/metacubex/sing-shadowsocks"
|
restlsC "github.com/3andne/restls-client-go"
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"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"
|
||||||
)
|
)
|
||||||
@ -27,22 +30,26 @@ type ShadowSocks struct {
|
|||||||
|
|
||||||
option *ShadowSocksOption
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
|
restlsConfig *restlsC.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption 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"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
||||||
|
UDPOverTCPVersion int `proxy:"udp-over-tcp-version,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -61,8 +68,24 @@ type v2rayObfsOption struct {
|
|||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
type shadowTLSOption struct {
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
Password string `obfs:"password"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Version int `obfs:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type restlsOption struct {
|
||||||
|
Password string `obfs:"password"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
VersionHint string `obfs:"version-hint"`
|
||||||
|
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
useEarly := false
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -71,15 +94,39 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
case "websocket":
|
case "websocket":
|
||||||
var err error
|
var err error
|
||||||
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
c, err = v2rayObfs.NewV2rayObfs(ctx, c, ss.v2rayOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
|
case shadowtls.Mode:
|
||||||
|
var err error
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
|
case restls.Mode:
|
||||||
|
var err error
|
||||||
|
c, err = restls.NewRestls(ctx, c, ss.restlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
}
|
}
|
||||||
|
useEarly = useEarly || N.NeedHandshake(c)
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
uotDestination := uot.RequestDestination(uint8(ss.option.UDPOverTCPVersion))
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, uotDestination), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, uotDestination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -89,6 +136,12 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -99,7 +152,7 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -110,12 +163,18 @@ 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 {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
||||||
}
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -126,21 +185,35 @@ 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(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
pc = ss.method.DialPacketConn(N.NewBindPacketConn(pc, addr))
|
||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) SupportWithDialer() bool {
|
func (ss *ShadowSocks) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
return newPacketConn(uot.NewClientConn(c), ss), nil
|
// ss uot use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
|
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||||
|
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
|
} else {
|
||||||
|
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -150,13 +223,17 @@ func (ss *ShadowSocks) SupportUOT() bool {
|
|||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
method, err := shadowsocks.CreateMethod(context.Background(), option.Cipher, shadowsocks.MethodOptions{
|
||||||
|
Password: option.Password,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
|
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||||
|
var restlsConfig *restlsC.Config
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -192,6 +269,43 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
}
|
}
|
||||||
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
|
obfsMode = shadowtls.Mode
|
||||||
|
opt := &shadowTLSOption{
|
||||||
|
Version: 2,
|
||||||
|
}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, opt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
||||||
|
Password: opt.Password,
|
||||||
|
Host: opt.Host,
|
||||||
|
Fingerprint: opt.Fingerprint,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
|
Version: opt.Version,
|
||||||
|
}
|
||||||
|
} else if option.Plugin == restls.Mode {
|
||||||
|
obfsMode = restls.Mode
|
||||||
|
restlsOpt := &restlsOption{}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, restlsOpt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
restlsConfig, err = restlsC.NewRestlsConfig(restlsOpt.Host, restlsOpt.Password, restlsOpt.VersionHint, restlsOpt.RestlsScript, option.ClientFingerprint)
|
||||||
|
restlsConfig.SessionTicketsDisabled = true
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
switch option.UDPOverTCPVersion {
|
||||||
|
case uot.Version, uot.LegacyVersion:
|
||||||
|
case 0:
|
||||||
|
option.UDPOverTCPVersion = uot.LegacyVersion
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -200,48 +314,18 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
method: method,
|
method: method,
|
||||||
|
|
||||||
option: &option,
|
option: &option,
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
shadowTLSOption: shadowTLSOpt,
|
||||||
|
restlsConfig: restlsConfig,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type ssPacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|
||||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, _, e := spc.PacketConn.ReadFrom(b)
|
|
||||||
if e != nil {
|
|
||||||
return 0, nil, e
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := socks5.SplitAddr(b[:n])
|
|
||||||
if addr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
udpAddr := addr.UDPAddr()
|
|
||||||
if udpAddr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
copy(b, b[len(addr):])
|
|
||||||
return n - len(addr), udpAddr, e
|
|
||||||
}
|
|
||||||
|
@ -2,21 +2,26 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *ShadowSocksROption
|
||||||
cipher core.Cipher
|
cipher core.Cipher
|
||||||
obfs obfs.Obfs
|
obfs obfs.Obfs
|
||||||
protocol protocol.Protocol
|
protocol protocol.Protocol
|
||||||
@ -36,8 +41,8 @@ type ShadowSocksROption struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ssr *ShadowSocksR) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = ssr.obfs.StreamConn(c)
|
c = ssr.obfs.StreamConn(c)
|
||||||
c = ssr.cipher.StreamConn(c)
|
c = ssr.cipher.StreamConn(c)
|
||||||
var (
|
var (
|
||||||
@ -65,6 +70,12 @@ func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(ssr.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ssr.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
@ -75,7 +86,7 @@ func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dia
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,6 +97,12 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if len(ssr.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ssr.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -96,14 +113,14 @@ func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Di
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc = ssr.cipher.PacketConn(pc)
|
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
|
||||||
pc = ssr.protocol.PacketConn(pc)
|
epc = ssr.protocol.PacketConn(epc)
|
||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) SupportWithDialer() bool {
|
func (ssr *ShadowSocksR) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
@ -163,12 +180,73 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
protocol: protocol,
|
protocol: protocol,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ssrPacketConn struct {
|
||||||
|
N.EnhancePacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := spc.EnhancePacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), udpAddr, e
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
data, put, _, err = spc.EnhancePacketConn.WaitReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_addr := socks5.SplitAddr(data)
|
||||||
|
if _addr == nil {
|
||||||
|
if put != nil {
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
addr = _addr.UDPAddr()
|
||||||
|
if addr == nil {
|
||||||
|
if put != nil {
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
data = data[len(_addr):]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
138
adapter/outbound/singmux.go
Normal file
138
adapter/outbound/singmux.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
mux "github.com/sagernet/sing-mux"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SingMux struct {
|
||||||
|
C.ProxyAdapter
|
||||||
|
base ProxyBase
|
||||||
|
client *mux.Client
|
||||||
|
dialer *muxSingDialer
|
||||||
|
onlyTcp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type SingMuxOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||||
|
MinStreams int `proxy:"min-streams,omitempty"`
|
||||||
|
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||||
|
Padding bool `proxy:"padding,omitempty"`
|
||||||
|
Statistic bool `proxy:"statistic,omitempty"`
|
||||||
|
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyBase interface {
|
||||||
|
DialOptions(opts ...dialer.Option) []dialer.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
type muxSingDialer struct {
|
||||||
|
dialer dialer.Dialer
|
||||||
|
proxy C.ProxyAdapter
|
||||||
|
statistic bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.Dialer = (*muxSingDialer)(nil)
|
||||||
|
|
||||||
|
func (d *muxSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
||||||
|
return cDialer.DialContext(ctx, network, destination.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *muxSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
||||||
|
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
options := s.base.DialOptions(opts...)
|
||||||
|
s.dialer.dialer = dialer.NewDialer(options...)
|
||||||
|
c, err := s.client.DialContext(ctx, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(CN.NewRefConn(c, s), s.ProxyAdapter), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
|
}
|
||||||
|
options := s.base.DialOptions(opts...)
|
||||||
|
s.dialer.dialer = dialer.NewDialer(options...)
|
||||||
|
|
||||||
|
// sing-mux use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := s.client.ListenPacket(ctx, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, E.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(CN.NewRefPacketConn(CN.NewThreadSafePacketConn(pc), s), s.ProxyAdapter), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) SupportUDP() bool {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.SupportUOT()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) SupportUOT() bool {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.SupportUOT()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeSingMux(s *SingMux) {
|
||||||
|
_ = s.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
||||||
|
singDialer := &muxSingDialer{dialer: dialer.NewDialer(), proxy: proxy, statistic: option.Statistic}
|
||||||
|
client, err := mux.NewClient(mux.Options{
|
||||||
|
Dialer: singDialer,
|
||||||
|
Protocol: option.Protocol,
|
||||||
|
MaxConnections: option.MaxConnections,
|
||||||
|
MinStreams: option.MinStreams,
|
||||||
|
MaxStreams: option.MaxStreams,
|
||||||
|
Padding: option.Padding,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
outbound := &SingMux{
|
||||||
|
ProxyAdapter: proxy,
|
||||||
|
base: base,
|
||||||
|
client: client,
|
||||||
|
dialer: singDialer,
|
||||||
|
onlyTcp: option.OnlyTcp,
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeSingMux)
|
||||||
|
return outbound, nil
|
||||||
|
}
|
@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/snell"
|
"github.com/Dreamacro/clash/transport/snell"
|
||||||
@ -15,6 +16,7 @@ import (
|
|||||||
|
|
||||||
type Snell struct {
|
type Snell struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *SnellOption
|
||||||
psk []byte
|
psk []byte
|
||||||
pool *snell.Pool
|
pool *snell.Pool
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
@ -50,8 +52,8 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
return snell.StreamConn(c, option.psk, option.version)
|
return snell.StreamConn(c, option.psk, option.version)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
err := snell.WriteUDPHeader(c, s.version)
|
||||||
@ -83,6 +85,12 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(s.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(s.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
@ -93,7 +101,7 @@ func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -104,6 +112,13 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
var err error
|
||||||
|
if len(s.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(s.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -121,8 +136,8 @@ func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) SupportWithDialer() bool {
|
func (s *Snell) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -167,10 +182,12 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
version: option.Version,
|
version: option.Version,
|
||||||
@ -178,7 +195,15 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
|
|
||||||
if option.Version == snell.Version2 {
|
if option.Version == snell.Version2 {
|
||||||
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", addr, s.Base.DialOptions()...)
|
var err error
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions()...)
|
||||||
|
if len(s.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(ctx, "tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -5,18 +5,20 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *Socks5Option
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@ -37,12 +39,10 @@ type Socks5Option struct {
|
|||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -70,6 +70,12 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -80,7 +86,7 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -89,13 +95,20 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ss *Socks5) SupportWithDialer() bool {
|
func (ss *Socks5) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.TCP
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
var cDialer C.Dialer = dialer.NewDialer(ss.Base.DialOptions(opts...)...)
|
||||||
|
if len(ss.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(ss.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
return
|
return
|
||||||
@ -167,7 +180,7 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
var err error
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
@ -182,10 +195,12 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
|
@ -4,12 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
@ -25,27 +26,31 @@ type Trojan struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption 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"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
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{
|
||||||
@ -66,19 +71,24 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
wsOpts.Headers = header
|
wsOpts.Headers = header
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamWebsocketConn(c, wsOpts)
|
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamConn(c)
|
return t.instance.StreamConn(ctx, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
||||||
|
t.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||||
|
}
|
||||||
|
|
||||||
if t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig, t.realityConfig)
|
||||||
} else {
|
} else {
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(ctx, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -125,6 +135,12 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(t.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
@ -135,7 +151,7 @@ func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
c, err = t.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -169,6 +185,12 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if len(t.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
@ -177,7 +199,7 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(ctx, c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
@ -192,8 +214,8 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) SupportWithDialer() bool {
|
func (t *Trojan) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
@ -211,21 +233,25 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
tOption := &trojan.Option{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
Fingerprint: option.Fingerprint,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
switch option.Network {
|
||||||
option.Flow = option.Flow[:16]
|
case "", "tcp":
|
||||||
switch option.Flow {
|
if len(option.Flow) >= 16 {
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
option.Flow = option.Flow[:16]
|
||||||
tOption.Flow = option.Flow
|
switch option.Flow {
|
||||||
default:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
tOption.Flow = option.Flow
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -239,6 +265,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -247,9 +274,24 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
t.realityConfig, err = option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tOption.Reality = t.realityConfig
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
var err error
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(t.Base.DialOptions()...)
|
||||||
|
if len(t.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(t.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(context.Background(), "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -265,7 +307,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
var err error
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
@ -273,11 +315,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
|
||||||
} else {
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
|
@ -16,6 +16,7 @@ import (
|
|||||||
"github.com/metacubex/quic-go"
|
"github.com/metacubex/quic-go"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
"github.com/Dreamacro/clash/transport/tuic"
|
||||||
@ -23,6 +24,7 @@ import (
|
|||||||
|
|
||||||
type Tuic struct {
|
type Tuic struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *TuicOption
|
||||||
client *tuic.PoolClient
|
client *tuic.PoolClient
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,15 +44,17 @@ type TuicOption struct {
|
|||||||
DisableSni bool `proxy:"disable-sni,omitempty"`
|
DisableSni bool `proxy:"disable-sni,omitempty"`
|
||||||
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
||||||
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
|
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -82,8 +86,8 @@ func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (t *Tuic) SupportWithDialer() bool {
|
func (t *Tuic) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
@ -91,6 +95,12 @@ func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
|
if len(t.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
@ -106,12 +116,14 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.Pack
|
|||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: serverName,
|
ServerName: serverName,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
|
if option.SNI != "" {
|
||||||
|
tlsConfig.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
var bs []byte
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
@ -143,7 +155,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
@ -165,13 +177,22 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
option.MaxUdpRelayPacketSize = 1500
|
option.MaxUdpRelayPacketSize = 1252
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxOpenStreams == 0 {
|
if option.MaxOpenStreams == 0 {
|
||||||
option.MaxOpenStreams = 100
|
option.MaxOpenStreams = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize == 0 {
|
||||||
|
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + tuic.PacketOverHead
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize > 1400 {
|
||||||
|
option.MaxDatagramFrameSize = 1400
|
||||||
|
}
|
||||||
|
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - tuic.PacketOverHead
|
||||||
|
|
||||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
||||||
@ -184,6 +205,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
MaxIncomingUniStreams: quicMaxOpenStreams,
|
MaxIncomingUniStreams: quicMaxOpenStreams,
|
||||||
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
if option.ReceiveWindowConn == 0 {
|
if option.ReceiveWindowConn == 0 {
|
||||||
@ -213,12 +235,19 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
udp: true,
|
udp: true,
|
||||||
tfo: option.FastOpen,
|
tfo: option.FastOpen,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
}
|
}
|
||||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
|
||||||
|
// to avoid tuic's "too many open streams", decrease to 0.9x
|
||||||
|
if clientMaxOpenStreams == 100 {
|
||||||
|
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
||||||
|
}
|
||||||
|
|
||||||
if clientMaxOpenStreams < 1 {
|
if clientMaxOpenStreams < 1 {
|
||||||
clientMaxOpenStreams = 1
|
clientMaxOpenStreams = 1
|
||||||
}
|
}
|
||||||
|
@ -13,14 +13,21 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
vmessSing "github.com/sagernet/sing-vmess"
|
||||||
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -37,35 +44,46 @@ type Vless struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption 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"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
||||||
|
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||||
|
}
|
||||||
|
|
||||||
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 := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -73,6 +91,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Headers: http.Header{},
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,9 +110,12 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -107,10 +129,10 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
convert.SetUserAgent(wsOpts.Headers)
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
c, err = v.streamTLSOrXTLSConn(ctx, c, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -125,7 +147,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
c, err = v.streamTLSOrXTLSConn(c, true)
|
c, err = v.streamTLSOrXTLSConn(ctx, c, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -137,49 +159,71 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
if v.isXTLSEnabled() {
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||||
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
} else {
|
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS And XTLS
|
// handle TLS And XTLS
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
c, err = v.streamTLSOrXTLSConn(ctx, c, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
return v.streamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
metadata = &C.Metadata{
|
||||||
|
NetWork: C.UDP,
|
||||||
|
Host: packetaddr.SeqPacketMagicAddress,
|
||||||
|
DstPort: "443",
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
metadata = &C.Metadata{ // a clear metadata only contains ip
|
||||||
|
NetWork: C.UDP,
|
||||||
|
DstIP: metadata.DstIP,
|
||||||
|
DstPort: metadata.DstPort,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
conn = packetaddr.NewBindConn(conn)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, false))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
conn = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vless) streamTLSOrXTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
if v.isXTLSEnabled() {
|
if v.isLegacyXTLSEnabled() && !isH2 {
|
||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
Fingerprint: v.option.Fingerprint,
|
||||||
}
|
|
||||||
|
|
||||||
if isH2 {
|
|
||||||
xtlsOpts.NextProtos = []string{"h2"}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
xtlsOpts.Host = v.option.ServerName
|
xtlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
return vless.StreamXTLSConn(ctx, conn, &xtlsOpts)
|
||||||
|
|
||||||
} else if v.option.TLS {
|
} else if v.option.TLS {
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -190,14 +234,14 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
return vmess.StreamTLSConn(ctx, conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return conn, nil
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isXTLSEnabled() bool {
|
func (v *Vless) isLegacyXTLSEnabled() bool {
|
||||||
return v.client.Addons != nil
|
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -212,7 +256,7 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -224,6 +268,12 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -233,13 +283,16 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -247,7 +300,6 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
@ -259,20 +311,26 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
c, err = v.streamConn(c, metadata)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
}
|
}
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -280,6 +338,7 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -289,22 +348,41 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) SupportWithDialer() bool {
|
func (v *Vless) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.XUDP {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(
|
||||||
|
vmessSing.NewXUDPConn(c, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
|
), v), nil
|
||||||
|
} else if v.option.PacketAddr {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(
|
||||||
|
packetaddr.NewConn(&vlessPacketConn{
|
||||||
|
Conn: c, rAddr: metadata.UDPAddr(),
|
||||||
|
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
|
), v), nil
|
||||||
|
}
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -313,7 +391,7 @@ func (v *Vless) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType() {
|
switch metadata.AddrType() {
|
||||||
@ -337,7 +415,8 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
UDP: metadata.NetWork == C.UDP,
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: uint(port),
|
Port: uint16(port),
|
||||||
|
Mux: metadata.NetWork == C.UDP && xudp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -438,6 +517,9 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
switch option.Flow {
|
||||||
|
case vless.XRV:
|
||||||
|
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
||||||
|
fallthrough
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
@ -447,6 +529,19 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch option.PacketEncoding {
|
||||||
|
case "packetaddr", "packet":
|
||||||
|
option.PacketAddr = true
|
||||||
|
option.XUDP = false
|
||||||
|
default: // https://github.com/XTLS/Xray-core/pull/1567#issuecomment-1407305458
|
||||||
|
if !option.PacketAddr {
|
||||||
|
option.XUDP = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.XUDP {
|
||||||
|
option.PacketAddr = false
|
||||||
|
}
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -458,13 +553,21 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
xudp: option.XUDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2":
|
case "h2":
|
||||||
if len(option.HTTP2Opts.Host) == 0 {
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
@ -472,7 +575,15 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
var err error
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(v.Base.DialOptions()...)
|
||||||
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(v.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(context.Background(), "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -481,27 +592,29 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
if option.ServerName == "" {
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
gunConfig.Host = v.addr
|
||||||
ServerName: v.option.ServerName,
|
}
|
||||||
})
|
var tlsConfig *tls.Config
|
||||||
|
if option.TLS {
|
||||||
if v.option.ServerName == "" {
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
tlsConfig.ServerName = host
|
ServerName: v.option.ServerName,
|
||||||
gunConfig.Host = host
|
})
|
||||||
|
if option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
if v.isXTLSEnabled() {
|
|
||||||
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
||||||
} else {
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -5,20 +5,22 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
@ -34,31 +36,35 @@ type Vmess struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption 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"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -83,12 +89,16 @@ type WSOptions struct {
|
|||||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
||||||
|
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||||
|
}
|
||||||
|
|
||||||
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 := &clashVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -96,6 +106,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Headers: http.Header{},
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,9 +125,8 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
|
||||||
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -128,21 +138,22 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamWebsocketConn(c, wsOpts)
|
c, err = clashVMess.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 := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
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 = clashVMess.StreamTLSConn(c, tlsOpts)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -160,16 +171,18 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := clashVMess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
c, err = clashVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -181,36 +194,65 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
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 := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
return v.streamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Vmess) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
if v.option.XUDP {
|
if v.option.XUDP {
|
||||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
conn = v.client.DialEarlyXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
}
|
||||||
|
} else if v.option.PacketAddr {
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
conn = v.client.DialEarlyPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||||
|
}
|
||||||
|
conn = packetaddr.NewBindConn(conn)
|
||||||
} else {
|
} else {
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
conn = v.client.DialEarlyPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
conn = v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
conn = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -237,6 +279,12 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -246,13 +294,13 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -260,14 +308,6 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
_metadata := *metadata // make a copy
|
|
||||||
metadata = &_metadata
|
|
||||||
metadata.Host = packetaddr.SeqPacketMagicAddress
|
|
||||||
metadata.DstPort = "443"
|
|
||||||
}
|
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
@ -279,33 +319,25 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
if v.option.XUDP {
|
c, err = v.streamConn(c, metadata)
|
||||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
}
|
}
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -315,24 +347,39 @@ func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) SupportWithDialer() bool {
|
func (v *Vmess) SupportWithDialer() C.NetWork {
|
||||||
return true
|
return C.ALLNet
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if v.option.PacketAddr {
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
if !metadata.Resolved() {
|
||||||
} else if pc, ok := c.(net.PacketConn); ok {
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
@ -366,19 +413,14 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
option.PacketAddr = false
|
option.PacketAddr = false
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
|
||||||
case "h2", "grpc":
|
|
||||||
if !option.TLS {
|
|
||||||
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
v := &Vmess{
|
v := &Vmess{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
|
xudp: option.XUDP,
|
||||||
|
tfo: option.TFO,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -394,7 +436,15 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
var err error
|
||||||
|
var cDialer C.Dialer = dialer.NewDialer(v.Base.DialOptions()...)
|
||||||
|
if len(v.option.DialerProxy) > 0 {
|
||||||
|
cDialer, err = proxydialer.NewByName(v.option.DialerProxy, cDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c, err := cDialer.DialContext(context.Background(), "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -403,38 +453,39 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
if option.ServerName == "" {
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
gunConfig.Host = v.addr
|
||||||
ServerName: v.option.ServerName,
|
|
||||||
}
|
}
|
||||||
|
var tlsConfig *tls.Config
|
||||||
if v.option.ServerName == "" {
|
if option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
tlsConfig.ServerName = host
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
gunConfig.Host = host
|
ServerName: v.option.ServerName,
|
||||||
|
})
|
||||||
|
if option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.ServerName = host
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type threadSafePacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
access sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
c.access.Lock()
|
|
||||||
defer c.access.Unlock()
|
|
||||||
return c.PacketConn.WriteTo(b, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
@ -444,9 +495,9 @@ type vmessPacketConn struct {
|
|||||||
// WriteTo implments C.PacketConn.WriteTo
|
// WriteTo implments C.PacketConn.WriteTo
|
||||||
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
allowedAddr := uc.rAddr.(*net.UDPAddr)
|
allowedAddr := uc.rAddr
|
||||||
destAddr := addr.(*net.UDPAddr)
|
destAddr := addr
|
||||||
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
if allowedAddr.String() != destAddr.String() {
|
||||||
return 0, ErrUDPRemoteAddrMismatch
|
return 0, ErrUDPRemoteAddrMismatch
|
||||||
}
|
}
|
||||||
uc.access.Lock()
|
uc.access.Lock()
|
||||||
|
@ -15,9 +15,11 @@ import (
|
|||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/listener/sing"
|
"github.com/Dreamacro/clash/dns"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
@ -34,66 +36,100 @@ type WireGuard struct {
|
|||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer *wgDialer
|
dialer *wgSingDialer
|
||||||
startOnce sync.Once
|
startOnce sync.Once
|
||||||
startErr error
|
startErr error
|
||||||
|
resolver *dns.Resolver
|
||||||
|
refP *refProxyAdapter
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardOption struct {
|
type WireGuardOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
WireGuardPeerOption
|
||||||
Server string `proxy:"server"`
|
Name string `proxy:"name"`
|
||||||
Port int `proxy:"port"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
Ip string `proxy:"ip,omitempty"`
|
Workers int `proxy:"workers,omitempty"`
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
PrivateKey string `proxy:"private-key"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
PublicKey string `proxy:"public-key"`
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
||||||
Workers int `proxy:"workers,omitempty"`
|
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
Dns []string `proxy:"dns,omitempty"`
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type wgDialer struct {
|
type WireGuardPeerOption struct {
|
||||||
options []dialer.Option
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
|
PublicKey string `proxy:"public-key,omitempty"`
|
||||||
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
|
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
type wgSingDialer struct {
|
||||||
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
dialer dialer.Dialer
|
||||||
|
proxyName string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
var _ N.Dialer = (*wgSingDialer)(nil)
|
||||||
return dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", destination.Addr), "", d.options...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
outbound := &WireGuard{
|
var cDialer C.Dialer = d.dialer
|
||||||
Base: &Base{
|
if len(d.proxyName) > 0 {
|
||||||
name: option.Name,
|
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
if err != nil {
|
||||||
tp: C.WireGuard,
|
return nil, err
|
||||||
udp: option.UDP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
dialer: &wgDialer{},
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
|
||||||
if len(option.Reserved) > 0 {
|
|
||||||
if len(option.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
|
||||||
}
|
}
|
||||||
reserved[0] = uint8(option.Reserved[0])
|
cDialer = pd
|
||||||
reserved[1] = uint8(option.Reserved[1])
|
|
||||||
reserved[2] = uint8(option.Reserved[2])
|
|
||||||
}
|
}
|
||||||
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
return cDialer.DialContext(ctx, network, destination.String())
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
}
|
||||||
|
|
||||||
|
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
var cDialer C.Dialer = d.dialer
|
||||||
|
if len(d.proxyName) > 0 {
|
||||||
|
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cDialer = pd
|
||||||
|
}
|
||||||
|
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgSingErrorHandler struct {
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ E.Handler = (*wgSingErrorHandler)(nil)
|
||||||
|
|
||||||
|
func (w wgSingErrorHandler) NewError(ctx context.Context, err error) {
|
||||||
|
if E.IsClosedOrCanceled(err) {
|
||||||
|
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) connection closed: %s", w.name, err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", w.name, err))
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgNetDialer struct {
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ dialer.NetDialer = (*wgNetDialer)(nil)
|
||||||
|
|
||||||
|
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
||||||
|
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (option WireGuardPeerOption) 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, "/") {
|
||||||
@ -118,7 +154,46 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
if len(localPrefixes) == 0 {
|
if len(localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
var privateKey, peerPublicKey, preSharedKey string
|
return localPrefixes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
|
outbound := &WireGuard{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.WireGuard,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
dialer: &wgSingDialer{dialer: dialer.NewDialer(), proxyName: option.DialerProxy},
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
|
var reserved [3]uint8
|
||||||
|
if len(option.Reserved) > 0 {
|
||||||
|
if len(option.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
||||||
|
}
|
||||||
|
copy(reserved[:], option.Reserved)
|
||||||
|
}
|
||||||
|
var isConnect bool
|
||||||
|
var connectAddr M.Socksaddr
|
||||||
|
if len(option.Peers) < 2 {
|
||||||
|
isConnect = true
|
||||||
|
if len(option.Peers) == 1 {
|
||||||
|
connectAddr = option.Peers[0].Addr()
|
||||||
|
} else {
|
||||||
|
connectAddr = option.Addr()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
||||||
|
|
||||||
|
var localPrefixes []netip.Prefix
|
||||||
|
|
||||||
|
var privateKey string
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -126,40 +201,92 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
privateKey = hex.EncodeToString(bytes)
|
privateKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
if option.PreSharedKey != "" {
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
|
||||||
}
|
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
ipcConf := "private_key=" + privateKey
|
ipcConf := "private_key=" + privateKey
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
if peersLen := len(option.Peers); peersLen > 0 {
|
||||||
ipcConf += "\nendpoint=" + peerAddr.String()
|
localPrefixes = make([]netip.Prefix, 0, peersLen*2)
|
||||||
if preSharedKey != "" {
|
for i, peer := range option.Peers {
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
var peerPublicKey, preSharedKey string
|
||||||
}
|
{
|
||||||
var has4, has6 bool
|
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
||||||
for _, address := range localPrefixes {
|
if err != nil {
|
||||||
if address.Addr().Is4() {
|
return nil, E.Cause(err, "decode public key for peer ", i)
|
||||||
has4 = true
|
}
|
||||||
} else {
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
has6 = true
|
}
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
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) != 3 {
|
||||||
|
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 {
|
||||||
|
var peerPublicKey, preSharedKey string
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
|
}
|
||||||
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
if option.PreSharedKey != "" {
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
|
}
|
||||||
|
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
|
||||||
if option.PersistentKeepalive != 0 {
|
if option.PersistentKeepalive != 0 {
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
||||||
}
|
}
|
||||||
@ -167,6 +294,9 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
|
if len(localPrefixes) == 0 {
|
||||||
|
return nil, E.New("missing local address")
|
||||||
|
}
|
||||||
var err error
|
var err error
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -174,20 +304,45 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
sing.Logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
Errorf: func(format string, args ...interface{}) {
|
Errorf: func(format string, args ...interface{}) {
|
||||||
sing.Logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
},
|
},
|
||||||
}, option.Workers)
|
}, option.Workers)
|
||||||
if debug.Enabled {
|
if debug.Enabled {
|
||||||
sing.Logger.Trace("created wireguard ipc conf: \n", ipcConf)
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
||||||
}
|
}
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
}
|
}
|
||||||
//err = outbound.tunDevice.Start()
|
//err = outbound.tunDevice.Start()
|
||||||
|
|
||||||
|
var has6 bool
|
||||||
|
for _, address := range localPrefixes {
|
||||||
|
if !address.Addr().Unmap().Is4() {
|
||||||
|
has6 = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
refP := &refProxyAdapter{}
|
||||||
|
outbound.refP = refP
|
||||||
|
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
||||||
|
nss, err := dns.ParseNameServer(option.Dns)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range nss {
|
||||||
|
nss[i].ProxyAdapter = refP
|
||||||
|
}
|
||||||
|
outbound.resolver = dns.NewResolver(dns.Config{
|
||||||
|
Main: nss,
|
||||||
|
IPv6: has6,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,7 +354,8 @@ func closeWireGuard(w *WireGuard) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
w.dialer.options = opts
|
options := w.Base.DialOptions(opts...)
|
||||||
|
w.dialer.dialer = dialer.NewDialer(options...)
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -207,16 +363,19 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
if w.startErr != nil {
|
if w.startErr != nil {
|
||||||
return nil, w.startErr
|
return nil, w.startErr
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
var addrs []netip.Addr
|
r := resolver.DefaultResolver
|
||||||
addrs, err = resolver.LookupIP(ctx, metadata.Host)
|
if w.resolver != nil {
|
||||||
if err != nil {
|
w.refP.SetProxyAdapter(w)
|
||||||
return nil, err
|
defer w.refP.ClearProxyAdapter()
|
||||||
|
r = w.resolver
|
||||||
}
|
}
|
||||||
conn, err = N.DialSerial(ctx, w.tunDevice, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()), addrs)
|
options = append(options, dialer.WithResolver(r))
|
||||||
|
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||||
|
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
} else {
|
} else {
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -228,7 +387,8 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
w.dialer.options = opts
|
options := w.Base.DialOptions(opts...)
|
||||||
|
w.dialer.dialer = dialer.NewDialer(options...)
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -239,15 +399,21 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() {
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
r := resolver.DefaultResolver
|
||||||
|
if w.resolver != nil {
|
||||||
|
w.refP.SetProxyAdapter(w)
|
||||||
|
defer w.refP.ClearProxyAdapter()
|
||||||
|
r = w.resolver
|
||||||
|
}
|
||||||
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -256,3 +422,144 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
}
|
}
|
||||||
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (w *WireGuard) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type refProxyAdapter struct {
|
||||||
|
proxyAdapter C.ProxyAdapter
|
||||||
|
count int
|
||||||
|
mutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SetProxyAdapter(proxyAdapter C.ProxyAdapter) {
|
||||||
|
r.mutex.Lock()
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
r.proxyAdapter = proxyAdapter
|
||||||
|
r.count++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) ClearProxyAdapter() {
|
||||||
|
r.mutex.Lock()
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
r.count--
|
||||||
|
if r.count == 0 {
|
||||||
|
r.proxyAdapter = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) Name() string {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.Name()
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) Type() C.AdapterType {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.Type()
|
||||||
|
}
|
||||||
|
return C.AdapterType(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) Addr() string {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.Addr()
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportUDP() bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportUDP()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportXUDP() bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportXUDP()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportTFO() bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportTFO()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) MarshalJSON() ([]byte, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.MarshalJSON()
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.StreamConnContext(ctx, c, metadata)
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportUOT() bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportUOT()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) SupportWithDialer() C.NetWork {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.SupportWithDialer()
|
||||||
|
}
|
||||||
|
return C.InvalidNet
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.DialContextWithDialer(ctx, dialer, metadata)
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.ListenPacketWithDialer(ctx, dialer, metadata)
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *refProxyAdapter) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
|
if r.proxyAdapter != nil {
|
||||||
|
return r.proxyAdapter.Unwrap(metadata, touch)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ C.ProxyAdapter = (*refProxyAdapter)(nil)
|
||||||
|
@ -4,11 +4,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
@ -29,11 +32,20 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
f.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
f.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,6 +70,11 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
return proxy.SupportUDP()
|
return proxy.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return f.findAliveProxy(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@ -121,6 +138,10 @@ func (f *Fallback) Set(name string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) ForceSet(name string) {
|
||||||
|
f.selected = name
|
||||||
|
}
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
@ -132,6 +153,7 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
@ -3,23 +3,26 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"go.uber.org/atomic"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filterRegs []*regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
excludeFilterReg *regexp2.Regexp
|
excludeFilterReg *regexp2.Regexp
|
||||||
|
excludeTypeArray []string
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
@ -33,6 +36,7 @@ type GroupBaseOption struct {
|
|||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
excludeFilter string
|
||||||
|
excludeType string
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,6 +45,10 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
if opt.excludeFilter != "" {
|
if opt.excludeFilter != "" {
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
||||||
}
|
}
|
||||||
|
var excludeTypeArray []string
|
||||||
|
if opt.excludeType != "" {
|
||||||
|
excludeTypeArray = strings.Split(opt.excludeType, "|")
|
||||||
|
}
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
@ -54,6 +62,7 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
Base: outbound.NewBase(opt.BaseOption),
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
filterRegs: filterRegs,
|
filterRegs: filterRegs,
|
||||||
excludeFilterReg: excludeFilterReg,
|
excludeFilterReg: excludeFilterReg,
|
||||||
|
excludeTypeArray: excludeTypeArray,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
}
|
}
|
||||||
@ -121,10 +130,6 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
proxiesSet := map[string]struct{}{}
|
proxiesSet := map[string]struct{}{}
|
||||||
@ -148,6 +153,25 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
proxies = newProxies
|
proxies = newProxies
|
||||||
}
|
}
|
||||||
|
if gb.excludeTypeArray != nil {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
for _, p := range proxies {
|
||||||
|
mType := p.Type().String()
|
||||||
|
flag := false
|
||||||
|
for i := range gb.excludeTypeArray {
|
||||||
|
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
||||||
|
flag = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if flag {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
if gb.excludeFilterReg != nil {
|
if gb.excludeFilterReg != nil {
|
||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
@ -161,6 +185,10 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
proxies = newProxies
|
proxies = newProxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,12 +5,15 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -18,7 +21,7 @@ import (
|
|||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
@ -83,17 +86,24 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := lb.Unwrap(metadata, true)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(lb)
|
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,14 +124,32 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
return !lb.disableUDP
|
return !lb.disableUDP
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return lb.Unwrap(metadata, false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
idxMutex := sync.Mutex{}
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
|
idxMutex.Lock()
|
||||||
|
defer idxMutex.Unlock()
|
||||||
|
|
||||||
|
i := 0
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
for i := 0; i < length; i++ {
|
|
||||||
idx = (idx + 1) % length
|
if touch {
|
||||||
proxy := proxies[idx]
|
defer func() {
|
||||||
|
idx = (idx + i) % length
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
for ; i < length; i++ {
|
||||||
|
id := (idx + i) % length
|
||||||
|
proxy := proxies[id]
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
|
i++
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,7 +160,7 @@ func strategyRoundRobin() strategyFn {
|
|||||||
|
|
||||||
func strategyConsistentHashing() strategyFn {
|
func strategyConsistentHashing() strategyFn {
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(proxies))
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
@ -160,7 +188,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
lruCache := cache.New[uint64, int](
|
lruCache := cache.New[uint64, int](
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
cache.WithSize[uint64, int](1000))
|
cache.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
idx, has := lruCache.Get(key)
|
idx, has := lruCache.Get(key)
|
||||||
@ -192,7 +220,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(touch)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata, touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -229,6 +257,7 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
@ -31,6 +31,7 @@ type GroupCommonOption struct {
|
|||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
|
ExcludeType string `group:"exclude-type,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) (C.ProxyAdapter, error) {
|
||||||
@ -77,7 +78,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" {
|
if groupOption.URL == "" {
|
||||||
groupOption.URL = "http://www.gstatic.com/generate_204"
|
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
|
@ -3,13 +3,9 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/proxydialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -18,36 +14,6 @@ type Relay struct {
|
|||||||
*GroupBase
|
*GroupBase
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyDialer struct {
|
|
||||||
proxy C.Proxy
|
|
||||||
dialer C.Dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p proxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
currentMeta, err := addrToMetadata(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if strings.Contains(network, "udp") { // should not support this operation
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
pc, err := p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return N.NewBindPacketConn(pc, currentMeta.UDPAddr()), nil
|
|
||||||
}
|
|
||||||
return p.proxy.DialContextWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
|
||||||
currentMeta, err := addrToMetadata(rAddrPort.String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
return p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
@ -61,10 +27,7 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
var d C.Dialer
|
var d C.Dialer
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
d = proxyDialer{
|
d = proxydialer.New(proxy, d, false)
|
||||||
proxy: proxy,
|
|
||||||
dialer: d,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
||||||
@ -95,10 +58,7 @@ func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
var d C.Dialer
|
var d C.Dialer
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
d = proxyDialer{
|
d = proxydialer.New(proxy, d, false)
|
||||||
proxy: proxy,
|
|
||||||
dialer: d,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
||||||
@ -129,7 +89,10 @@ func (r *Relay) SupportUDP() bool {
|
|||||||
if proxy.SupportUOT() {
|
if proxy.SupportUOT() {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if !proxy.SupportWithDialer() {
|
switch proxy.SupportWithDialer() {
|
||||||
|
case C.ALLNet:
|
||||||
|
case C.UDP:
|
||||||
|
default: // C.TCP and C.InvalidNet
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -176,7 +139,7 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Addr() string {
|
func (r *Relay) Addr() string {
|
||||||
proxies, _ := r.proxies(nil, true)
|
proxies, _ := r.proxies(nil, false)
|
||||||
return proxies[len(proxies)-1].Addr()
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -191,6 +154,7 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
},
|
},
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
|
"",
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
@ -44,6 +44,11 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
return s.selectedProxy(false).SupportUDP()
|
return s.selectedProxy(false).SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (s *Selector) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return s.selectedProxy(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@ -73,6 +78,10 @@ func (s *Selector) Set(name string) error {
|
|||||||
return errors.New("proxy not exist")
|
return errors.New("proxy not exist")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Selector) ForceSet(name string) {
|
||||||
|
s.selected = name
|
||||||
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return s.selectedProxy(touch)
|
return s.selectedProxy(touch)
|
||||||
@ -100,6 +109,7 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
@ -3,9 +3,12 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -22,6 +25,8 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
|
selected string
|
||||||
|
testUrl string
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
@ -32,16 +37,46 @@ func (u *URLTest) Now() string {
|
|||||||
return u.fast(false).Name()
|
return u.fast(false).Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Set(name string) error {
|
||||||
|
var p C.Proxy
|
||||||
|
for _, proxy := range u.GetProxies(false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
p = proxy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p == nil {
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
u.selected = name
|
||||||
|
u.fast(false)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) ForceSet(name string) {
|
||||||
|
u.selected = name
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := u.fast(true)
|
proxy := u.fast(true)
|
||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
u.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
u.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,8 +96,21 @@ func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
|
|
||||||
|
proxies := u.GetProxies(touch)
|
||||||
|
if u.selected != "" {
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if proxy.Name() == u.selected {
|
||||||
|
u.fastNode = proxy
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
@ -81,13 +129,12 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
fast = proxy
|
fast = proxy
|
||||||
min = delay
|
min = 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.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
@ -102,10 +149,14 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
if u.disableUDP {
|
if u.disableUDP {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return u.fast(false).SupportUDP()
|
return u.fast(false).SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return u.fast(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@ -144,10 +195,12 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
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,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -1,37 +1,10 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|
||||||
host, port, err := net.SplitHostPort(rawAddress)
|
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip, err := netip.ParseAddr(host); err != nil {
|
|
||||||
addr = &C.Metadata{
|
|
||||||
Host: host,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
addr = &C.Metadata{
|
|
||||||
Host: "",
|
|
||||||
DstIP: ip.Unmap(),
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
@ -41,4 +14,5 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
|
|
||||||
type SelectAble interface {
|
type SelectAble interface {
|
||||||
Set(string) error
|
Set(string) error
|
||||||
|
ForceSet(name string)
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,9 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -20,7 +23,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
)
|
)
|
||||||
switch proxyType {
|
switch proxyType {
|
||||||
case "ss":
|
case "ss":
|
||||||
ssOption := &outbound.ShadowSocksOption{}
|
ssOption := &outbound.ShadowSocksOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, ssOption)
|
err = decoder.Decode(mapping, ssOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -53,14 +56,16 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
|
ClientFingerprint: tlsC.GetGlobalFingerprint(),
|
||||||
}
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -74,7 +79,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{}
|
trojanOption := &outbound.TrojanOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -109,5 +114,19 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if muxMapping, muxExist := mapping["smux"].(map[string]any); muxExist {
|
||||||
|
muxOption := &outbound.SingMuxOption{}
|
||||||
|
err = decoder.Decode(muxMapping, muxOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if muxOption.Enabled {
|
||||||
|
proxy, err = outbound.NewSingMux(*muxOption, proxy, proxy.(outbound.ProxyBase))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return NewProxy(proxy), nil
|
return NewProxy(proxy), nil
|
||||||
}
|
}
|
||||||
|
@ -4,13 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -34,16 +33,15 @@ type HealthCheck struct {
|
|||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go func() {
|
|
||||||
time.Sleep(30 * time.Second)
|
|
||||||
hc.lazyCheck()
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
hc.lazyCheck()
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
} else {
|
||||||
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -51,17 +49,6 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) lazyCheck() bool {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -76,10 +63,7 @@ func (hc *HealthCheck) touch() {
|
|||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
id := ""
|
id := utils.NewUUIDV4().String()
|
||||||
if uid, err := uuid.NewV4(); err == nil {
|
|
||||||
id = uid.String()
|
|
||||||
}
|
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
|
@ -3,10 +3,10 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -27,6 +27,8 @@ type proxyProviderSchema struct {
|
|||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
|
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,5 +65,8 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
excludeFilter := schema.ExcludeFilter
|
excludeFilter := schema.ExcludeFilter
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, vehicle, hc)
|
excludeType := schema.ExcludeType
|
||||||
|
dialerProxy := schema.DialerProxy
|
||||||
|
|
||||||
|
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -5,8 +5,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
@ -19,6 +17,10 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"github.com/Dreamacro/clash/tunnel/statistic"
|
||||||
|
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -79,6 +81,8 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pp.OnUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
|
pp.getSubscriptionInfo()
|
||||||
|
pp.closeAllConnections()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,7 +102,7 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
defer func() { go pp.healthCheck.lazyCheck() }()
|
go pp.healthCheck.check()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,16 +140,33 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) closeAllConnections() {
|
||||||
|
snapshot := statistic.DefaultManager.Snapshot()
|
||||||
|
for _, c := range snapshot.Connections {
|
||||||
|
for _, chain := range c.Chains() {
|
||||||
|
if chain == pp.Name() {
|
||||||
|
_ = c.Close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.Fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
}
|
}
|
||||||
|
var excludeTypeArray []string
|
||||||
|
if excludeType != "" {
|
||||||
|
excludeTypeArray = strings.Split(excludeType, "|")
|
||||||
|
}
|
||||||
|
|
||||||
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, 0)
|
||||||
@ -164,10 +185,8 @@ 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, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg, dialerProxy), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
pd.getSubscriptionInfo()
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -262,7 +281,7 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@ -282,6 +301,28 @@ func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*re
|
|||||||
proxiesSet := map[string]struct{}{}
|
proxiesSet := map[string]struct{}{}
|
||||||
for _, filterReg := range filterRegs {
|
for _, filterReg := range filterRegs {
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
|
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
||||||
|
mType, ok := mapping["type"]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pType, ok := mType.(string)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
flag := false
|
||||||
|
for i := range excludeTypeArray {
|
||||||
|
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
||||||
|
flag = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if flag {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
mName, ok := mapping["name"]
|
mName, ok := mapping["name"]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@ -303,6 +344,9 @@ func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*re
|
|||||||
if _, ok := proxiesSet[name]; ok {
|
if _, ok := proxiesSet[name]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if len(dialerProxy) > 0 {
|
||||||
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
|
}
|
||||||
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)
|
||||||
|
205
common/atomic/type.go
Normal file
205
common/atomic/type.go
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Bool struct {
|
||||||
|
atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBool(val bool) *Bool {
|
||||||
|
i := &Bool{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) UnmarshalJSON(b []byte) error {
|
||||||
|
var v bool
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatBool(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pointer[T any] struct {
|
||||||
|
atomic.Pointer[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPointer[T any](v *T) *Pointer[T] {
|
||||||
|
var p Pointer[T]
|
||||||
|
if v != nil {
|
||||||
|
p.Store(v)
|
||||||
|
}
|
||||||
|
return &p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(p.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) UnmarshalJSON(b []byte) error {
|
||||||
|
var v *T
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) String() string {
|
||||||
|
return fmt.Sprint(p.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
type Int32 struct {
|
||||||
|
atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInt32(val int32) *Int32 {
|
||||||
|
i := &Int32{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) UnmarshalJSON(b []byte) error {
|
||||||
|
var v int32
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Int64 struct {
|
||||||
|
atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInt64(val int64) *Int64 {
|
||||||
|
i := &Int64{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) UnmarshalJSON(b []byte) error {
|
||||||
|
var v int64
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uint32 struct {
|
||||||
|
atomic.Uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUint32(val uint32) *Uint32 {
|
||||||
|
i := &Uint32{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uint32
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uint64 struct {
|
||||||
|
atomic.Uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUint64(val uint64) *Uint64 {
|
||||||
|
i := &Uint64{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uint64
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uintptr struct {
|
||||||
|
atomic.Uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUintptr(val uintptr) *Uintptr {
|
||||||
|
i := &Uintptr{}
|
||||||
|
i.Store(val)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uintptr
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
58
common/atomic/value.go
Normal file
58
common/atomic/value.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
func DefaultValue[T any]() T {
|
||||||
|
var defaultValue T
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
type TypedValue[T any] struct {
|
||||||
|
value atomic.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Load() T {
|
||||||
|
value := t.value.Load()
|
||||||
|
if value == nil {
|
||||||
|
return DefaultValue[T]()
|
||||||
|
}
|
||||||
|
return value.(T)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
|
t.value.Store(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Swap(new T) T {
|
||||||
|
old := t.value.Swap(new)
|
||||||
|
if old == nil {
|
||||||
|
return DefaultValue[T]()
|
||||||
|
}
|
||||||
|
return old.(T)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
|
return t.value.CompareAndSwap(old, new)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(t.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) UnmarshalJSON(b []byte) error {
|
||||||
|
var v T
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTypedValue[T any](t T) *TypedValue[T] {
|
||||||
|
v := &TypedValue[T]{}
|
||||||
|
v.Store(t)
|
||||||
|
return v
|
||||||
|
}
|
29
common/buf/sing.go
Normal file
29
common/buf/sing.go
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
package buf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
)
|
||||||
|
|
||||||
|
const BufferSize = buf.BufferSize
|
||||||
|
|
||||||
|
type Buffer = buf.Buffer
|
||||||
|
|
||||||
|
var New = buf.New
|
||||||
|
var NewSize = buf.NewSize
|
||||||
|
var StackNew = buf.StackNew
|
||||||
|
var StackNewSize = buf.StackNewSize
|
||||||
|
var With = buf.With
|
||||||
|
var As = buf.As
|
||||||
|
|
||||||
|
var KeepAlive = common.KeepAlive
|
||||||
|
|
||||||
|
//go:norace
|
||||||
|
func Dup[T any](obj T) T {
|
||||||
|
return common.Dup(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
Must = common.Must
|
||||||
|
Error = common.Error
|
||||||
|
)
|
55
common/callback/callback.go
Normal file
55
common/callback/callback.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package callback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type firstWriteCallBackConn struct {
|
||||||
|
C.Conn
|
||||||
|
callback func(error)
|
||||||
|
written bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
||||||
|
defer func() {
|
||||||
|
if !c.written {
|
||||||
|
c.written = true
|
||||||
|
c.callback(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return c.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if !c.written {
|
||||||
|
c.written = true
|
||||||
|
c.callback(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return c.Conn.WriteBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) Upstream() any {
|
||||||
|
return c.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) WriterReplaceable() bool {
|
||||||
|
return c.written
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.ExtendedConn = (*firstWriteCallBackConn)(nil)
|
||||||
|
|
||||||
|
func NewFirstWriteCallBackConn(c C.Conn, callback func(error)) C.Conn {
|
||||||
|
return &firstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
callback: callback,
|
||||||
|
written: false,
|
||||||
|
}
|
||||||
|
}
|
@ -2,11 +2,14 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
@ -81,7 +84,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["port"] = urlTrojan.Port()
|
trojan["port"] = urlTrojan.Port()
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
trojan["password"] = urlTrojan.User.Username()
|
||||||
trojan["udp"] = true
|
trojan["udp"] = true
|
||||||
trojan["skip-cert-verify"] = false
|
trojan["skip-cert-verify"], _ = strconv.ParseBool(query.Get("allowInsecure"))
|
||||||
|
|
||||||
sni := query.Get("sni")
|
sni := query.Get("sni")
|
||||||
if sni != "" {
|
if sni != "" {
|
||||||
@ -111,6 +114,12 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["grpc-opts"] = grpcOpts
|
trojan["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||||
|
trojan["client-fingerprint"] = "chrome"
|
||||||
|
} else {
|
||||||
|
trojan["client-fingerprint"] = fingerprint
|
||||||
|
}
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
proxies = append(proxies, trojan)
|
||||||
|
|
||||||
case "vless":
|
case "vless":
|
||||||
@ -120,7 +129,11 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
query := urlVLess.Query()
|
query := urlVLess.Query()
|
||||||
vless := make(map[string]any, 20)
|
vless := make(map[string]any, 20)
|
||||||
handleVShareLink(names, urlVLess, scheme, vless)
|
err = handleVShareLink(names, urlVLess, scheme, vless)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("error:%s line:%s", err.Error(), line)
|
||||||
|
continue
|
||||||
|
}
|
||||||
if flow := query.Get("flow"); flow != "" {
|
if flow := query.Get("flow"); flow != "" {
|
||||||
vless["flow"] = strings.ToLower(flow)
|
vless["flow"] = strings.ToLower(flow)
|
||||||
}
|
}
|
||||||
@ -138,20 +151,16 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
query := urlVMess.Query()
|
query := urlVMess.Query()
|
||||||
vmess := make(map[string]any, 20)
|
vmess := make(map[string]any, 20)
|
||||||
handleVShareLink(names, urlVMess, scheme, vmess)
|
err = handleVShareLink(names, urlVMess, scheme, vmess)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("error:%s line:%s", err.Error(), line)
|
||||||
|
continue
|
||||||
|
}
|
||||||
vmess["alterId"] = 0
|
vmess["alterId"] = 0
|
||||||
vmess["cipher"] = "auto"
|
vmess["cipher"] = "auto"
|
||||||
if encryption := query.Get("encryption"); encryption != "" {
|
if encryption := query.Get("encryption"); encryption != "" {
|
||||||
vmess["cipher"] = encryption
|
vmess["cipher"] = encryption
|
||||||
}
|
}
|
||||||
if packetEncoding := query.Get("packetEncoding"); packetEncoding != "" {
|
|
||||||
switch packetEncoding {
|
|
||||||
case "packet":
|
|
||||||
vmess["packet-addr"] = true
|
|
||||||
case "xudp":
|
|
||||||
vmess["xudp"] = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxies = append(proxies, vmess)
|
proxies = append(proxies, vmess)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -162,8 +171,11 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if jsonDc.Decode(&values) != nil {
|
if jsonDc.Decode(&values) != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
tempName, ok := values["ps"].(string)
|
||||||
name := uniqueName(names, values["ps"].(string))
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := uniqueName(names, tempName)
|
||||||
vmess := make(map[string]any, 20)
|
vmess := make(map[string]any, 20)
|
||||||
|
|
||||||
vmess["name"] = name
|
vmess["name"] = name
|
||||||
@ -177,6 +189,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["alterId"] = 0
|
vmess["alterId"] = 0
|
||||||
}
|
}
|
||||||
vmess["udp"] = true
|
vmess["udp"] = true
|
||||||
|
vmess["xudp"] = true
|
||||||
vmess["tls"] = false
|
vmess["tls"] = false
|
||||||
vmess["skip-cert-verify"] = false
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
@ -189,7 +202,8 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["servername"] = sni
|
vmess["servername"] = sni
|
||||||
}
|
}
|
||||||
|
|
||||||
network := strings.ToLower(values["net"].(string))
|
network, _ := values["net"].(string)
|
||||||
|
network = strings.ToLower(network)
|
||||||
if values["type"] == "http" {
|
if values["type"] == "http" {
|
||||||
network = "http"
|
network = "http"
|
||||||
} else if network == "http" {
|
} else if network == "http" {
|
||||||
@ -197,9 +211,12 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
vmess["network"] = network
|
vmess["network"] = network
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
tls, ok := values["tls"].(string)
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if ok {
|
||||||
vmess["tls"] = true
|
tls = strings.ToLower(tls)
|
||||||
|
if strings.HasSuffix(tls, "tls") {
|
||||||
|
vmess["tls"] = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
@ -272,19 +289,25 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
cipher = urlSS.User.Username()
|
cipherRaw = urlSS.User.Username()
|
||||||
password string
|
cipher string
|
||||||
|
password string
|
||||||
)
|
)
|
||||||
|
cipher = cipherRaw
|
||||||
if password, found = urlSS.User.Password(); !found {
|
if password, found = urlSS.User.Password(); !found {
|
||||||
dcBuf, _ := enc.DecodeString(cipher)
|
dcBuf, err := base64.RawURLEncoding.DecodeString(cipherRaw)
|
||||||
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
if err != nil {
|
||||||
dcBuf, _ = encRaw.DecodeString(cipher)
|
dcBuf, _ = enc.DecodeString(cipherRaw)
|
||||||
}
|
}
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
if !found {
|
if !found {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
err = VerifyMethod(cipher, password)
|
||||||
|
if err != nil {
|
||||||
|
dcBuf, _ = encRaw.DecodeString(cipherRaw)
|
||||||
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ss := make(map[string]any, 10)
|
ss := make(map[string]any, 10)
|
||||||
|
@ -2,11 +2,14 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
|
||||||
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@ -291,8 +294,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func RandHost() string {
|
func RandHost() string {
|
||||||
id, _ := uuid.NewV4()
|
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(utils.NewUUIDV4().Bytes()))
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
base = strings.ReplaceAll(base, "-", "")
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
base = strings.ReplaceAll(base, "_", "")
|
||||||
buf := []byte(base)
|
buf := []byte(base)
|
||||||
@ -300,11 +302,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[rand.Intn(uaLen)]
|
return userAgents[fastrand.Intn(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
@ -314,3 +316,8 @@ func SetUserAgent(header http.Header) {
|
|||||||
userAgent := RandUserAgent()
|
userAgent := RandUserAgent()
|
||||||
header.Set("User-Agent", userAgent)
|
header.Set("User-Agent", userAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func VerifyMethod(cipher, password string) (err error) {
|
||||||
|
_, err = shadowimpl.FetchMethod(cipher, password, time.Now)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
@ -1,15 +1,24 @@
|
|||||||
package convert
|
package convert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) error {
|
||||||
// Xray VMessAEAD / VLESS share link standard
|
// Xray VMessAEAD / VLESS share link standard
|
||||||
// https://github.com/XTLS/Xray-core/discussions/716
|
// https://github.com/XTLS/Xray-core/discussions/716
|
||||||
query := url.Query()
|
query := url.Query()
|
||||||
proxy["name"] = uniqueName(names, url.Fragment)
|
proxy["name"] = uniqueName(names, url.Fragment)
|
||||||
|
if url.Hostname() == "" {
|
||||||
|
return errors.New("url.Hostname() is empty")
|
||||||
|
}
|
||||||
|
if url.Port() == "" {
|
||||||
|
return errors.New("url.Port() is empty")
|
||||||
|
}
|
||||||
proxy["type"] = scheme
|
proxy["type"] = scheme
|
||||||
proxy["server"] = url.Hostname()
|
proxy["server"] = url.Hostname()
|
||||||
proxy["port"] = url.Port()
|
proxy["port"] = url.Port()
|
||||||
@ -18,12 +27,31 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
proxy["skip-cert-verify"] = false
|
proxy["skip-cert-verify"] = false
|
||||||
proxy["tls"] = false
|
proxy["tls"] = false
|
||||||
tls := strings.ToLower(query.Get("security"))
|
tls := strings.ToLower(query.Get("security"))
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if strings.HasSuffix(tls, "tls") || tls == "reality" {
|
||||||
proxy["tls"] = true
|
proxy["tls"] = true
|
||||||
|
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||||
|
proxy["client-fingerprint"] = "chrome"
|
||||||
|
} else {
|
||||||
|
proxy["client-fingerprint"] = fingerprint
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if sni := query.Get("sni"); sni != "" {
|
if sni := query.Get("sni"); sni != "" {
|
||||||
proxy["servername"] = sni
|
proxy["servername"] = sni
|
||||||
}
|
}
|
||||||
|
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
|
||||||
|
proxy["reality-opts"] = map[string]any{
|
||||||
|
"public-key": realityPublicKey,
|
||||||
|
"short-id": query.Get("sid"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch query.Get("packetEncoding") {
|
||||||
|
case "none":
|
||||||
|
case "packet":
|
||||||
|
proxy["packet-addr"] = true
|
||||||
|
default:
|
||||||
|
proxy["xudp"] = true
|
||||||
|
}
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
network := strings.ToLower(query.Get("type"))
|
||||||
if network == "" {
|
if network == "" {
|
||||||
@ -79,6 +107,17 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
if earlyData := query.Get("ed"); earlyData != "" {
|
||||||
|
med, err := strconv.Atoi(earlyData)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
||||||
|
}
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
}
|
||||||
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
}
|
||||||
|
|
||||||
proxy["ws-opts"] = wsOpts
|
proxy["ws-opts"] = wsOpts
|
||||||
|
|
||||||
case "grpc":
|
case "grpc":
|
||||||
@ -86,4 +125,5 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
proxy["grpc-opts"] = grpcOpts
|
proxy["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -5,10 +5,10 @@
|
|||||||
// Package list implements a doubly linked list.
|
// Package list implements a doubly linked list.
|
||||||
//
|
//
|
||||||
// To iterate over a list (where l is a *List):
|
// To iterate over a list (where l is a *List):
|
||||||
|
//
|
||||||
// for e := l.Front(); e != nil; e = e.Next() {
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
// // do something with e.Value
|
// // do something with e.Value
|
||||||
// }
|
// }
|
||||||
//
|
|
||||||
package list
|
package list
|
||||||
|
|
||||||
// Element is an element of a linked list.
|
// Element is an element of a linked list.
|
||||||
|
36
common/net/addr.go
Normal file
36
common/net/addr.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CustomAddr interface {
|
||||||
|
net.Addr
|
||||||
|
RawAddr() net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
type customAddr struct {
|
||||||
|
networkStr string
|
||||||
|
addrStr string
|
||||||
|
rawAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) Network() string {
|
||||||
|
return a.networkStr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) String() string {
|
||||||
|
return a.addrStr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) RawAddr() net.Addr {
|
||||||
|
return a.rawAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomAddr(networkStr string, addrStr string, rawAddr net.Addr) CustomAddr {
|
||||||
|
return customAddr{
|
||||||
|
networkStr: networkStr,
|
||||||
|
addrStr: addrStr,
|
||||||
|
rawAddr: rawAddr,
|
||||||
|
}
|
||||||
|
}
|
@ -3,34 +3,43 @@ package net
|
|||||||
import "net"
|
import "net"
|
||||||
|
|
||||||
type bindPacketConn struct {
|
type bindPacketConn struct {
|
||||||
net.PacketConn
|
EnhancePacketConn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
func (c *bindPacketConn) Read(b []byte) (n int, err error) {
|
||||||
n, _, err = wpc.PacketConn.ReadFrom(b)
|
n, _, err = c.EnhancePacketConn.ReadFrom(b)
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
func (c *bindPacketConn) WaitRead() (data []byte, put func(), err error) {
|
||||||
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
data, put, _, err = c.EnhancePacketConn.WaitReadFrom()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
func (c *bindPacketConn) Write(b []byte) (n int, err error) {
|
||||||
return wpc.rAddr
|
return c.EnhancePacketConn.WriteTo(b, c.rAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
func (c *bindPacketConn) RemoteAddr() net.Addr {
|
||||||
if wpc.PacketConn.LocalAddr() == nil {
|
return c.rAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *bindPacketConn) LocalAddr() net.Addr {
|
||||||
|
if c.EnhancePacketConn.LocalAddr() == nil {
|
||||||
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
} else {
|
} else {
|
||||||
return wpc.PacketConn.LocalAddr()
|
return c.EnhancePacketConn.LocalAddr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *bindPacketConn) Upstream() any {
|
||||||
|
return c.EnhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
||||||
return &bindPacketConn{
|
return &bindPacketConn{
|
||||||
PacketConn: pc,
|
EnhancePacketConn: NewEnhancePacketConn(pc),
|
||||||
rAddr: rAddr,
|
rAddr: rAddr,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,18 +3,23 @@ package net
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ ExtendedConn = (*BufferedConn)(nil)
|
||||||
|
|
||||||
type BufferedConn struct {
|
type BufferedConn struct {
|
||||||
r *bufio.Reader
|
r *bufio.Reader
|
||||||
net.Conn
|
ExtendedConn
|
||||||
|
peeked bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBufferedConn(c net.Conn) *BufferedConn {
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||||
if bc, ok := c.(*BufferedConn); ok {
|
if bc, ok := c.(*BufferedConn); ok {
|
||||||
return bc
|
return bc
|
||||||
}
|
}
|
||||||
return &BufferedConn{bufio.NewReader(c), c}
|
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reader returns the internal bufio.Reader.
|
// Reader returns the internal bufio.Reader.
|
||||||
@ -22,11 +27,24 @@ func (c *BufferedConn) Reader() *bufio.Reader {
|
|||||||
return c.r
|
return c.r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ResetPeeked() {
|
||||||
|
c.peeked = false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Peeked() bool {
|
||||||
|
return c.peeked
|
||||||
|
}
|
||||||
|
|
||||||
// Peek returns the next n bytes without advancing the reader.
|
// Peek returns the next n bytes without advancing the reader.
|
||||||
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||||
|
c.peeked = true
|
||||||
return c.r.Peek(n)
|
return c.r.Peek(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Discard(n int) (discarded int, err error) {
|
||||||
|
return c.r.Discard(n)
|
||||||
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) Read(p []byte) (int, error) {
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
||||||
return c.r.Read(p)
|
return c.r.Read(p)
|
||||||
}
|
}
|
||||||
@ -42,3 +60,37 @@ func (c *BufferedConn) UnreadByte() error {
|
|||||||
func (c *BufferedConn) Buffered() int {
|
func (c *BufferedConn) Buffered() int {
|
||||||
return c.r.Buffered()
|
return c.r.Buffered()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||||
|
if c.r != nil && c.r.Buffered() > 0 {
|
||||||
|
_, err = buffer.ReadOnceFrom(c.r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
|
||||||
|
if c.r != nil && c.r.Buffered() > 0 {
|
||||||
|
length := c.r.Buffered()
|
||||||
|
b, _ := c.r.Peek(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 nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Upstream() any {
|
||||||
|
return c.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReaderReplaceable() bool {
|
||||||
|
if c.r != nil && c.r.Buffered() > 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
154
common/net/deadline/packet.go
Normal file
154
common/net/deadline/packet.go
Normal file
@ -0,0 +1,154 @@
|
|||||||
|
package deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
|
)
|
||||||
|
|
||||||
|
type readResult struct {
|
||||||
|
data []byte
|
||||||
|
addr net.Addr
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type NetPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
deadline atomic.TypedValue[time.Time]
|
||||||
|
pipeDeadline pipeDeadline
|
||||||
|
disablePipe atomic.Bool
|
||||||
|
inRead atomic.Bool
|
||||||
|
resultCh chan any
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewNetPacketConn(pc net.PacketConn) net.PacketConn {
|
||||||
|
npc := &NetPacketConn{
|
||||||
|
PacketConn: pc,
|
||||||
|
pipeDeadline: makePipeDeadline(),
|
||||||
|
resultCh: make(chan any, 1),
|
||||||
|
}
|
||||||
|
npc.resultCh <- nil
|
||||||
|
if enhancePC, isEnhance := pc.(packet.EnhancePacketConn); isEnhance {
|
||||||
|
epc := &EnhancePacketConn{
|
||||||
|
NetPacketConn: npc,
|
||||||
|
enhancePacketConn: enhancePacketConn{
|
||||||
|
netPacketConn: npc,
|
||||||
|
enhancePacketConn: enhancePC,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
||||||
|
return &EnhanceSingPacketConn{
|
||||||
|
EnhancePacketConn: epc,
|
||||||
|
singPacketConn: singPacketConn{
|
||||||
|
netPacketConn: npc,
|
||||||
|
singPacketConn: singPC,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return epc
|
||||||
|
}
|
||||||
|
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
||||||
|
return &SingPacketConn{
|
||||||
|
NetPacketConn: npc,
|
||||||
|
singPacketConn: singPacketConn{
|
||||||
|
netPacketConn: npc,
|
||||||
|
singPacketConn: singPC,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return npc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
FOR:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case result := <-c.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
if result, ok := result.(*readResult); ok {
|
||||||
|
n = copy(p, result.data)
|
||||||
|
addr = result.addr
|
||||||
|
err = result.err
|
||||||
|
c.resultCh <- nil // finish cache read
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.resultCh <- result // another type of read
|
||||||
|
runtime.Gosched() // allowing other goroutines to run
|
||||||
|
continue FOR
|
||||||
|
} else {
|
||||||
|
c.resultCh <- nil
|
||||||
|
break FOR
|
||||||
|
}
|
||||||
|
case <-c.pipeDeadline.wait():
|
||||||
|
return 0, nil, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.disablePipe.Load() {
|
||||||
|
return c.PacketConn.ReadFrom(p)
|
||||||
|
} else if c.deadline.Load().IsZero() {
|
||||||
|
c.inRead.Store(true)
|
||||||
|
defer c.inRead.Store(false)
|
||||||
|
n, addr, err = c.PacketConn.ReadFrom(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.resultCh
|
||||||
|
go c.pipeReadFrom(len(p))
|
||||||
|
|
||||||
|
return c.ReadFrom(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) pipeReadFrom(size int) {
|
||||||
|
buffer := make([]byte, size)
|
||||||
|
n, addr, err := c.PacketConn.ReadFrom(buffer)
|
||||||
|
buffer = buffer[:n]
|
||||||
|
result := &readResult{}
|
||||||
|
result.data = buffer
|
||||||
|
result.addr = addr
|
||||||
|
result.err = err
|
||||||
|
c.resultCh <- result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
if c.disablePipe.Load() {
|
||||||
|
return c.PacketConn.SetReadDeadline(t)
|
||||||
|
} else if c.inRead.Load() {
|
||||||
|
c.disablePipe.Store(true)
|
||||||
|
return c.PacketConn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
c.deadline.Store(t)
|
||||||
|
c.pipeDeadline.set(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) 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 *NetPacketConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) Upstream() any {
|
||||||
|
return c.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NetPacketConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return false
|
||||||
|
}
|
83
common/net/deadline/packet_enhance.go
Normal file
83
common/net/deadline/packet_enhance.go
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
package deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EnhancePacketConn struct {
|
||||||
|
*NetPacketConn
|
||||||
|
enhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ packet.EnhancePacketConn = (*EnhancePacketConn)(nil)
|
||||||
|
|
||||||
|
func NewEnhancePacketConn(pc packet.EnhancePacketConn) packet.EnhancePacketConn {
|
||||||
|
return NewNetPacketConn(pc).(packet.EnhancePacketConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
type enhanceReadResult struct {
|
||||||
|
data []byte
|
||||||
|
put func()
|
||||||
|
addr net.Addr
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type enhancePacketConn struct {
|
||||||
|
netPacketConn *NetPacketConn
|
||||||
|
enhancePacketConn packet.EnhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
FOR:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case result := <-c.netPacketConn.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
if result, ok := result.(*enhanceReadResult); ok {
|
||||||
|
data = result.data
|
||||||
|
put = result.put
|
||||||
|
addr = result.addr
|
||||||
|
err = result.err
|
||||||
|
c.netPacketConn.resultCh <- nil // finish cache read
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.netPacketConn.resultCh <- result // another type of read
|
||||||
|
runtime.Gosched() // allowing other goroutines to run
|
||||||
|
continue FOR
|
||||||
|
} else {
|
||||||
|
c.netPacketConn.resultCh <- nil
|
||||||
|
break FOR
|
||||||
|
}
|
||||||
|
case <-c.netPacketConn.pipeDeadline.wait():
|
||||||
|
return nil, nil, nil, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.netPacketConn.disablePipe.Load() {
|
||||||
|
return c.enhancePacketConn.WaitReadFrom()
|
||||||
|
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||||
|
c.netPacketConn.inRead.Store(true)
|
||||||
|
defer c.netPacketConn.inRead.Store(false)
|
||||||
|
data, put, addr, err = c.enhancePacketConn.WaitReadFrom()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.netPacketConn.resultCh
|
||||||
|
go c.pipeWaitReadFrom()
|
||||||
|
|
||||||
|
return c.WaitReadFrom()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) pipeWaitReadFrom() {
|
||||||
|
data, put, addr, err := c.enhancePacketConn.WaitReadFrom()
|
||||||
|
result := &enhanceReadResult{}
|
||||||
|
result.data = data
|
||||||
|
result.put = put
|
||||||
|
result.addr = addr
|
||||||
|
result.err = err
|
||||||
|
c.netPacketConn.resultCh <- result
|
||||||
|
}
|
177
common/net/deadline/packet_sing.go
Normal file
177
common/net/deadline/packet_sing.go
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
package deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SingPacketConn struct {
|
||||||
|
*NetPacketConn
|
||||||
|
singPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ packet.SingPacketConn = (*SingPacketConn)(nil)
|
||||||
|
|
||||||
|
func NewSingPacketConn(pc packet.SingPacketConn) packet.SingPacketConn {
|
||||||
|
return NewNetPacketConn(pc).(packet.SingPacketConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
type EnhanceSingPacketConn struct {
|
||||||
|
*EnhancePacketConn
|
||||||
|
singPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEnhanceSingPacketConn(pc packet.EnhanceSingPacketConn) packet.EnhanceSingPacketConn {
|
||||||
|
return NewNetPacketConn(pc).(packet.EnhanceSingPacketConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ packet.EnhanceSingPacketConn = (*EnhanceSingPacketConn)(nil)
|
||||||
|
|
||||||
|
type singReadResult struct {
|
||||||
|
buffer *buf.Buffer
|
||||||
|
destination M.Socksaddr
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type singPacketConn struct {
|
||||||
|
netPacketConn *NetPacketConn
|
||||||
|
singPacketConn packet.SingPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||||
|
FOR:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case result := <-c.netPacketConn.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
if result, ok := result.(*singReadResult); ok {
|
||||||
|
destination = result.destination
|
||||||
|
err = result.err
|
||||||
|
n, _ := buffer.Write(result.buffer.Bytes())
|
||||||
|
result.buffer.Advance(n)
|
||||||
|
if result.buffer.IsEmpty() {
|
||||||
|
result.buffer.Release()
|
||||||
|
}
|
||||||
|
c.netPacketConn.resultCh <- nil // finish cache read
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.netPacketConn.resultCh <- result // another type of read
|
||||||
|
runtime.Gosched() // allowing other goroutines to run
|
||||||
|
continue FOR
|
||||||
|
} else {
|
||||||
|
c.netPacketConn.resultCh <- nil
|
||||||
|
break FOR
|
||||||
|
}
|
||||||
|
case <-c.netPacketConn.pipeDeadline.wait():
|
||||||
|
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.netPacketConn.disablePipe.Load() {
|
||||||
|
return c.singPacketConn.ReadPacket(buffer)
|
||||||
|
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||||
|
c.netPacketConn.inRead.Store(true)
|
||||||
|
defer c.netPacketConn.inRead.Store(false)
|
||||||
|
destination, err = c.singPacketConn.ReadPacket(buffer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.netPacketConn.resultCh
|
||||||
|
go c.pipeReadPacket(buffer.FreeLen())
|
||||||
|
|
||||||
|
return c.ReadPacket(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketConn) pipeReadPacket(pLen int) {
|
||||||
|
buffer := buf.NewSize(pLen)
|
||||||
|
destination, err := c.singPacketConn.ReadPacket(buffer)
|
||||||
|
result := &singReadResult{}
|
||||||
|
result.destination = destination
|
||||||
|
result.err = err
|
||||||
|
c.netPacketConn.resultCh <- result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||||
|
return c.singPacketConn.WritePacket(buffer, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketConn) CreateReadWaiter() (N.PacketReadWaiter, bool) {
|
||||||
|
prw, isReadWaiter := bufio.CreatePacketReadWaiter(c.singPacketConn)
|
||||||
|
if isReadWaiter {
|
||||||
|
return &singPacketReadWaiter{
|
||||||
|
netPacketConn: c.netPacketConn,
|
||||||
|
packetReadWaiter: prw,
|
||||||
|
}, true
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.PacketReadWaiter = (*singPacketReadWaiter)(nil)
|
||||||
|
|
||||||
|
type singPacketReadWaiter struct {
|
||||||
|
netPacketConn *NetPacketConn
|
||||||
|
packetReadWaiter N.PacketReadWaiter
|
||||||
|
}
|
||||||
|
|
||||||
|
type singWaitReadResult singReadResult
|
||||||
|
|
||||||
|
func (c *singPacketReadWaiter) InitializeReadWaiter(newBuffer func() *buf.Buffer) {
|
||||||
|
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketReadWaiter) WaitReadPacket() (destination M.Socksaddr, err error) {
|
||||||
|
FOR:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case result := <-c.netPacketConn.resultCh:
|
||||||
|
if result != nil {
|
||||||
|
if result, ok := result.(*singWaitReadResult); ok {
|
||||||
|
destination = result.destination
|
||||||
|
err = result.err
|
||||||
|
c.netPacketConn.resultCh <- nil // finish cache read
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.netPacketConn.resultCh <- result // another type of read
|
||||||
|
runtime.Gosched() // allowing other goroutines to run
|
||||||
|
continue FOR
|
||||||
|
} else {
|
||||||
|
c.netPacketConn.resultCh <- nil
|
||||||
|
break FOR
|
||||||
|
}
|
||||||
|
case <-c.netPacketConn.pipeDeadline.wait():
|
||||||
|
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.netPacketConn.disablePipe.Load() {
|
||||||
|
return c.packetReadWaiter.WaitReadPacket()
|
||||||
|
} else if c.netPacketConn.deadline.Load().IsZero() {
|
||||||
|
c.netPacketConn.inRead.Store(true)
|
||||||
|
defer c.netPacketConn.inRead.Store(false)
|
||||||
|
destination, err = c.packetReadWaiter.WaitReadPacket()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
<-c.netPacketConn.resultCh
|
||||||
|
go c.pipeWaitReadPacket()
|
||||||
|
|
||||||
|
return c.WaitReadPacket()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
||||||
|
destination, err := c.packetReadWaiter.WaitReadPacket()
|
||||||
|
result := &singWaitReadResult{}
|
||||||
|
result.destination = destination
|
||||||
|
result.err = err
|
||||||
|
c.netPacketConn.resultCh <- result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *singPacketReadWaiter) Upstream() any {
|
||||||
|
return c.packetReadWaiter
|
||||||
|
}
|
84
common/net/deadline/pipe.go
Normal file
84
common/net/deadline/pipe.go
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
// Copyright 2010 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 deadline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// pipeDeadline is an abstraction for handling timeouts.
|
||||||
|
type pipeDeadline struct {
|
||||||
|
mu sync.Mutex // Guards timer and cancel
|
||||||
|
timer *time.Timer
|
||||||
|
cancel chan struct{} // Must be non-nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func makePipeDeadline() pipeDeadline {
|
||||||
|
return pipeDeadline{cancel: make(chan struct{})}
|
||||||
|
}
|
||||||
|
|
||||||
|
// set sets the point in time when the deadline will time out.
|
||||||
|
// A timeout event is signaled by closing the channel returned by waiter.
|
||||||
|
// Once a timeout has occurred, the deadline can be refreshed by specifying a
|
||||||
|
// t value in the future.
|
||||||
|
//
|
||||||
|
// A zero value for t prevents timeout.
|
||||||
|
func (d *pipeDeadline) set(t time.Time) {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
if d.timer != nil && !d.timer.Stop() {
|
||||||
|
<-d.cancel // Wait for the timer callback to finish and close cancel
|
||||||
|
}
|
||||||
|
d.timer = nil
|
||||||
|
|
||||||
|
// Time is zero, then there is no deadline.
|
||||||
|
closed := isClosedChan(d.cancel)
|
||||||
|
if t.IsZero() {
|
||||||
|
if closed {
|
||||||
|
d.cancel = make(chan struct{})
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time in the future, setup a timer to cancel in the future.
|
||||||
|
if dur := time.Until(t); dur > 0 {
|
||||||
|
if closed {
|
||||||
|
d.cancel = make(chan struct{})
|
||||||
|
}
|
||||||
|
d.timer = time.AfterFunc(dur, func() {
|
||||||
|
close(d.cancel)
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time in the past, so close immediately.
|
||||||
|
if !closed {
|
||||||
|
close(d.cancel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// wait returns a channel that is closed when the deadline is exceeded.
|
||||||
|
func (d *pipeDeadline) wait() chan struct{} {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
return d.cancel
|
||||||
|
}
|
||||||
|
|
||||||
|
func isClosedChan(c <-chan struct{}) bool {
|
||||||
|
select {
|
||||||
|
case <-c:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeFilledChan() chan struct{} {
|
||||||
|
ch := make(chan struct{}, 1)
|
||||||
|
ch <- struct{}{}
|
||||||
|
return ch
|
||||||
|
}
|
18
common/net/packet.go
Normal file
18
common/net/packet.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/common/net/deadline"
|
||||||
|
"github.com/Dreamacro/clash/common/net/packet"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EnhancePacketConn = packet.EnhancePacketConn
|
||||||
|
type WaitReadFrom = packet.WaitReadFrom
|
||||||
|
|
||||||
|
var NewEnhancePacketConn = packet.NewEnhancePacketConn
|
||||||
|
var NewThreadSafePacketConn = packet.NewThreadSafePacketConn
|
||||||
|
var NewRefPacketConn = packet.NewRefPacketConn
|
||||||
|
|
||||||
|
var NewDeadlineNetPacketConn = deadline.NewNetPacketConn
|
||||||
|
var NewDeadlineEnhancePacketConn = deadline.NewEnhancePacketConn
|
||||||
|
var NewDeadlineSingPacketConn = deadline.NewSingPacketConn
|
||||||
|
var NewDeadlineEnhanceSingPacketConn = deadline.NewEnhanceSingPacketConn
|
77
common/net/packet/packet.go
Normal file
77
common/net/packet/packet.go
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WaitReadFrom interface {
|
||||||
|
WaitReadFrom() (data []byte, put func(), addr net.Addr, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type EnhancePacketConn interface {
|
||||||
|
net.PacketConn
|
||||||
|
WaitReadFrom
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
|
||||||
|
if udpConn, isUDPConn := pc.(*net.UDPConn); isUDPConn {
|
||||||
|
return &enhanceUDPConn{UDPConn: udpConn}
|
||||||
|
}
|
||||||
|
if enhancePC, isEnhancePC := pc.(EnhancePacketConn); isEnhancePC {
|
||||||
|
return enhancePC
|
||||||
|
}
|
||||||
|
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||||
|
return newEnhanceSingPacketConn(singPC)
|
||||||
|
}
|
||||||
|
return &enhancePacketConn{PacketConn: pc}
|
||||||
|
}
|
||||||
|
|
||||||
|
type enhancePacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
return waitReadFrom(c.PacketConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) Upstream() any {
|
||||||
|
return c.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhancePacketConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceUDPConn) Upstream() any {
|
||||||
|
return c.UDPConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceUDPConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceUDPConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitReadFrom(pc net.PacketConn) (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
readBuf := pool.Get(pool.UDPBufferSize)
|
||||||
|
put = func() {
|
||||||
|
_ = pool.Put(readBuf)
|
||||||
|
}
|
||||||
|
var readN int
|
||||||
|
readN, addr, err = pc.ReadFrom(readBuf)
|
||||||
|
if readN > 0 {
|
||||||
|
data = readBuf[:readN]
|
||||||
|
} else {
|
||||||
|
put()
|
||||||
|
put = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
65
common/net/packet/packet_posix.go
Normal file
65
common/net/packet/packet_posix.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type enhanceUDPConn struct {
|
||||||
|
*net.UDPConn
|
||||||
|
rawConn syscall.RawConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
if c.rawConn == nil {
|
||||||
|
c.rawConn, _ = c.UDPConn.SyscallConn()
|
||||||
|
}
|
||||||
|
var readErr error
|
||||||
|
err = c.rawConn.Read(func(fd uintptr) (done bool) {
|
||||||
|
readBuf := pool.Get(pool.UDPBufferSize)
|
||||||
|
put = func() {
|
||||||
|
_ = pool.Put(readBuf)
|
||||||
|
}
|
||||||
|
var readFrom syscall.Sockaddr
|
||||||
|
var readN int
|
||||||
|
readN, _, _, readFrom, readErr = syscall.Recvmsg(int(fd), readBuf, nil, 0)
|
||||||
|
if readN > 0 {
|
||||||
|
data = readBuf[:readN]
|
||||||
|
} else {
|
||||||
|
put()
|
||||||
|
put = nil
|
||||||
|
data = nil
|
||||||
|
}
|
||||||
|
if readErr == syscall.EAGAIN {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if readFrom != nil {
|
||||||
|
switch from := readFrom.(type) {
|
||||||
|
case *syscall.SockaddrInet4:
|
||||||
|
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 4 bytes
|
||||||
|
addr = &net.UDPAddr{IP: ip[:], Port: from.Port}
|
||||||
|
case *syscall.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
|
||||||
|
//}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if readErr != nil {
|
||||||
|
err = readErr
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
79
common/net/packet/packet_sing.go
Normal file
79
common/net/packet/packet_sing.go
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SingPacketConn = N.NetPacketConn
|
||||||
|
|
||||||
|
type EnhanceSingPacketConn interface {
|
||||||
|
SingPacketConn
|
||||||
|
EnhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
type enhanceSingPacketConn struct {
|
||||||
|
SingPacketConn
|
||||||
|
packetReadWaiter N.PacketReadWaiter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
var buff *buf.Buffer
|
||||||
|
var dest M.Socksaddr
|
||||||
|
newBuffer := func() *buf.Buffer {
|
||||||
|
buff = buf.NewPacket() // do not use stack buffer
|
||||||
|
return buff
|
||||||
|
}
|
||||||
|
if c.packetReadWaiter != nil {
|
||||||
|
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
||||||
|
defer c.packetReadWaiter.InitializeReadWaiter(nil)
|
||||||
|
dest, err = c.packetReadWaiter.WaitReadPacket()
|
||||||
|
} else {
|
||||||
|
dest, err = c.SingPacketConn.ReadPacket(newBuffer())
|
||||||
|
}
|
||||||
|
if dest.IsFqdn() {
|
||||||
|
addr = dest
|
||||||
|
} else {
|
||||||
|
addr = dest.UDPAddr()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if buff != nil {
|
||||||
|
buff.Release()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if buff == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if buff.IsEmpty() {
|
||||||
|
buff.Release()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data = buff.Bytes()
|
||||||
|
put = buff.Release
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceSingPacketConn) Upstream() any {
|
||||||
|
return c.SingPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceSingPacketConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceSingPacketConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEnhanceSingPacketConn(conn SingPacketConn) *enhanceSingPacketConn {
|
||||||
|
epc := &enhanceSingPacketConn{SingPacketConn: conn}
|
||||||
|
if readWaiter, isReadWaiter := bufio.CreatePacketReadWaiter(conn); isReadWaiter {
|
||||||
|
epc.packetReadWaiter = readWaiter
|
||||||
|
}
|
||||||
|
return epc
|
||||||
|
}
|
15
common/net/packet/packet_windows.go
Normal file
15
common/net/packet/packet_windows.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type enhanceUDPConn struct {
|
||||||
|
*net.UDPConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
return waitReadFrom(c.UDPConn)
|
||||||
|
}
|
75
common/net/packet/ref.go
Normal file
75
common/net/packet/ref.go
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type refPacketConn struct {
|
||||||
|
pc EnhancePacketConn
|
||||||
|
ref any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.WaitReadFrom()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.ReadFrom(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.WriteTo(p, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) Close() error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) LocalAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.SetDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.pc.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) Upstream() any {
|
||||||
|
return c.pc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) ReaderReplaceable() bool { // Relay() will handle reference
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refPacketConn) WriterReplaceable() bool { // Relay() will handle reference
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRefPacketConn(pc net.PacketConn, ref any) EnhancePacketConn {
|
||||||
|
rPC := &refPacketConn{pc: NewEnhancePacketConn(pc), ref: ref}
|
||||||
|
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||||
|
return &refSingPacketConn{
|
||||||
|
refPacketConn: rPC,
|
||||||
|
singPacketConn: singPC,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rPC
|
||||||
|
}
|
26
common/net/packet/ref_sing.go
Normal file
26
common/net/packet/ref_sing.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type refSingPacketConn struct {
|
||||||
|
*refPacketConn
|
||||||
|
singPacketConn SingPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.NetPacketConn = (*refSingPacketConn)(nil)
|
||||||
|
|
||||||
|
func (c *refSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.singPacketConn.WritePacket(buffer, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.singPacketConn.ReadPacket(buffer)
|
||||||
|
}
|
36
common/net/packet/thread.go
Normal file
36
common/net/packet/thread.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type threadSafePacketConn struct {
|
||||||
|
EnhancePacketConn
|
||||||
|
access sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
c.access.Lock()
|
||||||
|
defer c.access.Unlock()
|
||||||
|
return c.EnhancePacketConn.WriteTo(b, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *threadSafePacketConn) Upstream() any {
|
||||||
|
return c.EnhancePacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *threadSafePacketConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewThreadSafePacketConn(pc net.PacketConn) EnhancePacketConn {
|
||||||
|
tsPC := &threadSafePacketConn{EnhancePacketConn: NewEnhancePacketConn(pc)}
|
||||||
|
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
||||||
|
return &threadSafeSingPacketConn{
|
||||||
|
threadSafePacketConn: tsPC,
|
||||||
|
singPacketConn: singPC,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tsPC
|
||||||
|
}
|
24
common/net/packet/thread_sing.go
Normal file
24
common/net/packet/thread_sing.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package packet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type threadSafeSingPacketConn struct {
|
||||||
|
*threadSafePacketConn
|
||||||
|
singPacketConn SingPacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.NetPacketConn = (*threadSafeSingPacketConn)(nil)
|
||||||
|
|
||||||
|
func (c *threadSafeSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||||
|
c.access.Lock()
|
||||||
|
defer c.access.Unlock()
|
||||||
|
return c.singPacketConn.WritePacket(buffer, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *threadSafeSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||||
|
return c.singPacketConn.ReadPacket(buffer)
|
||||||
|
}
|
@ -4,10 +4,12 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
type refConn struct {
|
type refConn struct {
|
||||||
conn net.Conn
|
conn ExtendedConn
|
||||||
ref any
|
ref any
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,50 +53,30 @@ func (c *refConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return c.conn.SetWriteDeadline(t)
|
return c.conn.SetWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Upstream() any {
|
||||||
|
return c.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.WriteBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) ReaderReplaceable() bool { // Relay() will handle reference
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) WriterReplaceable() bool { // Relay() will handle reference
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ ExtendedConn = (*refConn)(nil)
|
||||||
|
|
||||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||||
return &refConn{conn: conn, ref: ref}
|
return &refConn{conn: NewExtendedConn(conn), ref: ref}
|
||||||
}
|
|
||||||
|
|
||||||
type refPacketConn struct {
|
|
||||||
pc net.PacketConn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.ReadFrom(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.WriteTo(p, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefPacketConn(pc net.PacketConn, ref any) net.PacketConn {
|
|
||||||
return &refPacketConn{pc: pc, ref: ref}
|
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,24 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
//import (
|
||||||
"io"
|
// "io"
|
||||||
"net"
|
// "net"
|
||||||
"time"
|
// "time"
|
||||||
)
|
//)
|
||||||
|
//
|
||||||
// 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) {
|
||||||
ch := make(chan error)
|
// ch := make(chan error)
|
||||||
|
//
|
||||||
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/Dreamacro/clash/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
|
||||||
}()
|
// }()
|
||||||
|
//
|
||||||
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
rightConn.SetReadDeadline(time.Now())
|
// rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
// <-ch
|
||||||
}
|
//}
|
||||||
|
40
common/net/sing.go
Normal file
40
common/net/sing.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
"github.com/sagernet/sing/common/bufio/deadline"
|
||||||
|
"github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
var NewExtendedConn = bufio.NewExtendedConn
|
||||||
|
var NewExtendedWriter = bufio.NewExtendedWriter
|
||||||
|
var NewExtendedReader = bufio.NewExtendedReader
|
||||||
|
|
||||||
|
type ExtendedConn = network.ExtendedConn
|
||||||
|
type ExtendedWriter = network.ExtendedWriter
|
||||||
|
type ExtendedReader = network.ExtendedReader
|
||||||
|
|
||||||
|
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
||||||
|
return deadline.NewFallbackConn(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NeedHandshake(conn any) bool {
|
||||||
|
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type CountFunc = network.CountFunc
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
defer runtime.KeepAlive(leftConn)
|
||||||
|
defer runtime.KeepAlive(rightConn)
|
||||||
|
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
||||||
|
}
|
@ -1,11 +1,19 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/big"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
|
if certificate == "" && privateKey == "" {
|
||||||
|
return newRandomTLSKeyPair()
|
||||||
|
}
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||||
if painTextErr == nil {
|
if painTextErr == nil {
|
||||||
return cert, nil
|
return cert, nil
|
||||||
@ -17,3 +25,28 @@ func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
|||||||
}
|
}
|
||||||
return cert, nil
|
return cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
||||||
|
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
||||||
|
certDER, err := x509.CreateCertificate(
|
||||||
|
rand.Reader,
|
||||||
|
&template,
|
||||||
|
&template,
|
||||||
|
&key.PublicKey,
|
||||||
|
key)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||||
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||||
|
|
||||||
|
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
return tlsCert, nil
|
||||||
|
}
|
||||||
|
131
common/net/websocket.go
Normal file
131
common/net/websocket.go
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
// kanged from https://github.com/nhooyr/websocket/blob/master/frame.go
|
||||||
|
// License: MIT
|
||||||
|
|
||||||
|
// MaskWebSocket applies the WebSocket masking algorithm to p
|
||||||
|
// with the given key.
|
||||||
|
// See https://tools.ietf.org/html/rfc6455#section-5.3
|
||||||
|
//
|
||||||
|
// The returned value is the correctly rotated key to
|
||||||
|
// to continue to mask/unmask the message.
|
||||||
|
//
|
||||||
|
// It is optimized for LittleEndian and expects the key
|
||||||
|
// to be in little endian.
|
||||||
|
//
|
||||||
|
// See https://github.com/golang/go/issues/31586
|
||||||
|
func MaskWebSocket(key uint32, b []byte) uint32 {
|
||||||
|
if len(b) >= 8 {
|
||||||
|
key64 := uint64(key)<<32 | uint64(key)
|
||||||
|
|
||||||
|
// At some point in the future we can clean these unrolled loops up.
|
||||||
|
// See https://github.com/golang/go/issues/31586#issuecomment-487436401
|
||||||
|
|
||||||
|
// Then we xor until b is less than 128 bytes.
|
||||||
|
for len(b) >= 128 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[32:40])
|
||||||
|
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[40:48])
|
||||||
|
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[48:56])
|
||||||
|
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[56:64])
|
||||||
|
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[64:72])
|
||||||
|
binary.LittleEndian.PutUint64(b[64:72], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[72:80])
|
||||||
|
binary.LittleEndian.PutUint64(b[72:80], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[80:88])
|
||||||
|
binary.LittleEndian.PutUint64(b[80:88], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[88:96])
|
||||||
|
binary.LittleEndian.PutUint64(b[88:96], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[96:104])
|
||||||
|
binary.LittleEndian.PutUint64(b[96:104], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[104:112])
|
||||||
|
binary.LittleEndian.PutUint64(b[104:112], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[112:120])
|
||||||
|
binary.LittleEndian.PutUint64(b[112:120], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[120:128])
|
||||||
|
binary.LittleEndian.PutUint64(b[120:128], v^key64)
|
||||||
|
b = b[128:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 64 bytes.
|
||||||
|
for len(b) >= 64 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[32:40])
|
||||||
|
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[40:48])
|
||||||
|
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[48:56])
|
||||||
|
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[56:64])
|
||||||
|
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||||
|
b = b[64:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 32 bytes.
|
||||||
|
for len(b) >= 32 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
b = b[32:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 16 bytes.
|
||||||
|
for len(b) >= 16 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
b = b[16:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 8 bytes.
|
||||||
|
for len(b) >= 8 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
b = b[8:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 4 bytes.
|
||||||
|
for len(b) >= 4 {
|
||||||
|
v := binary.LittleEndian.Uint32(b)
|
||||||
|
binary.LittleEndian.PutUint32(b, v^key)
|
||||||
|
b = b[4:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// xor remaining bytes.
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= byte(key)
|
||||||
|
key = bits.RotateLeft32(key, -8)
|
||||||
|
}
|
||||||
|
|
||||||
|
return key
|
||||||
|
}
|
@ -5,8 +5,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator[T any](item []T) chan T {
|
func iterator[T any](item []T) chan T {
|
||||||
@ -44,7 +45,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan int) {
|
waitCh := func(ch <-chan int) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count.Inc()
|
count.Add(1)
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math/rand"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(rand.Int())
|
msb(fastrand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
15
common/pool/buffer_low_memory.go
Normal file
15
common/pool/buffer_low_memory.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
//go:build with_low_memory
|
||||||
|
|
||||||
|
package pool
|
||||||
|
|
||||||
|
const (
|
||||||
|
// io.Copy default buffer size is 32 KiB
|
||||||
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
|
RelayBufferSize = 16 * 1024
|
||||||
|
|
||||||
|
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
||||||
|
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
||||||
|
// set to 9000, so the UDP Buffer size set to 16Kib
|
||||||
|
UDPBufferSize = 8 * 1024
|
||||||
|
)
|
15
common/pool/buffer_standard.go
Normal file
15
common/pool/buffer_standard.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
//go:build !with_low_memory
|
||||||
|
|
||||||
|
package pool
|
||||||
|
|
||||||
|
const (
|
||||||
|
// io.Copy default buffer size is 32 KiB
|
||||||
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
|
RelayBufferSize = 20 * 1024
|
||||||
|
|
||||||
|
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
||||||
|
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
||||||
|
// set to 9000, so the UDP Buffer size set to 16Kib
|
||||||
|
UDPBufferSize = 16 * 1024
|
||||||
|
)
|
@ -1,17 +1,5 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
const (
|
|
||||||
// io.Copy default buffer size is 32 KiB
|
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
|
||||||
RelayBufferSize = 20 * 1024
|
|
||||||
|
|
||||||
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
|
||||||
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
|
||||||
// set to 9000, so the UDP Buffer size set to 16Kib
|
|
||||||
UDPBufferSize = 16 * 1024
|
|
||||||
)
|
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return defaultAllocator.Get(size)
|
return defaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
@ -5,8 +5,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/atomic"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBasic(t *testing.T) {
|
func TestBasic(t *testing.T) {
|
||||||
@ -26,7 +27,7 @@ func TestBasic(t *testing.T) {
|
|||||||
go func() {
|
go func() {
|
||||||
_, _, shard := single.Do(call)
|
_, _, shard := single.Do(call)
|
||||||
if shard {
|
if shard {
|
||||||
shardCount.Inc()
|
shardCount.Add(1)
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
|
8
common/utils/must.go
Normal file
8
common/utils/must.go
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
func MustOK[T any](result T, ok bool) T {
|
||||||
|
if ok {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
panic("operation failed")
|
||||||
|
}
|
34
common/utils/slice.go
Normal file
34
common/utils/slice.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
|
||||||
|
result := make([]T, 0)
|
||||||
|
for _, t := range tSlice {
|
||||||
|
if filter(t) {
|
||||||
|
result = append(result, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func ToStringSlice(value any) ([]string, error) {
|
||||||
|
strArr := make([]string, 0)
|
||||||
|
switch reflect.TypeOf(value).Kind() {
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
origin := reflect.ValueOf(value)
|
||||||
|
for i := 0; i < origin.Len(); i++ {
|
||||||
|
item := fmt.Sprintf("%v", origin.Index(i))
|
||||||
|
strArr = append(strArr, item)
|
||||||
|
}
|
||||||
|
case reflect.String:
|
||||||
|
strArr = append(strArr, fmt.Sprintf("%v", value))
|
||||||
|
default:
|
||||||
|
return nil, errors.New("value format error, must be string or array")
|
||||||
|
}
|
||||||
|
return strArr, nil
|
||||||
|
}
|
9
common/utils/strings.go
Normal file
9
common/utils/strings.go
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
func Reverse(s string) string {
|
||||||
|
a := []rune(s)
|
||||||
|
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
|
||||||
|
a[i], a[j] = a[j], a[i]
|
||||||
|
}
|
||||||
|
return string(a)
|
||||||
|
}
|
@ -1,16 +1,51 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid/v5"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
type fastRandReader struct{}
|
||||||
|
|
||||||
|
func (r fastRandReader) Read(p []byte) (int, error) {
|
||||||
|
return fastrand.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
|
||||||
|
|
||||||
|
func NewUUIDV1() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
|
||||||
|
return UnsafeUUIDGenerator.NewV3(ns, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV4() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
|
||||||
|
return UnsafeUUIDGenerator.NewV5(ns, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV6() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV7() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
func UUIDMap(str string) (uuid.UUID, error) {
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
u, err := uuid.FromString(str)
|
u, err := uuid.FromString(str)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return uuid.NewV5(uuidNamespace, str), nil
|
return NewUUIDV5(uuid.Nil, str), nil
|
||||||
}
|
}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid/v5"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
@ -10,16 +11,8 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type controlFn = func(network, address string, c syscall.RawConn) error
|
func bindControl(ifaceIdx int) controlFn {
|
||||||
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||||
func bindControl(ifaceIdx int, chain controlFn) controlFn {
|
|
||||||
return func(network, address string, c syscall.RawConn) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil && chain != nil {
|
|
||||||
err = chain(network, address, c)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
return
|
return
|
||||||
@ -49,7 +42,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
|
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,6 +52,10 @@ func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
lc.Control = bindControl(ifaceObj.Index, lc.Control)
|
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
||||||
return address, nil
|
return address, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
return network
|
||||||
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
@ -8,16 +9,8 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type controlFn = func(network, address string, c syscall.RawConn) error
|
func bindControl(ifaceName string) controlFn {
|
||||||
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||||
func bindControl(ifaceName string, chain controlFn) controlFn {
|
|
||||||
return func(network, address string, c syscall.RawConn) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil && chain != nil {
|
|
||||||
err = chain(network, address, c)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
return
|
return
|
||||||
@ -37,13 +30,17 @@ func bindControl(ifaceName string, chain controlFn) controlFn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
||||||
dialer.Control = bindControl(ifaceName, dialer.Control)
|
addControlToDialer(dialer, bindControl(ifaceName))
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
lc.Control = bindControl(ifaceName, lc.Control)
|
addControlToListenConfig(lc, bindControl(ifaceName))
|
||||||
|
|
||||||
return address, nil
|
return address, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
return network
|
||||||
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
//go:build !linux && !darwin
|
//go:build !linux && !darwin && !windows
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
@ -91,3 +91,13 @@ func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, add
|
|||||||
|
|
||||||
return addr.String(), nil
|
return addr.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
// fix bindIfaceToListenConfig() force bind to an ipv4 address
|
||||||
|
if !strings.HasSuffix(network, "4") &&
|
||||||
|
!strings.HasSuffix(network, "6") &&
|
||||||
|
addr.Unmap().Is6() {
|
||||||
|
network += "6"
|
||||||
|
}
|
||||||
|
return network
|
||||||
|
}
|
||||||
|
101
component/dialer/bind_windows.go
Normal file
101
component/dialer/bind_windows.go
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
IP_UNICAST_IF = 31
|
||||||
|
IPV6_UNICAST_IF = 31
|
||||||
|
)
|
||||||
|
|
||||||
|
func bind4(handle syscall.Handle, ifaceIdx int) error {
|
||||||
|
var bytes [4]byte
|
||||||
|
binary.BigEndian.PutUint32(bytes[:], uint32(ifaceIdx))
|
||||||
|
idx := *(*uint32)(unsafe.Pointer(&bytes[0]))
|
||||||
|
err := syscall.SetsockoptInt(handle, syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx))
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("bind4: %w", err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func bind6(handle syscall.Handle, ifaceIdx int) error {
|
||||||
|
err := syscall.SetsockoptInt(handle, syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, ifaceIdx)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("bind6: %w", err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindControl(ifaceIdx int) controlFn {
|
||||||
|
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||||
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var innerErr error
|
||||||
|
err = c.Control(func(fd uintptr) {
|
||||||
|
handle := syscall.Handle(fd)
|
||||||
|
bind6err := bind6(handle, ifaceIdx)
|
||||||
|
bind4err := bind4(handle, ifaceIdx)
|
||||||
|
switch network {
|
||||||
|
case "ip6", "tcp6":
|
||||||
|
innerErr = bind6err
|
||||||
|
case "ip4", "tcp4", "udp4":
|
||||||
|
innerErr = bind4err
|
||||||
|
case "udp6":
|
||||||
|
// golang will set network to udp6 when listenUDP on wildcard ip (eg: ":0", "")
|
||||||
|
if (!addrPort.Addr().IsValid() || addrPort.Addr().IsUnspecified()) && bind6err != nil {
|
||||||
|
// try bind ipv6, if failed, ignore. it's a workaround for windows disable interface ipv6
|
||||||
|
if bind4err != nil {
|
||||||
|
innerErr = fmt.Errorf("%w (%s)", bind6err, bind4err)
|
||||||
|
} else {
|
||||||
|
innerErr = nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
innerErr = bind6err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if innerErr != nil {
|
||||||
|
err = innerErr
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
||||||
|
return address, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
return network
|
||||||
|
}
|
22
component/dialer/control.go
Normal file
22
component/dialer/control.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
type controlFn = func(ctx context.Context, network, address string, c syscall.RawConn) error
|
||||||
|
|
||||||
|
func addControlToListenConfig(lc *net.ListenConfig, fn controlFn) {
|
||||||
|
llc := *lc
|
||||||
|
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
switch {
|
||||||
|
case llc.Control != nil:
|
||||||
|
if err = llc.Control(network, address, c); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fn(context.Background(), network, address, c)
|
||||||
|
}
|
||||||
|
}
|
22
component/dialer/control_go119.go
Normal file
22
component/dialer/control_go119.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
//go:build !go1.20
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
||||||
|
ld := *d
|
||||||
|
d.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
switch {
|
||||||
|
case ld.Control != nil:
|
||||||
|
if err = ld.Control(network, address, c); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fn(context.Background(), network, address, c)
|
||||||
|
}
|
||||||
|
}
|
26
component/dialer/control_go120.go
Normal file
26
component/dialer/control_go120.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
//go:build go1.20
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
||||||
|
ld := *d
|
||||||
|
d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
||||||
|
switch {
|
||||||
|
case ld.ControlContext != nil:
|
||||||
|
if err = ld.ControlContext(ctx, network, address, c); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case ld.Control != nil:
|
||||||
|
if err = ld.Control(network, address, c); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fn(ctx, network, address, c)
|
||||||
|
}
|
||||||
|
}
|
@ -2,40 +2,27 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"runtime"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
tcpConcurrent = false
|
tcpConcurrent = false
|
||||||
DisableIPv6 = false
|
fallbackTimeout = 300 * time.Millisecond
|
||||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
|
||||||
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
if runtime.GOOS == "windows" { // fix bindIfaceToListenConfig() in windows force bind to an ipv4 address
|
|
||||||
if !strings.HasSuffix(network, "4") &&
|
|
||||||
!strings.HasSuffix(network, "6") &&
|
|
||||||
addr.Unmap().Is6() {
|
|
||||||
network += "6"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return network
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyOptions(options ...Option) *option {
|
func applyOptions(options ...Option) *option {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
@ -66,29 +53,23 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
network = fmt.Sprintf("%s%d", network, opt.network)
|
network = fmt.Sprintf("%s%d", network, opt.network)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleDialContext(ctx, network, address, opt)
|
return actualSingleStackDialContext(ctx, network, ips, port, opt)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return actualDualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, ips, port, opt)
|
||||||
default:
|
default:
|
||||||
return nil, ErrorInvalidedNetworkStack
|
return nil, ErrorInvalidedNetworkStack
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||||
cfg := &option{
|
cfg := applyOptions(options...)
|
||||||
interfaceName: DefaultInterface.Load(),
|
|
||||||
routingMark: int(DefaultRoutingMark.Load()),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range DefaultOptions {
|
|
||||||
o(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range options {
|
|
||||||
o(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
lc := &net.ListenConfig{}
|
lc := &net.ListenConfig{}
|
||||||
if cfg.interfaceName != "" {
|
if cfg.interfaceName != "" {
|
||||||
@ -108,26 +89,40 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetDial(concurrent bool) {
|
func SetTcpConcurrent(concurrent bool) {
|
||||||
dialMux.Lock()
|
dialMux.Lock()
|
||||||
|
defer dialMux.Unlock()
|
||||||
tcpConcurrent = concurrent
|
tcpConcurrent = concurrent
|
||||||
if concurrent {
|
if concurrent {
|
||||||
actualSingleDialContext = concurrentSingleDialContext
|
actualSingleStackDialContext = concurrentSingleStackDialContext
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
} else {
|
} else {
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
}
|
}
|
||||||
|
|
||||||
dialMux.Unlock()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDial() bool {
|
func GetTcpConcurrent() bool {
|
||||||
|
dialMux.Lock()
|
||||||
|
defer dialMux.Unlock()
|
||||||
return tcpConcurrent
|
return tcpConcurrent
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
address := net.JoinHostPort(destination.String(), port)
|
||||||
|
|
||||||
|
netDialer := opt.netDialer
|
||||||
|
switch netDialer.(type) {
|
||||||
|
case nil:
|
||||||
|
netDialer = &net.Dialer{}
|
||||||
|
case *net.Dialer:
|
||||||
|
_netDialer := *netDialer.(*net.Dialer)
|
||||||
|
netDialer = &_netDialer // make a copy
|
||||||
|
default:
|
||||||
|
return netDialer.DialContext(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := netDialer.(*net.Dialer)
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -136,313 +131,182 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
if opt.routingMark != 0 {
|
if opt.routingMark != 0 {
|
||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
if opt.tfo {
|
||||||
if DisableIPv6 && destination.Is6() {
|
return dialTFO(ctx, *dialer, network, address)
|
||||||
return nil, ErrorDisableIPv6
|
|
||||||
}
|
}
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
return serialDialContext(ctx, network, ips, port, opt)
|
||||||
if err != nil {
|
}
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
func serialDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
return dualStackDialContext(ctx, serialDialContext, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
return parallelDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
if opt.prefer != 4 && opt.prefer != 6 {
|
||||||
|
return parallelDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
return dualStackDialContext(ctx, parallelDialContext, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
ipv4s, ipv6s := resolver.SortationAddr(ips)
|
||||||
|
preferIPVersion := opt.prefer
|
||||||
|
|
||||||
|
fallbackTicker := time.NewTicker(fallbackTimeout)
|
||||||
|
defer fallbackTicker.Stop()
|
||||||
|
results := make(chan dialResult)
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
|
racer := func(ips []netip.Addr, isPrimary bool) {
|
||||||
type dialResult struct {
|
result := dialResult{isPrimary: isPrimary}
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
resolved bool
|
|
||||||
ipv6 bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
results := make(chan dialResult)
|
|
||||||
var primary, fallback dialResult
|
|
||||||
|
|
||||||
startRacer := func(ctx context.Context, network, host string, r resolver.Resolver, ipv6 bool) {
|
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil {
|
if result.Conn != nil && result.error == nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
result.Conn, result.error = dialFn(ctx, network, ips, port, opt)
|
||||||
var ip netip.Addr
|
|
||||||
if ipv6 {
|
|
||||||
if r == nil {
|
|
||||||
ip, result.error = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv6WithResolver(ctx, host, r)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if r == nil {
|
|
||||||
ip, result.error = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv4WithResolver(ctx, host, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if result.error != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.resolved = true
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
}
|
||||||
|
go racer(ipv4s, preferIPVersion != 6)
|
||||||
go startRacer(ctx, network+"4", host, opt.resolver, false)
|
go racer(ipv6s, preferIPVersion != 4)
|
||||||
go startRacer(ctx, network+"6", host, opt.resolver, true)
|
var fallback dialResult
|
||||||
|
var errs []error
|
||||||
count := 2
|
for i := 0; i < 2; {
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
select {
|
select {
|
||||||
|
case <-fallbackTicker.C:
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
case res := <-results:
|
case res := <-results:
|
||||||
|
i++
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
return res.Conn, nil
|
if res.isPrimary {
|
||||||
}
|
return res.Conn, nil
|
||||||
|
}
|
||||||
if !res.ipv6 {
|
|
||||||
primary = res
|
|
||||||
} else {
|
|
||||||
fallback = res
|
fallback = res
|
||||||
}
|
} else {
|
||||||
|
if res.isPrimary {
|
||||||
if primary.done && fallback.done {
|
errs = append([]error{fmt.Errorf("connect failed: %w", res.error)}, errs...)
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
} else {
|
||||||
return nil, primary.error
|
errs = append(errs, fmt.Errorf("connect failed: %w", res.error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case <-ctx.Done():
|
|
||||||
err = ctx.Err()
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
if err == nil {
|
return fallback.Conn, nil
|
||||||
err = fmt.Errorf("dual stack dial failed")
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("dual stack dial failed:%w", err)
|
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, errorsJoin(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
if len(ips) == 0 {
|
||||||
if err != nil {
|
return nil, ErrorNoIpAddress
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
results := make(chan dialResult)
|
||||||
var ips []netip.Addr
|
|
||||||
if opt.resolver != nil {
|
|
||||||
ips, err = resolver.LookupIPWithResolver(ctx, host, opt.resolver)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
|
racer := func(ctx context.Context, ip netip.Addr) {
|
||||||
type dialResult struct {
|
result := dialResult{isPrimary: true, ip: ip}
|
||||||
ip netip.Addr
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
isPrimary bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
|
|
||||||
preferCount := atomic.NewInt32(0)
|
|
||||||
results := make(chan dialResult)
|
|
||||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
result := dialResult{ip: ip, done: true}
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil {
|
if result.Conn != nil && result.error == nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if strings.Contains(network, "tcp") {
|
|
||||||
network = "tcp"
|
|
||||||
} else {
|
|
||||||
network = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is6() {
|
|
||||||
network += "6"
|
|
||||||
if opt.prefer != 4 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is4() {
|
|
||||||
network += "4"
|
|
||||||
if opt.prefer != 6 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.isPrimary {
|
|
||||||
preferCount.Add(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
go tcpRacer(ctx, ip)
|
go racer(ctx, ip)
|
||||||
}
|
}
|
||||||
|
var errs []error
|
||||||
connCount := len(ips)
|
for i := 0; i < len(ips); i++ {
|
||||||
var fallback dialResult
|
res := <-results
|
||||||
var primaryError error
|
if res.error == nil {
|
||||||
var finalError error
|
return res.Conn, nil
|
||||||
for i := 0; i < connCount; i++ {
|
|
||||||
select {
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
if res.isPrimary {
|
|
||||||
return res.Conn, nil
|
|
||||||
} else {
|
|
||||||
if !fallback.done || fallback.error != nil {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if res.isPrimary {
|
|
||||||
primaryError = res.error
|
|
||||||
preferCount.Add(-1)
|
|
||||||
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case <-ctx.Done():
|
|
||||||
if fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
finalError = ctx.Err()
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
errs = append(errs, res.error)
|
||||||
}
|
}
|
||||||
|
|
||||||
if fallback.done && fallback.error == nil {
|
if len(errs) > 0 {
|
||||||
return fallback.Conn, nil
|
return nil, errorsJoin(errs...)
|
||||||
}
|
}
|
||||||
|
return nil, os.ErrDeadlineExceeded
|
||||||
if primaryError != nil {
|
|
||||||
return nil, primaryError
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallback.error != nil {
|
|
||||||
return nil, fallback.error
|
|
||||||
}
|
|
||||||
|
|
||||||
if finalError == nil {
|
|
||||||
finalError = fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
|
||||||
} else {
|
|
||||||
finalError = fmt.Errorf("concurrent dial failed:%w", finalError)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, finalError
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, ErrorNoIpAddress
|
||||||
|
}
|
||||||
|
var errs []error
|
||||||
|
for _, ip := range ips {
|
||||||
|
if conn, err := dialContext(ctx, network, ip, port, opt); err == nil {
|
||||||
|
return conn, nil
|
||||||
|
} else {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, errorsJoin(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type dialResult struct {
|
||||||
|
ip netip.Addr
|
||||||
|
net.Conn
|
||||||
|
error
|
||||||
|
isPrimary bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAddr(ctx context.Context, network, address string, preferResolver resolver.Resolver) ([]netip.Addr, string, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, "-1", err
|
||||||
}
|
|
||||||
|
|
||||||
var ip netip.Addr
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
return concurrentIPv4DialContext(ctx, network, address, opt)
|
|
||||||
default:
|
|
||||||
return concurrentIPv6DialContext(ctx, network, address, opt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
if opt.resolver == nil {
|
switch network {
|
||||||
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
case "tcp4", "udp4":
|
||||||
} else {
|
if preferResolver == nil {
|
||||||
ips, err = resolver.LookupIPv4WithResolver(ctx, host, opt.resolver)
|
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPv4WithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPv6WithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPWithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, "-1", fmt.Errorf("dns resolve failed: %w", err)
|
||||||
}
|
}
|
||||||
|
for i, ip := range ips {
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
if ip.Is4In6() {
|
||||||
}
|
ips[i] = ip.Unmap()
|
||||||
|
}
|
||||||
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
return ips, port, nil
|
||||||
var ips []netip.Addr
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPv6WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Dialer struct {
|
type Dialer struct {
|
||||||
@ -454,7 +318,12 @@ func (d Dialer) DialContext(ctx context.Context, network, address string) (net.C
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, WithOption(d.Opt))
|
opt := WithOption(d.Opt)
|
||||||
|
if rAddrPort.Addr().Unmap().IsLoopback() {
|
||||||
|
// avoid "The requested address is not valid in its context."
|
||||||
|
opt = WithInterface("")
|
||||||
|
}
|
||||||
|
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDialer(options ...Option) Dialer {
|
func NewDialer(options ...Option) Dialer {
|
||||||
|
18
component/dialer/error.go
Normal file
18
component/dialer/error.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrorNoIpAddress = errors.New("no ip address")
|
||||||
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
|
)
|
||||||
|
|
||||||
|
func errorsJoin(errs ...error) error {
|
||||||
|
// compatibility with golang<1.20
|
||||||
|
// maybe use errors.Join(errs...) is better after we drop the old version's support
|
||||||
|
return E.Errors(errs...)
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user