Compare commits
512 Commits
Author | SHA1 | Date | |
---|---|---|---|
7468d08e4d | |||
72ab200faf | |||
8df44a7c3d | |||
cdd91f5132 | |||
05f877a324 | |||
f565edd76d | |||
a3b8c9c233 | |||
de92bc0234 | |||
e6377eac9b | |||
22726c1de8 | |||
bce3aeb218 | |||
81722610d5 | |||
5bfad04b41 | |||
880664c6ab | |||
8f0c61ed14 | |||
7d524668e0 | |||
75680c5866 | |||
a1d008e6f0 | |||
d5d62a4ffd | |||
b72bd5bb37 | |||
7fecd20a1d | |||
f586f22ce3 | |||
21848d6bf1 | |||
28c57c4144 | |||
4a6ebff473 | |||
5c8d955f61 | |||
baaf509637 | |||
db3e1b9ed5 | |||
1a1e3345f4 | |||
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 | |||
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 | |||
633b9c0426 | |||
7d6991dd65 | |||
95247154d6 | |||
be6142aa43 | |||
0069513780 | |||
0c9a23a53c | |||
0035fc2313 | |||
6f62d4d5c1 | |||
51f9b34a7c | |||
337be9124f | |||
dd4e4d7559 | |||
0f29c267be | |||
d38ceb78c9 | |||
0c354c748a | |||
3a8e7c8899 | |||
261b8a1d06 | |||
01d8b224db | |||
e9a7e104c0 | |||
b4503908df | |||
fd48c6df8a | |||
cd7134e309 | |||
5fa6777239 | |||
908d0b0007 | |||
8e6989758e | |||
29b72df14c | |||
f100a33d98 | |||
7a64c432b1 | |||
2301b909d2 | |||
89680de12b | |||
a03af85a6b | |||
fbca37c42b | |||
4a57917783 | |||
cdc7d449a6 | |||
daf0b23805 | |||
d8ac82be36 | |||
a6c144038b | |||
980454beb2 | |||
63922f86a2 | |||
22414ce399 | |||
7496d9c114 | |||
c63dd62ed2 | |||
ff01d845b4 | |||
57592ee840 | |||
432c4c2cf1 | |||
98b7377643 | |||
287ec7e851 | |||
8a2d1ec5a7 | |||
afb2364ca2 | |||
9711390c18 | |||
bffb0573a6 | |||
17cbbb5bf0 | |||
b3b5f17e03 | |||
88acf8e098 | |||
f87144f84b | |||
1333f1fd47 | |||
8fa6bd1743 | |||
02d3468516 | |||
f657ac97f6 | |||
57dfaf135d | |||
9df42d7b98 | |||
b5928c36a3 | |||
910e7fed97 | |||
a9839abd4c | |||
78c7b6259c | |||
a6f7e1472b | |||
e03fcd24dd | |||
cd99b2e795 | |||
b5b06ea49c | |||
f7fb5840cf | |||
3b96d54369 | |||
f390b9cf2f | |||
1c65a2c1b4 | |||
2d2b75a4bf | |||
dcbe25c3ae | |||
46d23d9b86 | |||
fd9c4cbfa5 | |||
5c410b8df4 | |||
8c58d8a8ad | |||
a0a2eb2106 | |||
b7d976796a | |||
2e22c712af | |||
c7f83d3ff1 | |||
62474e0ed6 | |||
62226e8b3d | |||
8144373725 | |||
e9d8dd09ac | |||
6fc62da7ae | |||
4f75201a98 | |||
ba884c29bd | |||
2fe271f19f | |||
cf5709aab1 | |||
654cdf3d5b | |||
6c79d9e63b | |||
0aefa3be85 | |||
bc5ab3120f | |||
df8e129fc6 | |||
84caee94af | |||
1d9e320087 | |||
2a3c4c1a33 | |||
8c0fbb3665 | |||
9ea09b2b94 | |||
db81db5363 | |||
e715ccbdd5 | |||
bc94c50783 | |||
b4b9ef2362 | |||
dd6f7e3701 | |||
01e382285d | |||
4b1d4a3e20 | |||
562819e3ca | |||
551283c16e | |||
cd53e2d4a7 | |||
a58234f0cd | |||
c8d7243b5b | |||
6b1ca7b07c | |||
b80e7c3c92 | |||
0da09c5ddd | |||
17c081a40c | |||
0647cee02a | |||
423850a7aa | |||
896d30b151 | |||
495fd191f2 | |||
ae76daf393 | |||
8056b5573b | |||
516623cbbb | |||
a5ae2e891c | |||
90b40a8e5a | |||
7f40645934 | |||
6c204d2b77 | |||
ed988dcdc5 | |||
7b44cde4bd | |||
c7bad89af3 | |||
21a91e88a1 | |||
76d2838721 | |||
9b1fe9f466 | |||
9976800a35 | |||
f542351404 | |||
a13dedb6e4 | |||
d47ce79a24 | |||
cce42b4b83 | |||
142d17ebad | |||
30ca59dab7 | |||
c89b1f0e96 | |||
59bd11a3a7 | |||
3880c3c1be | |||
efa4b9e0b8 | |||
8c6e205c5a | |||
d478728cb7 | |||
5b07d7b776 | |||
18d62c4a17 | |||
02830e0ad6 | |||
6d89bddf29 | |||
dbbd499349 | |||
d3562ce394 | |||
d5973cf8a6 | |||
1d3cc36eef | |||
8fcfecbed1 | |||
7c1b878c3f | |||
4ea4221380 | |||
b8b3c9ef9f | |||
f00dc69bb6 | |||
23f286f24e | |||
16f8f77f5d | |||
dfc0ec995c | |||
8b848b62bb | |||
2dc62024fe | |||
994e85425f | |||
1880a485f8 | |||
03645fb235 | |||
eb8431255d | |||
e5a81b6c35 | |||
0eecd11fdc | |||
9c8e39827f | |||
586dec5ba3 | |||
6db7c800d5 | |||
2a8e1778ad | |||
a3425c0e78 | |||
7300c917dc | |||
dc3e144b6a | |||
75d339392b | |||
901a47318d | |||
dbadf37823 | |||
3321ac95ca | |||
c0bd4af120 | |||
d78b2b1cfb | |||
3e20912339 | |||
b2d7149a95 | |||
64be213b66 | |||
68b28ed530 | |||
3eacce9a66 | |||
6dadc2357a | |||
698d8ca701 | |||
1a4b00c70e | |||
64552fbd00 | |||
7c8d8f56e1 | |||
93ada8989f | |||
4b4c3dc41e | |||
b699fb046b | |||
ae08d13de4 | |||
1d784231b0 | |||
5fd79890e7 | |||
53b2a480ef | |||
943137de3b | |||
2d3aad573e | |||
409cd4f6a1 | |||
bd526ad0a1 | |||
4673d2093a | |||
94a765ee31 | |||
dcd2417fce | |||
4c5853e5e7 | |||
52f4cb599a | |||
90f6cc233c | |||
de264c42a8 | |||
c2469162fb | |||
19b7c7f52a | |||
e20d01a679 | |||
9a5c0a4b6d | |||
1b0d09068b | |||
3373b62b02 | |||
508e257543 | |||
7b0cd14b00 | |||
22fb219ad8 | |||
c34c5ff1f9 | |||
4e5bdec13a | |||
fbd43d9947 | |||
5dab89c9ec | |||
2a24effac0 | |||
972d3f1d39 | |||
a7aa5fd523 | |||
b9d8b69889 | |||
dedb9122df | |||
0e5bf0c27e | |||
a46436f61a | |||
6106adc6a5 | |||
c8bc11d61d | |||
f29b54898f | |||
fc693bc257 | |||
bba5c2cc8a | |||
0fb0e490f8 | |||
023e3d0c41 | |||
c11a359761 | |||
0da49bd92b | |||
b9ef713dd7 | |||
4948f3f213 | |||
7b1427b843 | |||
77a3c1c3ae | |||
2c236387b7 | |||
66e5136ba0 | |||
f748e3632d | |||
90688b238a | |||
986c91b5c8 | |||
8c13426492 | |||
fefd9b7427 | |||
8a55208c62 | |||
1f8b54a92d | |||
8d74a86bf1 | |||
6c82e98bbc | |||
94246104b8 | |||
347e5e9606 | |||
e4138c3e1e | |||
f2b5ae6894 | |||
0a89107b8b | |||
2a323f77ce | |||
59edcf33bd | |||
35506e179a | |||
6ce3805719 | |||
c1a82f2fae | |||
4f9478a336 | |||
e1dc2681f1 | |||
ce77c3fd8b | |||
9f1194056a | |||
b82c9ba190 | |||
6857b05039 | |||
abbbcb02c0 | |||
ec6144250d | |||
89d1222b8f | |||
de4985a9b6 | |||
6dd8cf6c0a | |||
6b2eae36f2 | |||
13445d815b | |||
e2d71abecd | |||
ddf1c74091 | |||
1bcc916807 | |||
c06b48af0e | |||
7e9549c05a | |||
3e2b08f9d0 | |||
fb85691fb9 | |||
1684756b79 | |||
88e4a9a755 | |||
d411394482 | |||
827d5289bc | |||
b133bc58f0 | |||
82c9a1a2bb | |||
e1ec4a2502 | |||
b6dc539105 | |||
6e8d8befb8 | |||
6995e98181 | |||
4597ed49cf | |||
ef2f8317c7 | |||
9b89ff9f2d | |||
4f291fa513 | |||
22b9befbda | |||
a9694fcdc0 | |||
425b6e0dc0 | |||
2516169f61 | |||
a3281712e2 | |||
bf079742cb | |||
98f4f4d6c4 | |||
6e058f8581 | |||
3946d771e5 | |||
5940f62794 | |||
71cad51e8f | |||
50105f0559 | |||
6648793e40 | |||
95e3a88608 | |||
bec4df7b12 | |||
93400cf44d | |||
a794819869 | |||
be8d63ba8f | |||
3b90e18047 | |||
f0952b55d0 | |||
8c7c8f4374 | |||
65a8e8f59c | |||
5497adaba1 | |||
aaf08dadff | |||
557297ac9a | |||
77a1e3a653 | |||
27e1d6cdae | |||
91c22b16bf | |||
fc5c9b931b | |||
c231fd1466 | |||
fbb27b84d1 | |||
e0c5a85314 | |||
2fa1a5c4b9 | |||
06d75da257 | |||
09d49bac95 | |||
3360839fe3 | |||
c1285adbf8 | |||
9d2fc976e2 | |||
7f41f94fff | |||
d1f0dac302 | |||
afb3e00067 | |||
9a31ad6151 | |||
09cc6b69e3 | |||
8603ac40a1 | |||
b384449717 | |||
da7ffc0da9 | |||
5dd94c8298 | |||
412b44a981 | |||
aef4dd3fe7 | |||
6a92c6af4e | |||
e010940b61 | |||
2c9a4d276a | |||
4dfba73e5c | |||
c282d662ca | |||
b3d7594813 |
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
|
26
.github/rename-cgo.sh
vendored
Normal file
26
.github/rename-cgo.sh
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
#!/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 =~ "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
|
20
.github/workflows/build.yaml
vendored
20
.github/workflows/build.yaml
vendored
@ -1,20 +0,0 @@
|
|||||||
name: Build All
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.18
|
|
||||||
- name: Check out code
|
|
||||||
uses: actions/checkout@v1
|
|
||||||
- name: Build
|
|
||||||
run: make all
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
325
.github/workflows/build.yml
vendored
Normal file
325
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
name: Build
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
- Meta
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request_target:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
- Meta
|
||||||
|
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: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
|
id: "5",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
|
id: "6",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-arm64 windows-arm32v7",
|
||||||
|
id: "7",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
|
id: "8",
|
||||||
|
}
|
||||||
|
- { 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: |
|
||||||
|
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 -u)" >> $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@v3
|
||||||
|
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 ..
|
||||||
|
|
||||||
|
- 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: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- 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 Prerelease
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref_name }}
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
||||||
|
|
||||||
|
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: ${{ github.ref_name }}
|
||||||
|
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@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: Show files
|
||||||
|
run: |
|
||||||
|
ls .
|
||||||
|
ls bin/
|
||||||
|
- 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/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 }}
|
|
70
.github/workflows/prerelease.yml
vendored
70
.github/workflows/prerelease.yml
vendored
@ -1,70 +0,0 @@
|
|||||||
name: Prerelease
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
|
|
||||||
- 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: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1
|
|
||||||
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: ${{ github.ref_name }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
44
.github/workflows/release.yaml
vendored
44
.github/workflows/release.yaml
vendored
@ -1,44 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
- 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/
|
@ -8,9 +8,10 @@ linters:
|
|||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
gci:
|
gci:
|
||||||
|
custom-order: true
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/Dreamacro/clash)
|
- prefix(github.com/Dreamacro/clash)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.18'
|
go: '1.19'
|
||||||
|
21
Dockerfile
21
Dockerfile
@ -1,26 +1,25 @@
|
|||||||
FROM golang:alpine as builder
|
FROM alpine:latest as builder
|
||||||
|
|
||||||
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` && \
|
||||||
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"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata
|
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" ]
|
15
Makefile
15
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)
|
||||||
@ -12,7 +12,7 @@ VERSION=$(shell git rev-parse --short HEAD)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
@ -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)-$@
|
||||||
@ -117,7 +120,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
|
||||||
|
134
README.md
134
README.md
@ -29,12 +29,42 @@
|
|||||||
- 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).
|
|
||||||
|
|
||||||
## Advanced usage for this branch
|
Documentation and configuring examples are available on [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki) and [Clash.Meta Wiki](https://docs.metacubex.one/).
|
||||||
|
|
||||||
### DNS configuration
|
## Build
|
||||||
|
|
||||||
|
You should install [golang](https://go.dev) first.
|
||||||
|
|
||||||
|
Then get the source code of Clash.Meta:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||||
|
cd Clash.Meta && go mod download
|
||||||
|
```
|
||||||
|
|
||||||
|
If you can't visit github,you should set proxy first:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
|
```
|
||||||
|
|
||||||
|
Now you can build it:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go build
|
||||||
|
```
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
@ -44,7 +74,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:
|
||||||
@ -53,6 +82,7 @@ proxy-groups:
|
|||||||
interval: 180
|
interval: 180
|
||||||
lazy: true
|
lazy: true
|
||||||
```
|
```
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
@ -68,8 +98,8 @@ 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:
|
||||||
@ -90,21 +120,23 @@ 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
|
||||||
@ -133,7 +165,6 @@ rules:
|
|||||||
- 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)
|
||||||
@ -142,18 +173,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:
|
||||||
@ -165,14 +195,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"
|
||||||
@ -212,8 +240,46 @@ proxies:
|
|||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Support outbound transport protocol `Wireguard`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "wg"
|
||||||
|
type: wireguard
|
||||||
|
server: 162.159.192.1
|
||||||
|
port: 2480
|
||||||
|
ip: 172.16.0.2
|
||||||
|
ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
||||||
|
private-key: eCtXsJZ27+4PbhDkHnB923tkUn2Gj59wZw5wFA75MnU=
|
||||||
|
public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
||||||
|
udp: true
|
||||||
|
```
|
||||||
|
|
||||||
|
Support outbound transport protocol `Tuic`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
- name: "tuic"
|
||||||
|
server: www.example.com
|
||||||
|
port: 10443
|
||||||
|
type: tuic
|
||||||
|
token: TOKEN
|
||||||
|
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
||||||
|
# heartbeat-interval: 10000
|
||||||
|
# alpn: [h3]
|
||||||
|
# disable-sni: true
|
||||||
|
reduce-rtt: true
|
||||||
|
# request-timeout: 8000
|
||||||
|
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
||||||
|
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
||||||
|
# max-udp-relay-packet-size: 1500
|
||||||
|
# fast-open: 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
|
||||||
@ -224,17 +290,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`
|
|
||||||
|
|
||||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
- Create user given name `clash-meta`
|
||||||
|
|
||||||
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
+ 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.
|
||||||
|
|
||||||
@ -260,10 +324,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
|
||||||
@ -274,22 +341,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)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -92,6 +92,8 @@ 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()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -198,7 +200,6 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
Host: u.Hostname(),
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
|
29
adapter/inbound/addition.go
Normal file
29
adapter/inbound/addition.go
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Addition func(metadata *C.Metadata)
|
||||||
|
|
||||||
|
func (a Addition) Apply(metadata *C.Metadata) {
|
||||||
|
a(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInName(name string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.InName = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSpecialRules(specialRules string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.SpecialRules = specialRules
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSpecialProxy(specialProxy string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.SpecialProxy = specialProxy
|
||||||
|
}
|
||||||
|
}
|
@ -9,13 +9,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
for _, addition := range additions {
|
||||||
|
addition.Apply(metadata)
|
||||||
|
}
|
||||||
|
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()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -9,12 +9,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPS
|
metadata.Type = C.HTTPS
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
for _, addition := range additions {
|
||||||
|
addition.Apply(metadata)
|
||||||
|
}
|
||||||
|
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()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
26
adapter/inbound/listen.go
Normal file
26
adapter/inbound/listen.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/tfo-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
lc = tfo.ListenConfig{
|
||||||
|
DisableTFO: true,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetTfo(open bool) {
|
||||||
|
lc.DisableTFO = !open
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||||
|
return lc.Listen(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Listen(network, address string) (net.Listener, error) {
|
||||||
|
return ListenContext(context.Background(), network, address)
|
||||||
|
}
|
@ -17,17 +17,26 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) C.PacketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
for _, addition := range additions {
|
||||||
|
addition.Apply(metadata)
|
||||||
|
}
|
||||||
|
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 ip, port, err := parseAddr(p.InAddr()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &PacketAdapter{
|
return &PacketAdapter{
|
||||||
UDPPacket: packet,
|
packet,
|
||||||
metadata: metadata,
|
metadata,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,17 +10,21 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
remoteAddr := conn.RemoteAddr()
|
for _, addition := range additions {
|
||||||
// Filter when net.Addr interface is nil
|
addition.Apply(metadata)
|
||||||
if remoteAddr != nil {
|
}
|
||||||
if ip, port, err := parseAddr(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()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
@ -30,19 +34,14 @@ func NewInner(conn net.Conn, dst string, host 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.Host = host
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
metadata.DstPort = port
|
metadata.DstPort = port
|
||||||
if host == "" {
|
if host == "" {
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
if ip.Is6() {
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,21 +1,20 @@
|
|||||||
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
AddrType: int(target[0]),
|
|
||||||
}
|
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -46,7 +45,6 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
@ -54,20 +52,25 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
switch {
|
|
||||||
case ip.Is6():
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
default:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,14 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
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/gofrs/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
@ -18,6 +20,8 @@ type Base struct {
|
|||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
|
xudp bool
|
||||||
|
tfo bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
prefer C.DNSPrefer
|
prefer C.DNSPrefer
|
||||||
@ -56,16 +60,26 @@ func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
// 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, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketOnStreamConn(c net.Conn, 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, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportWithDialer() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
func (b *Base) SupportUOT() bool {
|
func (b *Base) SupportUOT() bool {
|
||||||
return false
|
return false
|
||||||
@ -76,6 +90,16 @@ 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
|
||||||
|
func (b *Base) SupportTFO() bool {
|
||||||
|
return b.tfo
|
||||||
|
}
|
||||||
|
|
||||||
// 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{
|
||||||
@ -90,7 +114,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,10 +140,15 @@ 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"`
|
||||||
@ -130,6 +159,8 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
|
XUDP bool
|
||||||
|
TFO bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
Prefer C.DNSPrefer
|
Prefer C.DNSPrefer
|
||||||
@ -141,6 +172,8 @@ 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,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
prefer: opt.Prefer,
|
prefer: opt.Prefer,
|
||||||
@ -148,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
|
||||||
}
|
}
|
||||||
@ -167,8 +200,12 @@ 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 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())}
|
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -14,7 +15,7 @@ type Direct struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -25,8 +26,8 @@ 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.WithDirect())
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", 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
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -15,6 +14,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -44,7 +44,9 @@ type HttpOption struct {
|
|||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConn(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)
|
||||||
err := cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
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)
|
||||||
@ -59,13 +61,20 @@ func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
|
return h.DialContextWithDialer(ctx, dialer.NewDialer(h.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -75,6 +84,11 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
return NewConn(c, h), nil
|
return NewConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (h *Http) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
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{
|
req := &http.Request{
|
||||||
@ -136,7 +150,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,
|
||||||
})
|
})
|
||||||
@ -156,6 +170,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),
|
||||||
|
@ -4,39 +4,41 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/core"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
|
||||||
"github.com/lucas-clemente/quic-go"
|
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
"github.com/metacubex/quic-go/congestion"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
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"
|
||||||
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
"github.com/lucas-clemente/quic-go/congestion"
|
"github.com/Dreamacro/clash/transport/hysteria/core"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
mbpsToBps = 125000
|
mbpsToBps = 125000
|
||||||
minSpeedBPS = 16384
|
|
||||||
|
|
||||||
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||||
DefaultMaxIncomingStreams = 1024
|
|
||||||
|
|
||||||
DefaultALPN = "hysteria"
|
DefaultALPN = "hysteria"
|
||||||
DefaultProtocol = "udp"
|
DefaultProtocol = "udp"
|
||||||
|
DefaultHopInterval = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
@ -50,11 +52,11 @@ type Hysteria struct {
|
|||||||
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{
|
hdc := hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func() (net.PacketConn, error) {
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,11 +71,11 @@ 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{
|
hdc := hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func() (net.PacketConn, error) {
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
udpConn, err := h.client.DialUDP(&hdc)
|
udpConn, err := h.client.DialUDP(&hdc)
|
||||||
@ -87,21 +89,28 @@ type HysteriaOption struct {
|
|||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port,omitempty"`
|
||||||
|
Ports string `proxy:"ports,omitempty"`
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
||||||
Up string `proxy:"up"`
|
Up string `proxy:"up"`
|
||||||
|
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
||||||
Down string `proxy:"down"`
|
Down string `proxy:"down"`
|
||||||
AuthString string `proxy:"auth_str,omitempty"`
|
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
||||||
|
Auth string `proxy:"auth,omitempty"`
|
||||||
|
AuthString string `proxy:"auth-str,omitempty"`
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
Obfs string `proxy:"obfs,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"`
|
||||||
ALPN string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,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"`
|
||||||
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
|
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
@ -125,8 +134,9 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
Timeout: 8 * time.Second,
|
Timeout: 8 * time.Second,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
ports := option.Ports
|
||||||
|
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
serverName = option.SNI
|
serverName = option.SNI
|
||||||
@ -168,15 +178,14 @@ 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 {
|
||||||
tlsConfig.NextProtos = []string{option.ALPN}
|
tlsConfig.NextProtos = option.ALPN
|
||||||
} else {
|
} else {
|
||||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
}
|
}
|
||||||
|
|
||||||
quicConfig := &quic.Config{
|
quicConfig := &quic.Config{
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
@ -186,10 +195,17 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
|
if option.ObfsProtocol != "" {
|
||||||
|
option.Protocol = option.ObfsProtocol
|
||||||
|
}
|
||||||
if option.Protocol == "" {
|
if option.Protocol == "" {
|
||||||
option.Protocol = DefaultProtocol
|
option.Protocol = DefaultProtocol
|
||||||
}
|
}
|
||||||
if option.ReceiveWindowConn == 0 {
|
if option.HopInterval == 0 {
|
||||||
|
option.HopInterval = DefaultHopInterval
|
||||||
|
}
|
||||||
|
hopInterval := time.Duration(int64(option.HopInterval)) * time.Second
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
||||||
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||||
}
|
}
|
||||||
@ -202,6 +218,12 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var auth = []byte(option.AuthString)
|
var auth = []byte(option.AuthString)
|
||||||
|
if option.Auth != "" {
|
||||||
|
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
var obfuscator obfs.Obfuscator
|
var obfuscator obfs.Obfuscator
|
||||||
if len(option.Obfs) > 0 {
|
if len(option.Obfs) > 0 {
|
||||||
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||||
@ -211,11 +233,16 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if option.UpSpeed != 0 {
|
||||||
|
up = uint64(option.UpSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
|
if option.DownSpeed != 0 {
|
||||||
|
down = uint64(option.DownSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
client, err := core.NewClient(
|
client, err := core.NewClient(
|
||||||
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
addr, ports, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
}, obfuscator,
|
}, obfuscator, hopInterval, option.FastOpen,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
@ -226,6 +253,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Hysteria,
|
tp: C.Hysteria,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
tfo: option.FastOpen,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -294,13 +322,17 @@ func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type hyDialerWithContext struct {
|
type hyDialerWithContext struct {
|
||||||
hyDialer func() (net.PacketConn, error)
|
hyDialer func(network string) (net.PacketConn, error)
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
remoteAddr func(host string) (net.Addr, error)
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
|
func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, error) {
|
||||||
return h.hyDialer()
|
network := "udp"
|
||||||
|
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
||||||
|
network = dialer.ParseNetwork(network, addrPort.Addr())
|
||||||
|
}
|
||||||
|
return h.hyDialer(network)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hyDialerWithContext) Context() context.Context {
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
@ -53,6 +53,9 @@ func (rw *nopConn) Read(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (rw *nopConn) Write(b []byte) (int, error) {
|
func (rw *nopConn) Write(b []byte) (int, error) {
|
||||||
|
if len(b) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,25 +7,21 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
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"
|
||||||
|
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
"github.com/sagernet/sing-shadowsocks"
|
|
||||||
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/common/uot"
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
|
||||||
buf.DefaultAllocator = pool.DefaultAllocator
|
|
||||||
}
|
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
method shadowsocks.Method
|
method shadowsocks.Method
|
||||||
@ -35,6 +31,7 @@ type ShadowSocks struct {
|
|||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
@ -66,8 +63,32 @@ type v2rayObfsOption struct {
|
|||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type shadowTLSOption struct {
|
||||||
|
Password string `obfs:"password"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
ClientFingerprint string `obfs:"client-fingerprint,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Version int `obfs:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
switch ss.obfsMode {
|
||||||
|
case shadowtls.Mode:
|
||||||
|
// fix tls handshake not timeout
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var err error
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ss.streamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) streamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -82,49 +103,72 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
metadata.Host = uot.UOTMagicAddress
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443")), nil
|
||||||
metadata.DstPort = "443"
|
|
||||||
}
|
}
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
switch ss.obfsMode {
|
||||||
|
case shadowtls.Mode:
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = ss.streamConn(c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
return ss.ListenPacketWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContext(ctx, metadata, opts...)
|
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 newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
||||||
}
|
}
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddrWithPrefer("udp", ss.addr, ss.prefer)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// 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(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
@ -147,6 +191,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
|
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -182,6 +227,23 @@ 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: opt.ClientFingerprint,
|
||||||
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
|
Version: opt.Version,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -190,6 +252,7 @@ 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),
|
||||||
@ -200,6 +263,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
shadowTLSOption: shadowTLSOpt,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -60,13 +60,20 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
return ssr.DialContextWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
@ -74,14 +81,18 @@ func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
|
return ssr.ListenPacketWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddrWithPrefer("udp", ssr.addr, ssr.prefer)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,6 +101,11 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
// SSR protocol compatibility
|
// SSR protocol compatibility
|
||||||
// https://github.com/Dreamacro/clash/pull/2056
|
// https://github.com/Dreamacro/clash/pull/2056
|
||||||
@ -147,6 +163,7 @@ 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),
|
||||||
|
@ -78,13 +78,20 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
return s.DialContextWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConn(c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
@ -92,7 +99,12 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
return s.ListenPacketWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -108,10 +120,9 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return newPacketConn(pc, s), nil
|
return newPacketConn(pc, s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (s *Snell) SupportWithDialer() bool {
|
||||||
pc := snell.PacketConn(c)
|
return true
|
||||||
return newPacketConn(pc, s), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -156,6 +167,7 @@ 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),
|
||||||
|
@ -5,12 +5,12 @@ 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"
|
||||||
|
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"
|
||||||
)
|
)
|
||||||
@ -41,7 +41,9 @@ type Socks5Option struct {
|
|||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(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)
|
||||||
err := cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
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)
|
||||||
@ -63,13 +65,20 @@ func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -79,6 +88,11 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
return NewConn(c, ss), nil
|
return NewConn(c, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// 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...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
@ -89,11 +103,15 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err = cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err = cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
@ -110,7 +128,21 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
// Support unspecified UDP bind address.
|
||||||
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr(ctx, "udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", bindUDPAddr.AddrPort().Addr()), "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -123,20 +155,6 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc.Close()
|
pc.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
err = errors.New("invalid UDP bind address")
|
|
||||||
return
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -149,7 +167,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 {
|
||||||
@ -164,6 +182,7 @@ 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),
|
||||||
|
@ -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"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
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"
|
||||||
@ -43,6 +44,7 @@ type TrojanOption struct {
|
|||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,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(c net.Conn) (net.Conn, error) {
|
||||||
@ -75,6 +77,11 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (t *Trojan) StreamConn(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)
|
||||||
} else {
|
} else {
|
||||||
@ -95,7 +102,7 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return N.NewExtendedConn(c), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -120,14 +127,20 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
return NewConn(c, t), nil
|
return NewConn(c, t), nil
|
||||||
}
|
}
|
||||||
|
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
c, err = t.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -147,19 +160,34 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
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)
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
} else {
|
safeConnClose(c, err)
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
}(c)
|
||||||
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(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)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -170,6 +198,11 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return newPacketConn(pc, t), err
|
return newPacketConn(pc, t), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
pc := t.instance.PacketConn(c)
|
pc := t.instance.PacketConn(c)
|
||||||
@ -191,9 +224,12 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
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 {
|
||||||
|
case "", "tcp":
|
||||||
|
if len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
switch option.Flow {
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
@ -202,6 +238,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
tOption.ServerName = option.SNI
|
tOption.ServerName = option.SNI
|
||||||
@ -213,6 +250,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),
|
||||||
@ -239,7 +277,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 {
|
||||||
@ -247,11 +285,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint)
|
||||||
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{
|
||||||
|
251
adapter/outbound/tuic.go
Normal file
251
adapter/outbound/tuic.go
Normal file
@ -0,0 +1,251 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/tuic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Tuic struct {
|
||||||
|
*Base
|
||||||
|
client *tuic.PoolClient
|
||||||
|
}
|
||||||
|
|
||||||
|
type TuicOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Token string `proxy:"token"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
ReduceRtt bool `proxy:"reduce-rtt,omitempty"`
|
||||||
|
RequestTimeout int `proxy:"request-timeout,omitempty"`
|
||||||
|
UdpRelayMode string `proxy:"udp-relay-mode,omitempty"`
|
||||||
|
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||||
|
DisableSni bool `proxy:"disable-sni,omitempty"`
|
||||||
|
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
||||||
|
|
||||||
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
|
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
conn, err := t.client.DialContextWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(conn, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc, err := t.client.ListenPacketWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(pc, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
|
return t.dialWithDialer(ctx, dialer.NewDialer(opts...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
addr = udpAddr
|
||||||
|
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
serverName := option.Server
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
}
|
||||||
|
if option.SNI != "" {
|
||||||
|
tlsConfig.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
|
var err error
|
||||||
|
if len(option.CustomCA) > 0 {
|
||||||
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("tuic %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.ALPN) > 0 {
|
||||||
|
tlsConfig.NextProtos = option.ALPN
|
||||||
|
} else {
|
||||||
|
tlsConfig.NextProtos = []string{"h3"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.RequestTimeout == 0 {
|
||||||
|
option.RequestTimeout = 8000
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.HeartbeatInterval <= 0 {
|
||||||
|
option.HeartbeatInterval = 10000
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.UdpRelayMode != "quic" {
|
||||||
|
option.UdpRelayMode = "native"
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
|
option.MaxUdpRelayPacketSize = 1252
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxOpenStreams == 0 {
|
||||||
|
option.MaxOpenStreams = 100
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||||
|
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
|
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
||||||
|
quicConfig := &quic.Config{
|
||||||
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxIncomingStreams: quicMaxOpenStreams,
|
||||||
|
MaxIncomingUniStreams: quicMaxOpenStreams,
|
||||||
|
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
||||||
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
EnableDatagrams: true,
|
||||||
|
}
|
||||||
|
if option.ReceiveWindowConn == 0 {
|
||||||
|
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
|
||||||
|
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
|
||||||
|
}
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
|
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
|
||||||
|
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
||||||
|
}
|
||||||
|
host := option.Server
|
||||||
|
if option.DisableSni {
|
||||||
|
host = ""
|
||||||
|
tlsConfig.ServerName = ""
|
||||||
|
}
|
||||||
|
tkn := tuic.GenTKN(option.Token)
|
||||||
|
|
||||||
|
t := &Tuic{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Tuic,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.FastOpen,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
clientMaxOpenStreams = 1
|
||||||
|
}
|
||||||
|
clientOption := &tuic.ClientOption{
|
||||||
|
TlsConfig: tlsConfig,
|
||||||
|
QuicConfig: quicConfig,
|
||||||
|
Host: host,
|
||||||
|
Token: tkn,
|
||||||
|
UdpRelayMode: option.UdpRelayMode,
|
||||||
|
CongestionController: option.CongestionController,
|
||||||
|
ReduceRtt: option.ReduceRtt,
|
||||||
|
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||||
|
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||||
|
FastOpen: option.FastOpen,
|
||||||
|
MaxOpenStreams: clientMaxOpenStreams,
|
||||||
|
}
|
||||||
|
|
||||||
|
t.client = tuic.NewPoolClient(clientOption)
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
@ -2,6 +2,7 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
xtls "github.com/xtls/go"
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
@ -44,10 +45,11 @@ func getClientXSessionCache() xtls.ClientSessionCache {
|
|||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
aType := uint8(metadata.AddrType)
|
addrType := metadata.AddrType()
|
||||||
|
aType := uint8(addrType)
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch metadata.AddrType {
|
switch addrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
lenM := uint8(len(metadata.Host))
|
lenM := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
@ -62,34 +64,34 @@ func serializesSocksAddr(metadata *C.Metadata) []byte {
|
|||||||
return bytes.Join(buf, nil)
|
return bytes.Join(buf, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
func resolveUDPAddr(ctx context.Context, network, address string) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveProxyServerHost(host)
|
ip, err := resolver.ResolveProxyServerHost(ctx, host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var ip netip.Addr
|
var ip netip.Addr
|
||||||
|
var fallback netip.Addr
|
||||||
switch prefer {
|
switch prefer {
|
||||||
case C.IPv4Only:
|
case C.IPv4Only:
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
||||||
case C.IPv6Only:
|
case C.IPv6Only:
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
||||||
case C.IPv6Prefer:
|
case C.IPv6Prefer:
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
var fallback netip.Addr
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is6() {
|
if addr.Is6() {
|
||||||
@ -101,13 +103,11 @@ func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ip = fallback
|
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
// C.IPv4Prefer, C.DualStack and other
|
// C.IPv4Prefer, C.DualStack and other
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
var fallback netip.Addr
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is4() {
|
if addr.Is4() {
|
||||||
@ -120,11 +120,12 @@ func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !ip.IsValid() && fallback.IsValid() {
|
if !ip.IsValid() && fallback.IsValid() {
|
||||||
ip = fallback
|
ip = fallback
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -133,7 +134,7 @@ func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net
|
|||||||
}
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil {
|
if err != nil && c != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,20 +6,25 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"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"
|
||||||
|
"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 (
|
||||||
@ -48,6 +53,9 @@ type VlessOption struct {
|
|||||||
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"`
|
||||||
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
@ -58,10 +66,16 @@ type VlessOption struct {
|
|||||||
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"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConn(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":
|
||||||
|
|
||||||
@ -72,6 +86,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{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,9 +105,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 != "" {
|
||||||
@ -136,11 +154,7 @@ 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.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
} else {
|
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
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
|
||||||
@ -151,21 +165,17 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
return v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamTLSOrXTLSConn(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 != "" {
|
||||||
@ -179,6 +189,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -195,8 +206,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
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
|
||||||
@ -207,32 +218,43 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(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
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
|
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(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(metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
@ -246,17 +268,55 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
if v.option.PacketAddr {
|
||||||
|
packetAddrMetadata := *metadata // make a copy
|
||||||
|
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
packetAddrMetadata.DstPort = "443"
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(&packetAddrMetadata, false))
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
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 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
|
||||||
|
}
|
||||||
|
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())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
packetAddrMetadata := *metadata // make a copy
|
||||||
|
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
packetAddrMetadata.DstPort = "443"
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, &packetAddrMetadata)
|
||||||
|
} else {
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -267,8 +327,24 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (v *Vless) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// 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(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if v.option.XUDP {
|
||||||
|
return newPacketConn(&threadSafePacketConn{
|
||||||
|
PacketConn: vmessSing.NewXUDPConn(c, M.ParseSocksaddr(metadata.RemoteAddress())),
|
||||||
|
}, v), nil
|
||||||
|
} else if v.option.PacketAddr {
|
||||||
|
return newPacketConn(&threadSafePacketConn{
|
||||||
|
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
||||||
|
Conn: c, rAddr: metadata.UDPAddr(),
|
||||||
|
}, M.ParseSocksaddr(metadata.RemoteAddress())),
|
||||||
|
}, v), nil
|
||||||
|
}
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -277,19 +353,19 @@ 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() {
|
||||||
case C.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
addrType = vless.AtypIPv4
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
addrType = vless.AtypIPv6
|
addrType = vless.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
addrType = vless.AtypDomainName
|
addrType = vless.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
@ -301,7 +377,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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -402,7 +479,7 @@ 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.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS, vless.XRV:
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
}
|
}
|
||||||
@ -411,6 +488,16 @@ 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
@ -422,7 +509,10 @@ 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,
|
||||||
@ -447,8 +537,9 @@ 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{
|
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
})
|
||||||
@ -461,11 +552,9 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
|
|
||||||
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)
|
||||||
} else {
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -5,8 +5,6 @@ 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"
|
||||||
@ -15,13 +13,18 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
*Base
|
*Base
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
@ -52,7 +55,11 @@ type VmessOption struct {
|
|||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -80,6 +87,11 @@ type WSOptions struct {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vmess) StreamConn(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":
|
||||||
|
|
||||||
@ -90,6 +102,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{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,9 +121,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
|
||||||
}
|
}
|
||||||
@ -130,6 +142,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -157,6 +170,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -183,6 +197,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -197,9 +212,13 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if v.option.XUDP {
|
||||||
|
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
} else {
|
} else {
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -211,7 +230,9 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -220,13 +241,19 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
|
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
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())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
@ -234,9 +261,9 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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(metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
@ -244,6 +271,8 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
if v.option.PacketAddr {
|
||||||
|
_metadata := *metadata // make a copy
|
||||||
|
metadata = &_metadata
|
||||||
metadata.Host = packetaddr.SeqPacketMagicAddress
|
metadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
metadata.DstPort = "443"
|
metadata.DstPort = "443"
|
||||||
}
|
}
|
||||||
@ -255,36 +284,60 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if v.option.XUDP {
|
||||||
|
c = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
c = v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(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(c, metadata)
|
||||||
if v.option.PacketAddr {
|
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
|
||||||
} else if pc, ok := c.(net.PacketConn); ok {
|
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
|
||||||
}
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
|
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 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
|
||||||
|
}
|
||||||
|
|
||||||
|
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.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) SupportWithDialer() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if v.option.PacketAddr {
|
if v.option.PacketAddr {
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
||||||
} else if pc, ok := c.(net.PacketConn); ok {
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
}
|
}
|
||||||
@ -299,6 +352,9 @@ func (v *Vmess) SupportUOT() bool {
|
|||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
var options []vmess.ClientOption
|
var options []vmess.ClientOption
|
||||||
|
if option.GlobalPadding {
|
||||||
|
options = append(options, vmess.ClientWithGlobalPadding())
|
||||||
|
}
|
||||||
if option.AuthenticatedLength {
|
if option.AuthenticatedLength {
|
||||||
options = append(options, vmess.ClientWithAuthenticatedLength())
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
}
|
}
|
||||||
@ -307,10 +363,20 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch option.PacketEncoding {
|
||||||
|
case "packetaddr", "packet":
|
||||||
|
option.PacketAddr = true
|
||||||
|
case "xudp":
|
||||||
|
option.XUDP = true
|
||||||
|
}
|
||||||
|
if option.XUDP {
|
||||||
|
option.PacketAddr = false
|
||||||
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2", "grpc":
|
case "h2", "grpc":
|
||||||
if !option.TLS {
|
if !option.TLS {
|
||||||
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
option.TLS = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -320,6 +386,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
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),
|
||||||
@ -346,6 +414,7 @@ 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{
|
tlsConfig := &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
@ -360,7 +429,9 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
|
|
||||||
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)
|
||||||
|
|
||||||
}
|
}
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
@ -382,7 +453,14 @@ type vmessPacketConn struct {
|
|||||||
access sync.Mutex
|
access sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
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)
|
||||||
|
destAddr := addr.(*net.UDPAddr)
|
||||||
|
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
||||||
|
return 0, ErrUDPRemoteAddrMismatch
|
||||||
|
}
|
||||||
uc.access.Lock()
|
uc.access.Lock()
|
||||||
defer uc.access.Unlock()
|
defer uc.access.Unlock()
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
|
258
adapter/outbound/wireguard.go
Normal file
258
adapter/outbound/wireguard.go
Normal file
@ -0,0 +1,258 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/debug"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/wireguard-go/device"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WireGuard struct {
|
||||||
|
*Base
|
||||||
|
bind *wireguard.ClientBind
|
||||||
|
device *device.Device
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
dialer *wgDialer
|
||||||
|
startOnce sync.Once
|
||||||
|
startErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
type WireGuardOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key"`
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
|
Workers int `proxy:"workers,omitempty"`
|
||||||
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgDialer struct {
|
||||||
|
options []dialer.Option
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", destination.Addr), "", d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
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: &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])
|
||||||
|
reserved[1] = uint8(option.Reserved[1])
|
||||||
|
reserved[2] = uint8(option.Reserved[2])
|
||||||
|
}
|
||||||
|
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
|
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
||||||
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
if !strings.Contains(option.Ip, "/") {
|
||||||
|
option.Ip = option.Ip + "/32"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ip address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(option.Ipv6) > 0 {
|
||||||
|
if !strings.Contains(option.Ipv6, "/") {
|
||||||
|
option.Ipv6 = option.Ipv6 + "/128"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ipv6 address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(localPrefixes) == 0 {
|
||||||
|
return nil, E.New("missing local address")
|
||||||
|
}
|
||||||
|
var privateKey, peerPublicKey, preSharedKey string
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode private key")
|
||||||
|
}
|
||||||
|
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 += "\npublic_key=" + peerPublicKey
|
||||||
|
ipcConf += "\nendpoint=" + peerAddr.String()
|
||||||
|
if preSharedKey != "" {
|
||||||
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
|
}
|
||||||
|
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 option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
mtu := option.MTU
|
||||||
|
if mtu == 0 {
|
||||||
|
mtu = 1408
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
|
}
|
||||||
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
|
log.SingLogger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
|
},
|
||||||
|
Errorf: func(format string, args ...interface{}) {
|
||||||
|
log.SingLogger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
|
},
|
||||||
|
}, option.Workers)
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace("created wireguard ipc conf: \n", ipcConf)
|
||||||
|
}
|
||||||
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
|
}
|
||||||
|
//err = outbound.tunDevice.Start()
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeWireGuard(w *WireGuard) {
|
||||||
|
if w.device != nil {
|
||||||
|
w.device.Close()
|
||||||
|
}
|
||||||
|
_ = common.Close(w.tunDevice)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
w.dialer.options = opts
|
||||||
|
var conn net.Conn
|
||||||
|
w.startOnce.Do(func() {
|
||||||
|
w.startErr = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if w.startErr != nil {
|
||||||
|
return nil, w.startErr
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
var addrs []netip.Addr
|
||||||
|
addrs, err = resolver.LookupIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
conn, err = N.DialSerial(ctx, w.tunDevice, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()), addrs)
|
||||||
|
} else {
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if conn == nil {
|
||||||
|
return nil, E.New("conn is nil")
|
||||||
|
}
|
||||||
|
return NewConn(CN.NewRefConn(conn, w), w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
w.dialer.options = opts
|
||||||
|
var pc net.PacketConn
|
||||||
|
w.startOnce.Do(func() {
|
||||||
|
w.startErr = w.tunDevice.Start()
|
||||||
|
})
|
||||||
|
if w.startErr != nil {
|
||||||
|
return nil, w.startErr
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, E.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
||||||
|
}
|
@ -4,11 +4,13 @@ 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"
|
||||||
"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,9 +31,19 @@ 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)
|
||||||
|
} else {
|
||||||
|
f.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
f.onDialSuccess()
|
f.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed()
|
f.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
@ -72,8 +84,8 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (f *Fallback) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxy := f.findAliveProxy(true)
|
proxy := f.findAliveProxy(touch)
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -131,6 +143,8 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
@ -3,21 +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"
|
||||||
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"
|
"go.uber.org/atomic"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filter *regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
|
excludeFilterReg *regexp2.Regexp
|
||||||
|
excludeTypeArray []string
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
@ -30,18 +35,34 @@ type GroupBase struct {
|
|||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
|
excludeFilter string
|
||||||
|
excludeType string
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var filter *regexp2.Regexp = nil
|
var excludeFilterReg *regexp2.Regexp
|
||||||
|
if opt.excludeFilter != "" {
|
||||||
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
||||||
|
}
|
||||||
|
var excludeTypeArray []string
|
||||||
|
if opt.excludeType != "" {
|
||||||
|
excludeTypeArray = strings.Split(opt.excludeType, "|")
|
||||||
|
}
|
||||||
|
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
filter = regexp2.MustCompile(opt.filter, 0)
|
for _, filter := range strings.Split(opt.filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, 0)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
gb := &GroupBase{
|
gb := &GroupBase{
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
filter: filter,
|
filterRegs: filterRegs,
|
||||||
|
excludeFilterReg: excludeFilterReg,
|
||||||
|
excludeTypeArray: excludeTypeArray,
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
}
|
}
|
||||||
@ -52,21 +73,22 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
return gb
|
return gb
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) Touch() {
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
pd.Touch()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
if gb.filter == nil {
|
|
||||||
var proxies []C.Proxy
|
var proxies []C.Proxy
|
||||||
|
if len(gb.filterRegs) == 0 {
|
||||||
for _, pd := range gb.providers {
|
for _, pd := range gb.providers {
|
||||||
if touch {
|
if touch {
|
||||||
pd.Touch()
|
pd.Touch()
|
||||||
}
|
}
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
}
|
}
|
||||||
if len(proxies) == 0 {
|
} else {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, pd := range gb.providers {
|
for i, pd := range gb.providers {
|
||||||
if touch {
|
if touch {
|
||||||
pd.Touch()
|
pd.Touch()
|
||||||
@ -79,32 +101,94 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
version := gb.versions[i].Load()
|
version := gb.versions[i].Load()
|
||||||
if version != pd.Version() && gb.versions[i].CAS(version, pd.Version()) {
|
if version != pd.Version() && gb.versions[i].CompareAndSwap(version, pd.Version()) {
|
||||||
var (
|
var (
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
newProxies []C.Proxy
|
newProxies []C.Proxy
|
||||||
)
|
)
|
||||||
|
|
||||||
proxies = pd.Proxies()
|
proxies = pd.Proxies()
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range gb.filterRegs {
|
||||||
for _, p := range proxies {
|
for _, p := range proxies {
|
||||||
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
newProxies = append(newProxies, p)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
gb.proxies[i] = newProxies
|
gb.proxies[i] = newProxies
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var proxies []C.Proxy
|
|
||||||
for _, p := range gb.proxies {
|
for _, p := range gb.proxies {
|
||||||
proxies = append(proxies, p...)
|
proxies = append(proxies, p...)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range gb.filterRegs {
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range proxies { // add not matched proxies at the end
|
||||||
|
name := p.Name()
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,8 +220,13 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed() {
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
||||||
if gb.failedTesting.Load() {
|
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(err.Error(), "connection refused") {
|
||||||
|
go gb.healthCheck()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -157,8 +246,19 @@ func (gb *GroupBase) onDialFailed() {
|
|||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
gb.failedTesting.Store(true)
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
|
gb.healthCheck()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) healthCheck() {
|
||||||
|
if gb.failedTesting.Load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.failedTesting.Store(true)
|
||||||
wg := sync.WaitGroup{}
|
wg := sync.WaitGroup{}
|
||||||
for _, proxyProvider := range gb.providers {
|
for _, proxyProvider := range gb.providers {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
@ -173,9 +273,6 @@ func (gb *GroupBase) onDialFailed() {
|
|||||||
gb.failedTesting.Store(false)
|
gb.failedTesting.Store(false)
|
||||||
gb.failedTimes = 0
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||||
return 5 * time.Second.Milliseconds()
|
return 5 * time.Second.Milliseconds()
|
||||||
|
@ -5,11 +5,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"net"
|
"net"
|
||||||
"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"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -82,18 +83,25 @@ 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) {
|
||||||
defer func() {
|
proxy := lb.Unwrap(metadata, true)
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(lb)
|
c.AppendToChains(lb)
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
lb.onDialSuccess()
|
lb.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
lb.onDialFailed()
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,7 +113,7 @@ func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,11 +123,20 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
|
flag := true
|
||||||
idx := 0
|
idx := 0
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
for i := 0; i < length; i++ {
|
for i := 0; i < length; i++ {
|
||||||
idx = (idx + 1) % length
|
flag = !flag
|
||||||
|
if flag {
|
||||||
|
idx = (idx - 1) % length
|
||||||
|
} else {
|
||||||
|
idx = (idx + 2) % length
|
||||||
|
}
|
||||||
|
if idx < 0 {
|
||||||
|
idx = idx + length
|
||||||
|
}
|
||||||
proxy := proxies[idx]
|
proxy := proxies[idx]
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
return proxy
|
return proxy
|
||||||
@ -157,7 +174,7 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
func strategyStickySessions() strategyFn {
|
func strategyStickySessions() strategyFn {
|
||||||
ttl := time.Minute * 10
|
ttl := time.Minute * 10
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
lruCache := cache.NewLRUCache[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) C.Proxy {
|
||||||
@ -190,8 +207,8 @@ func strategyStickySessions() strategyFn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(true)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -228,6 +245,8 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
@ -30,6 +30,8 @@ type GroupCommonOption struct {
|
|||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
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"`
|
||||||
|
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) {
|
||||||
@ -76,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,9 +3,12 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"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"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -15,6 +18,36 @@ 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)
|
||||||
@ -25,38 +58,20 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
case 1:
|
case 1:
|
||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
var d C.Dialer
|
||||||
first := proxies[0]
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
last := proxies[len(proxies)-1]
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
|
d = proxyDialer{
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
proxy: proxy,
|
||||||
if err != nil {
|
dialer: d,
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
}
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
var currentMeta *C.Metadata
|
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
conn := outbound.NewConn(c, last)
|
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
conn.AppendToChains(chainProxies[i])
|
conn.AppendToChains(chainProxies[i])
|
||||||
}
|
}
|
||||||
@ -77,41 +92,20 @@ func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
first := proxies[0]
|
var d C.Dialer
|
||||||
last := proxies[len(proxies)-1]
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
d = proxyDialer{
|
||||||
if err != nil {
|
proxy: proxy,
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
dialer: d,
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
}
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
var currentMeta *C.Metadata
|
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var pc C.PacketConn
|
|
||||||
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
pc.AppendToChains(chainProxies[i])
|
pc.AppendToChains(chainProxies[i])
|
||||||
}
|
}
|
||||||
@ -127,8 +121,19 @@ func (r *Relay) SupportUDP() bool {
|
|||||||
if len(proxies) == 0 { // C.Direct
|
if len(proxies) == 0 { // C.Direct
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
for i := len(proxies) - 1; i >= 0; i-- {
|
||||||
return last.SupportUDP() && last.SupportUOT()
|
proxy := proxies[i]
|
||||||
|
if !proxy.SupportUDP() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if proxy.SupportUOT() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if !proxy.SupportWithDialer() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -153,11 +158,11 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
for n, proxy := range rawProxies {
|
for n, proxy := range rawProxies {
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
chainProxies = append(chainProxies, proxy)
|
chainProxies = append(chainProxies, proxy)
|
||||||
subproxy := proxy.Unwrap(metadata)
|
subproxy := proxy.Unwrap(metadata, touch)
|
||||||
for subproxy != nil {
|
for subproxy != nil {
|
||||||
chainProxies = append(chainProxies, subproxy)
|
chainProxies = append(chainProxies, subproxy)
|
||||||
proxies[n] = subproxy
|
proxies[n] = subproxy
|
||||||
subproxy = subproxy.Unwrap(metadata)
|
subproxy = subproxy.Unwrap(metadata, touch)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,6 +190,8 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
"",
|
"",
|
||||||
|
"",
|
||||||
|
"",
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
@ -74,8 +74,8 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
@ -99,6 +99,8 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
@ -6,6 +6,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
"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"
|
||||||
@ -34,12 +35,23 @@ func (u *URLTest) Now() string {
|
|||||||
|
|
||||||
// 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) {
|
||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
proxy := u.fast(true)
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
|
} else {
|
||||||
|
u.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
u.onDialSuccess()
|
u.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed()
|
u.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -55,12 +67,12 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
@ -89,6 +101,9 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
|
u.Touch()
|
||||||
|
}
|
||||||
|
|
||||||
return elm
|
return elm
|
||||||
}
|
}
|
||||||
@ -139,6 +154,8 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
},
|
},
|
||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
|
option.ExcludeFilter,
|
||||||
|
option.ExcludeType,
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
@ -16,32 +16,19 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
if ip, err := netip.ParseAddr(host); err != nil {
|
||||||
if err != nil {
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: netip.Addr{},
|
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
err = nil
|
} else {
|
||||||
return
|
|
||||||
} else if ip.Is4() {
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
|
||||||
Host: "",
|
Host: "",
|
||||||
DstIP: ip,
|
DstIP: ip.Unmap(),
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
addr = &C.Metadata{
|
|
||||||
AddrType: C.AtypIPv6,
|
|
||||||
Host: "",
|
|
||||||
DstIP: ip,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,13 +3,15 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true, KeyReplacer: structure.DefaultKeyReplacer})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
return nil, fmt.Errorf("missing type")
|
return nil, fmt.Errorf("missing type")
|
||||||
@ -55,6 +57,11 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
vmessOption.ClientFingerprint = GlobalUtlsClient
|
||||||
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -62,6 +69,11 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
vlessOption.ClientFingerprint = GlobalUtlsClient
|
||||||
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -76,6 +88,11 @@ 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{}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
trojanOption.ClientFingerprint = GlobalUtlsClient
|
||||||
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -88,6 +105,20 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
|
case "wireguard":
|
||||||
|
wgOption := &outbound.WireGuardOption{}
|
||||||
|
err = decoder.Decode(mapping, wgOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewWireGuard(*wgOption)
|
||||||
|
case "tuic":
|
||||||
|
tuicOption := &outbound.TuicOption{}
|
||||||
|
err = decoder.Decode(mapping, tuicOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewTuic(*tuicOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -2,12 +2,14 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -35,16 +37,13 @@ func (hc *HealthCheck) process() {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
hc.check()
|
hc.lazyCheck()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
now := time.Now().Unix()
|
hc.lazyCheck()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
}
|
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -52,6 +51,17 @@ 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
|
||||||
}
|
}
|
||||||
@ -66,18 +76,26 @@ 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 := ""
|
||||||
|
if uid, err := uuid.NewV4(); err == nil {
|
||||||
|
id = uid.String()
|
||||||
|
}
|
||||||
|
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 {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
|
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Wait()
|
b.Wait()
|
||||||
|
log.Debugln("Finish A Health Checking {%s}", id)
|
||||||
return struct{}{}, nil
|
return struct{}{}, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -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"
|
||||||
)
|
)
|
||||||
@ -26,6 +26,8 @@ type proxyProviderSchema struct {
|
|||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
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"`
|
||||||
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,5 +63,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
|
||||||
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
excludeFilter := schema.ExcludeFilter
|
||||||
|
excludeType := schema.ExcludeType
|
||||||
|
|
||||||
|
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -1,19 +1,24 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"net/http"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||||
|
"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"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -35,6 +40,7 @@ type proxySetProvider struct {
|
|||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
version uint32
|
version uint32
|
||||||
|
subscriptionInfo *SubscriptionInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -44,6 +50,7 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,20 +99,67 @@ 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.check() }()
|
defer func() { go pp.healthCheck.lazyCheck() }()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) getSubscriptionInfo() {
|
||||||
|
if pp.VehicleType() != types.HTTP {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
||||||
|
defer cancel()
|
||||||
|
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
||||||
|
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp2.Body.Close()
|
||||||
|
userInfoStr = strings.TrimSpace(resp2.Header.Get("subscription-userinfo"))
|
||||||
|
if userInfoStr == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pp.subscriptionInfo, err = NewSubscriptionInfo(userInfoStr)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
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, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
|
}
|
||||||
|
var excludeTypeArray []string
|
||||||
|
if excludeType != "" {
|
||||||
|
excludeTypeArray = strings.Split(excludeType, "|")
|
||||||
|
}
|
||||||
|
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
if hc.auto() {
|
||||||
go hc.process()
|
go hc.process()
|
||||||
@ -116,9 +170,10 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg), 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
|
||||||
@ -209,10 +264,11 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
pd.version += 1
|
pd.version += 1
|
||||||
|
pd.getSubscriptionInfo()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@ -229,18 +285,60 @@ func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) resource.Pa
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
name, ok := mapping["name"]
|
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
||||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
mType, ok := mapping["type"]
|
||||||
if ok && len(filter) > 0 && mat == nil {
|
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"]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name, ok := mName.(string)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(excludeFilter) > 0 {
|
||||||
|
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(filter) > 0 {
|
||||||
|
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := proxiesSet[name]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
|
57
adapter/provider/subscription_info.go
Normal file
57
adapter/provider/subscription_info.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SubscriptionInfo struct {
|
||||||
|
Upload int64
|
||||||
|
Download int64
|
||||||
|
Total int64
|
||||||
|
Expire int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) {
|
||||||
|
si = &SubscriptionInfo{}
|
||||||
|
str = strings.ToLower(str)
|
||||||
|
reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0)
|
||||||
|
reExpire := regexp2.MustCompile("expire=(\\d+)", 0)
|
||||||
|
|
||||||
|
match, err := reTraffic.FindStringMatch(str)
|
||||||
|
if err != nil || match == nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
group := match.Groups()
|
||||||
|
si.Upload, err = str2uint64(group[1].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
si.Download, err = str2uint64(group[2].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
si.Total, err = str2uint64(group[3].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
match, _ = reExpire.FindStringMatch(str)
|
||||||
|
if match != nil {
|
||||||
|
group = match.Groups()
|
||||||
|
si.Expire, err = str2uint64(group[1].String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func str2uint64(str string) (int64, error) {
|
||||||
|
i, err := strconv.ParseInt(str, 10, 64)
|
||||||
|
return i, err
|
||||||
|
}
|
25
common/buf/sing.go
Normal file
25
common/buf/sing.go
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
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 StackNew = buf.StackNew
|
||||||
|
var StackNewSize = buf.StackNewSize
|
||||||
|
var With = buf.With
|
||||||
|
|
||||||
|
var KeepAlive = common.KeepAlive
|
||||||
|
|
||||||
|
//go:norace
|
||||||
|
func Dup[T any](obj T) T {
|
||||||
|
return common.Dup(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
var Must = common.Must
|
||||||
|
var Error = common.Error
|
106
common/cache/cache.go
vendored
106
common/cache/cache.go
vendored
@ -1,106 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Cache store element with a expired time
|
|
||||||
type Cache[K comparable, V any] struct {
|
|
||||||
*cache[K, V]
|
|
||||||
}
|
|
||||||
|
|
||||||
type cache[K comparable, V any] struct {
|
|
||||||
mapping sync.Map
|
|
||||||
janitor *janitor[K, V]
|
|
||||||
}
|
|
||||||
|
|
||||||
type element[V any] struct {
|
|
||||||
Expired time.Time
|
|
||||||
Payload V
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put element in Cache with its ttl
|
|
||||||
func (c *cache[K, V]) Put(key K, payload V, ttl time.Duration) {
|
|
||||||
c.mapping.Store(key, &element[V]{
|
|
||||||
Payload: payload,
|
|
||||||
Expired: time.Now().Add(ttl),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get element in Cache, and drop when it expired
|
|
||||||
func (c *cache[K, V]) Get(key K) V {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return getZero[V]()
|
|
||||||
}
|
|
||||||
elm := item.(*element[V])
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return getZero[V]()
|
|
||||||
}
|
|
||||||
return elm.Payload
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetWithExpire element in Cache with Expire Time
|
|
||||||
func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
elm := item.(*element[V])
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return elm.Payload, elm.Expired
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cache[K, V]) cleanup() {
|
|
||||||
c.mapping.Range(func(k, v any) bool {
|
|
||||||
key := k.(string)
|
|
||||||
elm := v.(*element[V])
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
type janitor[K comparable, V any] struct {
|
|
||||||
interval time.Duration
|
|
||||||
stop chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *janitor[K, V]) process(c *cache[K, V]) {
|
|
||||||
ticker := time.NewTicker(j.interval)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
c.cleanup()
|
|
||||||
case <-j.stop:
|
|
||||||
ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopJanitor[K comparable, V any](c *Cache[K, V]) {
|
|
||||||
c.janitor.stop <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// New return *Cache
|
|
||||||
func New[K comparable, V any](interval time.Duration) *Cache[K, V] {
|
|
||||||
j := &janitor[K, V]{
|
|
||||||
interval: interval,
|
|
||||||
stop: make(chan struct{}),
|
|
||||||
}
|
|
||||||
c := &cache[K, V]{janitor: j}
|
|
||||||
go j.process(c)
|
|
||||||
C := &Cache[K, V]{c}
|
|
||||||
runtime.SetFinalizer(C, stopJanitor[K, V])
|
|
||||||
return C
|
|
||||||
}
|
|
72
common/cache/cache_test.go
vendored
72
common/cache/cache_test.go
vendored
@ -1,72 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCache_Basic(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
|
|
||||||
d := New[string, string](interval)
|
|
||||||
d.Put("string", "a", ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
assert.Equal(t, i, 1, "should recv 1")
|
|
||||||
|
|
||||||
s := d.Get("string")
|
|
||||||
assert.Equal(t, s, "a", "should recv 'a'")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_TTL(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
now := time.Now()
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
c.Put("int2", 2, ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
_, expired := c.GetWithExpire("int2")
|
|
||||||
assert.Equal(t, i, 1, "should recv 1")
|
|
||||||
assert.True(t, now.Before(expired))
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i = c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int2")
|
|
||||||
assert.True(t, i == 0, "should recv 0")
|
|
||||||
assert.True(t, j == 0, "should recv 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoCleanup(t *testing.T) {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i := c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int")
|
|
||||||
assert.True(t, i == 0, "should recv 0")
|
|
||||||
assert.True(t, j == 0, "should recv 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoGC(t *testing.T) {
|
|
||||||
sign := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
sign <- struct{}{}
|
|
||||||
}()
|
|
||||||
|
|
||||||
<-sign
|
|
||||||
runtime.GC()
|
|
||||||
}
|
|
4
common/cache/lrucache.go
vendored
4
common/cache/lrucache.go
vendored
@ -65,8 +65,8 @@ type LruCache[K comparable, V any] struct {
|
|||||||
onEvict EvictCallback[K, V]
|
onEvict EvictCallback[K, V]
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewLRUCache creates an LruCache
|
// New creates an LruCache
|
||||||
func NewLRUCache[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||||
lc := &LruCache[K, V]{
|
lc := &LruCache[K, V]{
|
||||||
lru: list.New[*entry[K, V]](),
|
lru: list.New[*entry[K, V]](),
|
||||||
cache: make(map[K]*list.Element[*entry[K, V]]),
|
cache: make(map[K]*list.Element[*entry[K, V]]),
|
||||||
|
20
common/cache/lrucache_test.go
vendored
20
common/cache/lrucache_test.go
vendored
@ -19,7 +19,7 @@ var entries = []struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUCache(t *testing.T) {
|
func TestLRUCache(t *testing.T) {
|
||||||
c := NewLRUCache[string, string]()
|
c := New[string, string]()
|
||||||
|
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
c.Set(e.key, e.value)
|
c.Set(e.key, e.value)
|
||||||
@ -45,7 +45,7 @@ func TestLRUCache(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUMaxAge(t *testing.T) {
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
c := NewLRUCache[string, string](WithAge[string, string](86400))
|
c := New[string, string](WithAge[string, string](86400))
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expected := now + 86400
|
expected := now + 86400
|
||||||
@ -88,7 +88,7 @@ func TestLRUMaxAge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUpdateOnGet(t *testing.T) {
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
c := NewLRUCache[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
c := New[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expires := now + 86400/2
|
expires := now + 86400/2
|
||||||
@ -103,7 +103,7 @@ func TestLRUpdateOnGet(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestMaxSize(t *testing.T) {
|
func TestMaxSize(t *testing.T) {
|
||||||
c := NewLRUCache[string, string](WithSize[string, string](2))
|
c := New[string, string](WithSize[string, string](2))
|
||||||
// Add one expired entry
|
// Add one expired entry
|
||||||
c.Set("foo", "bar")
|
c.Set("foo", "bar")
|
||||||
_, ok := c.Get("foo")
|
_, ok := c.Get("foo")
|
||||||
@ -117,7 +117,7 @@ func TestMaxSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExist(t *testing.T) {
|
func TestExist(t *testing.T) {
|
||||||
c := NewLRUCache[int, int](WithSize[int, int](1))
|
c := New[int, int](WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
assert.True(t, c.Exist(1))
|
assert.True(t, c.Exist(1))
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
@ -130,7 +130,7 @@ func TestEvict(t *testing.T) {
|
|||||||
temp = key + value
|
temp = key + value
|
||||||
}
|
}
|
||||||
|
|
||||||
c := NewLRUCache[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
c := New[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
|
|
||||||
@ -138,7 +138,7 @@ func TestEvict(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSetWithExpire(t *testing.T) {
|
func TestSetWithExpire(t *testing.T) {
|
||||||
c := NewLRUCache[int, *struct{}](WithAge[int, *struct{}](1))
|
c := New[int, *struct{}](WithAge[int, *struct{}](1))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -153,7 +153,7 @@ func TestSetWithExpire(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStale(t *testing.T) {
|
func TestStale(t *testing.T) {
|
||||||
c := NewLRUCache[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
c := New[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -166,11 +166,11 @@ func TestStale(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCloneTo(t *testing.T) {
|
func TestCloneTo(t *testing.T) {
|
||||||
o := NewLRUCache[string, int](WithSize[string, int](10))
|
o := New[string, int](WithSize[string, int](10))
|
||||||
o.Set("1", 1)
|
o.Set("1", 1)
|
||||||
o.Set("2", 2)
|
o.Set("2", 2)
|
||||||
|
|
||||||
n := NewLRUCache[string, int](WithSize[string, int](2))
|
n := New[string, int](WithSize[string, int](2))
|
||||||
n.Set("3", 3)
|
n.Set("3", 3)
|
||||||
n.Set("4", 4)
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
25
common/callback/callback.go
Normal file
25
common/callback/callback.go
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package callback
|
||||||
|
|
||||||
|
import (
|
||||||
|
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) Upstream() any {
|
||||||
|
return c.Conn
|
||||||
|
}
|
@ -2,8 +2,10 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@ -47,7 +49,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["port"] = urlHysteria.Port()
|
hysteria["port"] = urlHysteria.Port()
|
||||||
hysteria["sni"] = query.Get("peer")
|
hysteria["sni"] = query.Get("peer")
|
||||||
hysteria["obfs"] = query.Get("obfs")
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
hysteria["alpn"] = query.Get("alpn")
|
hysteria["alpn"] = []string{query.Get("alpn")}
|
||||||
hysteria["auth_str"] = query.Get("auth")
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
hysteria["protocol"] = query.Get("protocol")
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
up := query.Get("up")
|
up := query.Get("up")
|
||||||
@ -111,6 +113,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 +128,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,7 +150,11 @@ 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 != "" {
|
||||||
@ -154,8 +170,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
|
||||||
@ -169,6 +188,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
|
||||||
|
|
||||||
@ -264,22 +284,28 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
cipher = urlSS.User.Username()
|
cipherRaw = urlSS.User.Username()
|
||||||
|
cipher string
|
||||||
password 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, 20)
|
ss := make(map[string]any, 10)
|
||||||
|
|
||||||
ss["name"] = name
|
ss["name"] = name
|
||||||
ss["type"] = scheme
|
ss["type"] = scheme
|
||||||
@ -289,6 +315,9 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
ss["password"] = password
|
ss["password"] = password
|
||||||
query := urlSS.Query()
|
query := urlSS.Query()
|
||||||
ss["udp"] = true
|
ss["udp"] = true
|
||||||
|
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
||||||
|
ss["udp-over-tcp"] = true
|
||||||
|
}
|
||||||
if strings.Contains(query.Get("plugin"), "obfs") {
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
obfsParams := strings.Split(query.Get("plugin"), ";")
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
ss["plugin"] = "obfs"
|
ss["plugin"] = "obfs"
|
||||||
|
@ -2,6 +2,7 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
@ -314,3 +315,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)
|
||||||
|
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()
|
||||||
@ -20,11 +29,24 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
tls := strings.ToLower(query.Get("security"))
|
tls := strings.ToLower(query.Get("security"))
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 == "" {
|
||||||
network = "tcp"
|
network = "tcp"
|
||||||
@ -79,6 +101,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 +119,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/bind.go
Normal file
36
common/net/bind.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
type bindPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
||||||
|
n, _, err = wpc.PacketConn.ReadFrom(b)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
||||||
|
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
||||||
|
return wpc.rAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
||||||
|
if wpc.PacketConn.LocalAddr() == nil {
|
||||||
|
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
} else {
|
||||||
|
return wpc.PacketConn.LocalAddr()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
||||||
|
return &bindPacketConn{
|
||||||
|
PacketConn: pc,
|
||||||
|
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,22 @@ 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.Buffered() > 0 {
|
||||||
|
_, err = buffer.ReadOnceFrom(c.r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) Upstream() any {
|
||||||
|
return c.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BufferedConn) ReaderReplaceable() bool {
|
||||||
|
if c.r.Buffered() > 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
104
common/net/refconn.go
Normal file
104
common/net/refconn.go
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type refConn struct {
|
||||||
|
conn net.Conn
|
||||||
|
ref any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Read(b []byte) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Write(b []byte) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Close() error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) LocalAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) RemoteAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.RemoteAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) SetDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.SetDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) SetReadDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(c.ref)
|
||||||
|
return c.conn.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Upstream() any {
|
||||||
|
return c.conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||||
|
return &refConn{conn: 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,30 +1,24 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
//import (
|
||||||
"io"
|
// "io"
|
||||||
"net"
|
// "net"
|
||||||
"time"
|
// "time"
|
||||||
|
//)
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
//
|
||||||
)
|
//// Relay copies between left and right bidirectionally.
|
||||||
|
//func Relay(leftConn, rightConn net.Conn) {
|
||||||
// Relay copies between left and right bidirectionally.
|
// ch := make(chan error)
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
//
|
||||||
ch := make(chan error)
|
// go func() {
|
||||||
|
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
go func() {
|
// // See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// leftConn.SetReadDeadline(time.Now())
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// ch <- err
|
||||||
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
// }()
|
||||||
pool.Put(buf)
|
//
|
||||||
leftConn.SetReadDeadline(time.Now())
|
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
ch <- err
|
// rightConn.SetReadDeadline(time.Now())
|
||||||
}()
|
// <-ch
|
||||||
|
//}
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
|
||||||
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
|
||||||
pool.Put(buf)
|
|
||||||
rightConn.SetReadDeadline(time.Now())
|
|
||||||
<-ch
|
|
||||||
}
|
|
||||||
|
22
common/net/sing.go
Normal file
22
common/net/sing.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
"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
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
||||||
|
}
|
52
common/net/tls.go
Normal file
52
common/net/tls.go
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
|
if certificate == "" || privateKey == "" {
|
||||||
|
return newRandomTLSKeyPair()
|
||||||
|
}
|
||||||
|
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||||
|
if painTextErr == nil {
|
||||||
|
return cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
|
||||||
|
if loadErr != nil {
|
||||||
|
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
@ -8,7 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var DefaultAllocator = NewAllocator()
|
var defaultAllocator = NewAllocator()
|
||||||
|
|
||||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
type Allocator struct {
|
type Allocator struct {
|
||||||
|
@ -13,9 +13,9 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return DefaultAllocator.Get(size)
|
return defaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Put(buf []byte) error {
|
func Put(buf []byte) error {
|
||||||
return DefaultAllocator.Put(buf)
|
return defaultAllocator.Put(buf)
|
||||||
}
|
}
|
||||||
|
7
common/pool/sing.go
Normal file
7
common/pool/sing.go
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import "github.com/sagernet/sing/common/buf"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
buf.DefaultAllocator = defaultAllocator
|
||||||
|
}
|
@ -3,6 +3,7 @@ package structure
|
|||||||
// references: https://github.com/mitchellh/mapstructure
|
// references: https://github.com/mitchellh/mapstructure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -13,8 +14,11 @@ import (
|
|||||||
type Option struct {
|
type Option struct {
|
||||||
TagName string
|
TagName string
|
||||||
WeaklyTypedInput bool
|
WeaklyTypedInput bool
|
||||||
|
KeyReplacer *strings.Replacer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var DefaultKeyReplacer = strings.NewReplacer("_", "-")
|
||||||
|
|
||||||
// Decoder is the core of structure
|
// Decoder is the core of structure
|
||||||
type Decoder struct {
|
type Decoder struct {
|
||||||
option *Option
|
option *Option
|
||||||
@ -49,6 +53,23 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
omitempty := found && omitKey == "omitempty"
|
omitempty := found && omitKey == "omitempty"
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
|
if !ok {
|
||||||
|
if d.option.KeyReplacer != nil {
|
||||||
|
key = d.option.KeyReplacer.Replace(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _strKey := range src {
|
||||||
|
strKey := _strKey
|
||||||
|
if d.option.KeyReplacer != nil {
|
||||||
|
strKey = d.option.KeyReplacer.Replace(strKey)
|
||||||
|
}
|
||||||
|
if strings.EqualFold(key, strKey) {
|
||||||
|
value = src[_strKey]
|
||||||
|
ok = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
if omitempty {
|
if omitempty {
|
||||||
continue
|
continue
|
||||||
@ -65,9 +86,16 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
switch val.Kind() {
|
kind := val.Kind()
|
||||||
case reflect.Int:
|
switch {
|
||||||
|
case isInt(kind):
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
|
case isUint(kind):
|
||||||
|
return d.decodeUint(name, data, val)
|
||||||
|
case isFloat(kind):
|
||||||
|
return d.decodeFloat(name, data, val)
|
||||||
|
}
|
||||||
|
switch kind {
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
return d.decodeString(name, data, val)
|
return d.decodeString(name, data, val)
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
@ -85,13 +113,42 @@ func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isInt(kind reflect.Kind) bool {
|
||||||
|
switch kind {
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isUint(kind reflect.Kind) bool {
|
||||||
|
switch kind {
|
||||||
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isFloat(kind reflect.Kind) bool {
|
||||||
|
switch kind {
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.Int:
|
case isInt(kind):
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
case isUint(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetInt(int64(dataVal.Uint()))
|
||||||
|
case isFloat(kind) && d.option.WeaklyTypedInput:
|
||||||
val.SetInt(int64(dataVal.Float()))
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
@ -110,14 +167,72 @@ func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeUint(name string, data any, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
kind := dataVal.Kind()
|
||||||
|
switch {
|
||||||
|
case isUint(kind):
|
||||||
|
val.SetUint(dataVal.Uint())
|
||||||
|
case isInt(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetUint(uint64(dataVal.Int()))
|
||||||
|
case isFloat(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetUint(uint64(dataVal.Float()))
|
||||||
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
|
var i uint64
|
||||||
|
i, err = strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
|
||||||
|
if err == nil {
|
||||||
|
val.SetUint(i)
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf(
|
||||||
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
|
name, val.Type(), dataVal.Type(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeFloat(name string, data any, val reflect.Value) (err error) {
|
||||||
|
dataVal := reflect.ValueOf(data)
|
||||||
|
kind := dataVal.Kind()
|
||||||
|
switch {
|
||||||
|
case isFloat(kind):
|
||||||
|
val.SetFloat(dataVal.Float())
|
||||||
|
case isUint(kind):
|
||||||
|
val.SetFloat(float64(dataVal.Uint()))
|
||||||
|
case isInt(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetFloat(float64(dataVal.Int()))
|
||||||
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
|
var i float64
|
||||||
|
i, err = strconv.ParseFloat(dataVal.String(), val.Type().Bits())
|
||||||
|
if err == nil {
|
||||||
|
val.SetFloat(i)
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf(
|
||||||
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
|
name, val.Type(), dataVal.Type(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.String:
|
case kind == reflect.String:
|
||||||
val.SetString(dataVal.String())
|
val.SetString(dataVal.String())
|
||||||
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
case isInt(kind) && d.option.WeaklyTypedInput:
|
||||||
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||||
|
case isUint(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
||||||
|
case isFloat(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetString(strconv.FormatFloat(dataVal.Float(), 'E', -1, dataVal.Type().Bits()))
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -133,8 +248,10 @@ func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err erro
|
|||||||
switch {
|
switch {
|
||||||
case kind == reflect.Bool:
|
case kind == reflect.Bool:
|
||||||
val.SetBool(dataVal.Bool())
|
val.SetBool(dataVal.Bool())
|
||||||
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
case isInt(kind) && d.option.WeaklyTypedInput:
|
||||||
val.SetBool(dataVal.Int() != 0)
|
val.SetBool(dataVal.Int() != 0)
|
||||||
|
case isUint(kind) && d.option.WeaklyTypedInput:
|
||||||
|
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -149,6 +266,17 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
|
if dataVal.Kind() == reflect.String && valElemType.Kind() == reflect.Uint8 { // from encoding/json
|
||||||
|
s := []byte(dataVal.String())
|
||||||
|
b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
|
||||||
|
n, err := base64.StdEncoding.Decode(b, s)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("try decode '%s' by base64 error: %w", name, err)
|
||||||
|
}
|
||||||
|
val.SetBytes(b[:n])
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
if dataVal.Kind() != reflect.Slice {
|
if dataVal.Kind() != reflect.Slice {
|
||||||
return fmt.Errorf("'%s' is not a slice", name)
|
return fmt.Errorf("'%s' is not a slice", name)
|
||||||
}
|
}
|
||||||
@ -353,12 +481,18 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
if !rawMapVal.IsValid() {
|
if !rawMapVal.IsValid() {
|
||||||
// Do a slower search by iterating over each key and
|
// Do a slower search by iterating over each key and
|
||||||
// doing case-insensitive search.
|
// doing case-insensitive search.
|
||||||
|
if d.option.KeyReplacer != nil {
|
||||||
|
fieldName = d.option.KeyReplacer.Replace(fieldName)
|
||||||
|
}
|
||||||
for dataValKey := range dataValKeys {
|
for dataValKey := range dataValKeys {
|
||||||
mK, ok := dataValKey.Interface().(string)
|
mK, ok := dataValKey.Interface().(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
// Not a string key
|
// Not a string key
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if d.option.KeyReplacer != nil {
|
||||||
|
mK = d.option.KeyReplacer.Replace(mK)
|
||||||
|
}
|
||||||
|
|
||||||
if strings.EqualFold(mK, fieldName) {
|
if strings.EqualFold(mK, fieldName) {
|
||||||
rawMapKey = dataValKey
|
rawMapKey = dataValKey
|
||||||
|
@ -137,3 +137,45 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValue(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []any{"bar", nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"bar", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := weakTypeDecoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, goal.Bar, s.Bar)
|
||||||
|
|
||||||
|
s = &BazSlice{}
|
||||||
|
err = decoder.Decode(rawMap, s)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &struct {
|
||||||
|
Bar []map[string]any `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Nil(t, s.Bar[1])
|
||||||
|
|
||||||
|
ss := &struct {
|
||||||
|
Bar []Baz `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = decoder.Decode(rawMap, ss)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
@ -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
|
||||||
|
}
|
||||||
|
92
component/dialer/bind_windows.go
Normal file
92
component/dialer/bind_windows.go
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"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]))
|
||||||
|
return syscall.SetsockoptInt(handle, syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx))
|
||||||
|
}
|
||||||
|
|
||||||
|
func bind6(handle syscall.Handle, ifaceIdx int) error {
|
||||||
|
return syscall.SetsockoptInt(handle, syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, ifaceIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = bind6err
|
||||||
|
} else {
|
||||||
|
innerErr = bind4err
|
||||||
|
}
|
||||||
|
} 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)
|
||||||
|
}
|
||||||
|
}
|
@ -4,25 +4,26 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
tcpConcurrent = false
|
tcpConcurrent = false
|
||||||
DisableIPv6 = false
|
|
||||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
ErrorConnTimeout = errors.New("connect timeout")
|
||||||
|
fallbackTimeout = 300 * time.Millisecond
|
||||||
)
|
)
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
func applyOptions(options ...Option) *option {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
routingMark: int(DefaultRoutingMark.Load()),
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
@ -36,6 +37,12 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
o(opt)
|
o(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return opt
|
||||||
|
}
|
||||||
|
|
||||||
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
|
opt := applyOptions(options...)
|
||||||
|
|
||||||
if opt.network == 4 || opt.network == 6 {
|
if opt.network == 4 || opt.network == 6 {
|
||||||
if strings.Contains(network, "tcp") {
|
if strings.Contains(network, "tcp") {
|
||||||
network = "tcp"
|
network = "tcp"
|
||||||
@ -48,7 +55,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleDialContext(ctx, network, address, opt)
|
return actualSingleStackDialContext(ctx, network, address, opt)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return actualDualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, address, opt)
|
||||||
default:
|
default:
|
||||||
@ -57,18 +64,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 != "" {
|
||||||
@ -92,11 +88,11 @@ func SetDial(concurrent bool) {
|
|||||||
dialMux.Lock()
|
dialMux.Lock()
|
||||||
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()
|
dialMux.Unlock()
|
||||||
@ -117,34 +113,95 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
if DisableIPv6 && destination.Is6() {
|
address := net.JoinHostPort(destination.String(), port)
|
||||||
return nil, ErrorDisableIPv6
|
if opt.tfo {
|
||||||
|
return dialTFO(ctx, *dialer, network, address)
|
||||||
|
}
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
func serialSingleStackDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return serialDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func serialDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return dualStackDialContext(
|
||||||
|
ctx,
|
||||||
|
func(ctx context.Context) (net.Conn, error) { return serialDialContext(ctx, network, ips, port, opt) },
|
||||||
|
func(ctx context.Context) (net.Conn, error) { return serialDialContext(ctx, network, ips, port, opt) },
|
||||||
|
opt.prefer == 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleStackDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if conn, err := parallelDialContext(ctx, network, ips, port, opt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if opt.prefer != 4 && opt.prefer != 6 {
|
||||||
|
return parallelDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
ipv4s, ipv6s := sortationAddr(ips)
|
||||||
|
return dualStackDialContext(
|
||||||
|
ctx,
|
||||||
|
func(ctx context.Context) (net.Conn, error) {
|
||||||
|
return parallelDialContext(ctx, network, ipv4s, port, opt)
|
||||||
|
},
|
||||||
|
func(ctx context.Context) (net.Conn, error) {
|
||||||
|
return parallelDialContext(ctx, network, ipv6s, port, opt)
|
||||||
|
},
|
||||||
|
opt.prefer == 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Dialer struct {
|
||||||
|
Opt option
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return DialContext(ctx, network, address, WithOption(d.Opt))
|
||||||
|
}
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDialer(options ...Option) Dialer {
|
||||||
|
opt := applyOptions(options...)
|
||||||
|
return Dialer{Opt: *opt}
|
||||||
|
}
|
||||||
|
|
||||||
|
func dualStackDialContext(
|
||||||
|
ctx context.Context,
|
||||||
|
ipv4DialFn func(ctx context.Context) (net.Conn, error),
|
||||||
|
ipv6DialFn func(ctx context.Context) (net.Conn, error),
|
||||||
|
preferIPv4 bool) (net.Conn, error) {
|
||||||
|
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(dial func(ctx context.Context) (net.Conn, error), 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, direct bool, ipv6 bool) {
|
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
@ -154,249 +211,140 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
result.Conn, result.error = dial(ctx)
|
||||||
|
}
|
||||||
|
go racer(ipv4DialFn, preferIPv4)
|
||||||
|
go racer(ipv6DialFn, !preferIPv4)
|
||||||
|
var fallback dialResult
|
||||||
|
var err error
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("dual stack connect failed: %w", err)
|
||||||
|
case <-fallbackTicker.C:
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
|
if res.isPrimary {
|
||||||
|
return res.Conn, nil
|
||||||
|
}
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
err = res.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var ip netip.Addr
|
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
if ipv6 {
|
results := make(chan dialResult)
|
||||||
if !direct {
|
returned := make(chan struct{})
|
||||||
ip, result.error = resolver.ResolveIPv6ProxyServerHost(host)
|
defer close(returned)
|
||||||
} else {
|
tcpRacer := func(ctx context.Context, ip netip.Addr, port string) {
|
||||||
ip, result.error = resolver.ResolveIPv6(host)
|
result := dialResult{isPrimary: true}
|
||||||
}
|
defer func() {
|
||||||
} else {
|
select {
|
||||||
if !direct {
|
case results <- result:
|
||||||
ip, result.error = resolver.ResolveIPv4ProxyServerHost(host)
|
case <-returned:
|
||||||
} else {
|
if result.Conn != nil {
|
||||||
ip, result.error = resolver.ResolveIPv4(host)
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if result.error != nil {
|
}()
|
||||||
return
|
result.ip = ip
|
||||||
}
|
|
||||||
result.resolved = true
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
go startRacer(ctx, network+"4", host, opt.direct, false)
|
for _, ip := range ips {
|
||||||
go startRacer(ctx, network+"6", host, opt.direct, true)
|
go tcpRacer(ctx, ip, port)
|
||||||
|
}
|
||||||
count := 2
|
var err error
|
||||||
for i := 0; i < count; i++ {
|
for {
|
||||||
select {
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
|
return nil, ErrorConnTimeout
|
||||||
|
}
|
||||||
|
return nil, ctx.Err()
|
||||||
case res := <-results:
|
case res := <-results:
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
return res.Conn, nil
|
return res.Conn, nil
|
||||||
}
|
}
|
||||||
|
err = res.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !res.ipv6 {
|
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
primary = res
|
var (
|
||||||
|
conn net.Conn
|
||||||
|
err error
|
||||||
|
errs []error
|
||||||
|
)
|
||||||
|
for _, ip := range ips {
|
||||||
|
if conn, err = dialContext(ctx, network, ip, port, opt); err == nil {
|
||||||
|
return conn, nil
|
||||||
} else {
|
} else {
|
||||||
fallback = res
|
errs = append(errs, err)
|
||||||
}
|
|
||||||
|
|
||||||
if primary.done && fallback.done {
|
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
|
||||||
return nil, primary.error
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case <-ctx.Done():
|
return nil, errors.Join(errs...)
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return nil, errors.New("dual stack tcp shake hands failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDualStackDialContext(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
|
|
||||||
if opt.direct {
|
|
||||||
ips, err = resolver.ResolveAllIP(host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(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{})
|
|
||||||
defer close(returned)
|
|
||||||
|
|
||||||
type dialResult struct {
|
type dialResult struct {
|
||||||
ip netip.Addr
|
ip netip.Addr
|
||||||
net.Conn
|
net.Conn
|
||||||
error
|
error
|
||||||
isPrimary bool
|
isPrimary bool
|
||||||
done bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
preferCount := atomic.NewInt32(0)
|
func parseAddr(ctx context.Context, network, address string, preferResolver resolver.Resolver) ([]netip.Addr, string, error) {
|
||||||
results := make(chan dialResult)
|
|
||||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
result := dialResult{ip: ip, done: true}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
select {
|
|
||||||
case results <- result:
|
|
||||||
case <-returned:
|
|
||||||
if result.Conn != nil {
|
|
||||||
_ = 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, ip := range ips {
|
|
||||||
go tcpRacer(ctx, ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
connCount := len(ips)
|
|
||||||
var fallback dialResult
|
|
||||||
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 {
|
|
||||||
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
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
|
||||||
}
|
|
||||||
|
|
||||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, 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.direct {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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.direct {
|
switch network {
|
||||||
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
case "tcp4", "udp4":
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
||||||
} else {
|
} else {
|
||||||
ips, err = resolver.ResolveAllIPv4(host)
|
ips, err = resolver.LookupIPv4WithResolver(ctx, host, preferResolver)
|
||||||
}
|
}
|
||||||
|
case "tcp6", "udp6":
|
||||||
if err != nil {
|
if preferResolver == nil {
|
||||||
return nil, err
|
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
var ips []netip.Addr
|
|
||||||
if !opt.direct {
|
|
||||||
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
} else {
|
||||||
ips, err = resolver.ResolveAllIPv6(host)
|
ips, err = resolver.LookupIPv6WithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIP(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)
|
||||||
|
}
|
||||||
|
return ips, port, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
func sortationAddr(ips []netip.Addr) (ipv4s, ipv6s []netip.Addr) {
|
||||||
|
for _, v := range ips {
|
||||||
|
if v.Is4() || v.Is4In6() {
|
||||||
|
ipv4s = append(ipv4s, v)
|
||||||
|
} else {
|
||||||
|
ipv6s = append(ipv6s, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
@ -3,39 +3,35 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
||||||
dialer.Control = bindMarkToControl(mark, dialer.Control)
|
addControlToDialer(dialer, bindMarkToControl(mark))
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
||||||
lc.Control = bindMarkToControl(mark, lc.Control)
|
addControlToListenConfig(lc, bindMarkToControl(mark))
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindMarkToControl(mark int, chain controlFn) controlFn {
|
func bindMarkToControl(mark int) controlFn {
|
||||||
return func(network, address string, c syscall.RawConn) (err error) {
|
return func(ctx context.Context, 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
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
var innerErr error
|
||||||
switch network {
|
err = c.Control(func(fd uintptr) {
|
||||||
case "tcp4", "udp4":
|
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||||
_ = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
_ = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
if innerErr != nil {
|
||||||
|
err = innerErr
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -14,9 +16,10 @@ type option struct {
|
|||||||
interfaceName string
|
interfaceName string
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
direct bool
|
|
||||||
network int
|
network int
|
||||||
prefer int
|
prefer int
|
||||||
|
tfo bool
|
||||||
|
resolver resolver.Resolver
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -39,9 +42,9 @@ func WithRoutingMark(mark int) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithDirect() Option {
|
func WithResolver(r resolver.Resolver) Option {
|
||||||
return func(opt *option) {
|
return func(opt *option) {
|
||||||
opt.direct = true
|
opt.resolver = r
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,3 +69,15 @@ func WithOnlySingleStack(isIPv4 bool) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithTFO(tfo bool) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.tfo = tfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithOption(o option) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
*opt = o
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
@ -10,18 +11,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
chain := lc.Control
|
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
||||||
|
|
||||||
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil && chain != nil {
|
|
||||||
err = chain(network, address, c)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
return c.Control(func(fd uintptr) {
|
||||||
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
|
||||||
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
@ -8,17 +9,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
chain := lc.Control
|
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
||||||
|
|
||||||
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if err == nil && chain != nil {
|
|
||||||
err = chain(network, address, c)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
return c.Control(func(fd uintptr) {
|
||||||
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
119
component/dialer/tfo.go
Normal file
119
component/dialer/tfo.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/sagernet/tfo-go"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tfoConn struct {
|
||||||
|
net.Conn
|
||||||
|
closed bool
|
||||||
|
dialed chan bool
|
||||||
|
cancel context.CancelFunc
|
||||||
|
ctx context.Context
|
||||||
|
dialFn func(ctx context.Context, earlyData []byte) (net.Conn, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) Dial(earlyData []byte) (err error) {
|
||||||
|
c.Conn, err = c.dialFn(c.ctx, earlyData)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.dialed <- true
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) Read(b []byte) (n int, err error) {
|
||||||
|
if c.closed {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
if c.Conn == nil {
|
||||||
|
select {
|
||||||
|
case <-c.ctx.Done():
|
||||||
|
return 0, io.ErrUnexpectedEOF
|
||||||
|
case <-c.dialed:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c.Conn.Read(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) Write(b []byte) (n int, err error) {
|
||||||
|
if c.closed {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
if c.Conn == nil {
|
||||||
|
if err := c.Dial(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) Close() error {
|
||||||
|
c.closed = true
|
||||||
|
c.cancel()
|
||||||
|
if c.Conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) LocalAddr() net.Addr {
|
||||||
|
if c.Conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) RemoteAddr() net.Addr {
|
||||||
|
if c.Conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn.RemoteAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) SetDeadline(t time.Time) error {
|
||||||
|
if err := c.SetReadDeadline(t); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) SetReadDeadline(t time.Time) error {
|
||||||
|
if c.Conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
if c.Conn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *tfoConn) Upstream() any {
|
||||||
|
if c.Conn == nil { // ensure return a nil interface not an interface with nil value
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
||||||
|
return &tfoConn{
|
||||||
|
dialed: make(chan bool, 1),
|
||||||
|
cancel: cancel,
|
||||||
|
ctx: ctx,
|
||||||
|
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, address, earlyData)
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
@ -6,15 +6,38 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/vishvananda/netlink"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cmd"
|
"github.com/Dreamacro/clash/common/cmd"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/ebpf/redir"
|
"github.com/Dreamacro/clash/component/ebpf/redir"
|
||||||
"github.com/Dreamacro/clash/component/ebpf/tc"
|
"github.com/Dreamacro/clash/component/ebpf/tc"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/sagernet/netlink"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func GetAutoDetectInterface() (string, error) {
|
||||||
|
routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, route := range routes {
|
||||||
|
if route.Dst == nil {
|
||||||
|
lk, err := netlink.LinkByIndex(route.LinkIndex)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if lk.Type() == "tuntap" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return lk.Attrs().Name, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("interface not found")
|
||||||
|
}
|
||||||
|
|
||||||
// NewTcEBpfProgram new redirect to tun ebpf program
|
// NewTcEBpfProgram new redirect to tun ebpf program
|
||||||
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
||||||
tunIface, err := netlink.LinkByName(tunName)
|
tunIface, err := netlink.LinkByName(tunName)
|
||||||
|
@ -15,3 +15,7 @@ func NewTcEBpfProgram(_ []string, _ string) (*TcEBpfProgram, error) {
|
|||||||
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
||||||
return nil, fmt.Errorf("system not supported")
|
return nil, fmt.Errorf("system not supported")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetAutoDetectInterface() (string, error) {
|
||||||
|
return "", fmt.Errorf("system not supported")
|
||||||
|
}
|
||||||
|
@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
"github.com/cilium/ebpf"
|
"github.com/cilium/ebpf"
|
||||||
"github.com/cilium/ebpf/rlimit"
|
"github.com/cilium/ebpf/rlimit"
|
||||||
"github.com/vishvananda/netlink"
|
"github.com/sagernet/netlink"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
||||||
|
@ -134,5 +134,6 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
|
//
|
||||||
//go:embed bpf_bpfeb.o
|
//go:embed bpf_bpfeb.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -134,5 +134,6 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
|
//
|
||||||
//go:embed bpf_bpfel.o
|
//go:embed bpf_bpfel.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -115,5 +115,6 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
|
//
|
||||||
//go:embed bpf_bpfeb.o
|
//go:embed bpf_bpfeb.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -115,5 +115,6 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
|
//
|
||||||
//go:embed bpf_bpfel.o
|
//go:embed bpf_bpfel.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
|
|
||||||
"github.com/cilium/ebpf"
|
"github.com/cilium/ebpf"
|
||||||
"github.com/cilium/ebpf/rlimit"
|
"github.com/cilium/ebpf/rlimit"
|
||||||
"github.com/vishvananda/netlink"
|
"github.com/sagernet/netlink"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
@ -73,7 +73,7 @@ func (m *memoryStore) FlushFakeIP() error {
|
|||||||
|
|
||||||
func newMemoryStore(size int) *memoryStore {
|
func newMemoryStore(size int) *memoryStore {
|
||||||
return &memoryStore{
|
return &memoryStore{
|
||||||
cacheIP: cache.NewLRUCache[string, netip.Addr](cache.WithSize[string, netip.Addr](size)),
|
cacheIP: cache.New[string, netip.Addr](cache.WithSize[string, netip.Addr](size)),
|
||||||
cacheHost: cache.NewLRUCache[netip.Addr, string](cache.WithSize[netip.Addr, string](size)),
|
cacheHost: cache.New[netip.Addr, string](cache.WithSize[netip.Addr, string](size)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package fakeip
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
@ -26,7 +27,7 @@ type store interface {
|
|||||||
FlushFakeIP() error
|
FlushFakeIP() error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pool is a implementation about fake ip generator without storage
|
// Pool is an implementation about fake ip generator without storage
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
gateway netip.Addr
|
gateway netip.Addr
|
||||||
first netip.Addr
|
first netip.Addr
|
||||||
@ -34,7 +35,7 @@ type Pool struct {
|
|||||||
offset netip.Addr
|
offset netip.Addr
|
||||||
cycle bool
|
cycle bool
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
host *trie.DomainTrie[bool]
|
host *trie.DomainTrie[struct{}]
|
||||||
ipnet *netip.Prefix
|
ipnet *netip.Prefix
|
||||||
store store
|
store store
|
||||||
}
|
}
|
||||||
@ -43,6 +44,9 @@ type Pool struct {
|
|||||||
func (p *Pool) Lookup(host string) netip.Addr {
|
func (p *Pool) Lookup(host string) netip.Addr {
|
||||||
p.mux.Lock()
|
p.mux.Lock()
|
||||||
defer p.mux.Unlock()
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
|
// RFC4343: DNS Case Insensitive, we SHOULD return result with all cases.
|
||||||
|
host = strings.ToLower(host)
|
||||||
if ip, exist := p.store.GetByHost(host); exist {
|
if ip, exist := p.store.GetByHost(host); exist {
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
@ -150,7 +154,7 @@ func (p *Pool) restoreState() {
|
|||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
IPNet *netip.Prefix
|
IPNet *netip.Prefix
|
||||||
Host *trie.DomainTrie[bool]
|
Host *trie.DomainTrie[struct{}]
|
||||||
|
|
||||||
// Size sets the maximum number of entries in memory
|
// Size sets the maximum number of entries in memory
|
||||||
// and does not work if Persistence is true
|
// and does not work if Persistence is true
|
||||||
@ -166,7 +170,7 @@ func New(options Options) (*Pool, error) {
|
|||||||
var (
|
var (
|
||||||
hostAddr = options.IPNet.Masked().Addr()
|
hostAddr = options.IPNet.Masked().Addr()
|
||||||
gateway = hostAddr.Next()
|
gateway = hostAddr.Next()
|
||||||
first = gateway.Next().Next()
|
first = gateway.Next().Next().Next() // default start with 198.18.0.4
|
||||||
last = nnip.UnMasked(*options.IPNet)
|
last = nnip.UnMasked(*options.IPNet)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -62,16 +62,16 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
||||||
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 4})))
|
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
||||||
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 6})))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,20 +90,41 @@ func TestPool_BasicV6(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805"))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
||||||
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804")))
|
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8806")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPool_Case_Insensitive(t *testing.T) {
|
||||||
|
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
||||||
|
pools, tempfile, err := createPools(Options{
|
||||||
|
IPNet: &ipnet,
|
||||||
|
Size: 10,
|
||||||
|
})
|
||||||
|
assert.Nil(t, err)
|
||||||
|
defer os.Remove(tempfile)
|
||||||
|
|
||||||
|
for _, pool := range pools {
|
||||||
|
first := pool.Lookup("foo.com")
|
||||||
|
last := pool.Lookup("Foo.Com")
|
||||||
|
foo, exist := pool.LookBack(last)
|
||||||
|
|
||||||
|
assert.Equal(t, first, pool.Lookup("Foo.Com"))
|
||||||
|
assert.Equal(t, pool.Lookup("fOo.cOM"), first)
|
||||||
|
assert.True(t, exist)
|
||||||
|
assert.Equal(t, foo, "foo.com")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPool_CycleUsed(t *testing.T) {
|
func TestPool_CycleUsed(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.16/28")
|
ipnet := netip.MustParsePrefix("192.168.0.16/28")
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
@ -116,7 +137,7 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
for _, pool := range pools {
|
for _, pool := range pools {
|
||||||
foo := pool.Lookup("foo.com")
|
foo := pool.Lookup("foo.com")
|
||||||
bar := pool.Lookup("bar.com")
|
bar := pool.Lookup("bar.com")
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 9; i++ {
|
||||||
pool.Lookup(fmt.Sprintf("%d.com", i))
|
pool.Lookup(fmt.Sprintf("%d.com", i))
|
||||||
}
|
}
|
||||||
baz := pool.Lookup("baz.com")
|
baz := pool.Lookup("baz.com")
|
||||||
@ -128,8 +149,8 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_Skip(t *testing.T) {
|
func TestPool_Skip(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
||||||
tree := trie.New[bool]()
|
tree := trie.New[struct{}]()
|
||||||
tree.Insert("example.com", true)
|
tree.Insert("example.com", struct{}{})
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
Size: 10,
|
Size: 10,
|
||||||
@ -198,8 +219,8 @@ func TestPool_Clone(t *testing.T) {
|
|||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
||||||
|
|
||||||
newPool, _ := New(Options{
|
newPool, _ := New(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
|
@ -2,6 +2,7 @@ package geodata
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/mmdb"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"io"
|
"io"
|
||||||
@ -9,7 +10,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
var initFlag bool
|
var initGeoSite bool
|
||||||
|
var initGeoIP int
|
||||||
|
|
||||||
func InitGeoSite() error {
|
func InitGeoSite() error {
|
||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
@ -18,8 +20,9 @@ func InitGeoSite() error {
|
|||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
log.Infoln("Download GeoSite.dat finish")
|
log.Infoln("Download GeoSite.dat finish")
|
||||||
|
initGeoSite = false
|
||||||
}
|
}
|
||||||
if !initFlag {
|
if !initGeoSite {
|
||||||
if err := Verify(C.GeositeName); err != nil {
|
if err := Verify(C.GeositeName); err != nil {
|
||||||
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
||||||
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
||||||
@ -29,7 +32,7 @@ func InitGeoSite() error {
|
|||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
initFlag = true
|
initGeoSite = true
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -50,3 +53,68 @@ func downloadGeoSite(path string) (err error) {
|
|||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func downloadGeoIP(path string) (err error) {
|
||||||
|
resp, err := http.Get(C.GeoIpUrl)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitGeoIP() error {
|
||||||
|
if C.GeodataMode {
|
||||||
|
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find GeoIP.dat, start download")
|
||||||
|
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
log.Infoln("Download GeoIP.dat finish")
|
||||||
|
initGeoIP = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if initGeoIP != 1 {
|
||||||
|
if err := Verify(C.GeoipName); err != nil {
|
||||||
|
log.Warnln("GeoIP.dat invalid, remove and download: %s", err)
|
||||||
|
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initGeoIP = 1
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find MMDB, start download")
|
||||||
|
if err := mmdb.DownloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if initGeoIP != 2 {
|
||||||
|
if !mmdb.Verify() {
|
||||||
|
log.Warnln("MMDB invalid, remove and download")
|
||||||
|
if err := os.Remove(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := mmdb.DownloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
|
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initGeoIP = 2
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
@ -13,7 +13,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
UA = "Clash"
|
UA = "clash.meta"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||||
|
@ -2,6 +2,9 @@ package mmdb
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/oschwald/geoip2-golang"
|
"github.com/oschwald/geoip2-golang"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -42,3 +45,20 @@ func Instance() *geoip2.Reader {
|
|||||||
|
|
||||||
return mmdb
|
return mmdb
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func DownloadMMDB(path string) (err error) {
|
||||||
|
resp, err := http.Get(C.MmdbUrl)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package nat
|
package nat
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -10,16 +11,24 @@ type Table struct {
|
|||||||
mapping sync.Map
|
mapping sync.Map
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Table) Set(key string, pc C.PacketConn) {
|
type Entry struct {
|
||||||
t.mapping.Store(key, pc)
|
PacketConn C.PacketConn
|
||||||
|
LocalUDPConnMap sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) Set(key string, e C.PacketConn) {
|
||||||
|
t.mapping.Store(key, &Entry{
|
||||||
|
PacketConn: e,
|
||||||
|
LocalUDPConnMap: sync.Map{},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Table) Get(key string) C.PacketConn {
|
func (t *Table) Get(key string) C.PacketConn {
|
||||||
item, exist := t.mapping.Load(key)
|
entry, exist := t.getEntry(key)
|
||||||
if !exist {
|
if !exist {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return item.(C.PacketConn)
|
return entry.PacketConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Table) GetOrCreateLock(key string) (*sync.Cond, bool) {
|
func (t *Table) GetOrCreateLock(key string) (*sync.Cond, bool) {
|
||||||
@ -31,6 +40,62 @@ func (t *Table) Delete(key string) {
|
|||||||
t.mapping.Delete(key)
|
t.mapping.Delete(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Table) GetLocalConn(lAddr, rAddr string) *net.UDPConn {
|
||||||
|
entry, exist := t.getEntry(lAddr)
|
||||||
|
if !exist {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
item, exist := entry.LocalUDPConnMap.Load(rAddr)
|
||||||
|
if !exist {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return item.(*net.UDPConn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) AddLocalConn(lAddr, rAddr string, conn *net.UDPConn) bool {
|
||||||
|
entry, exist := t.getEntry(lAddr)
|
||||||
|
if !exist {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
entry.LocalUDPConnMap.Store(rAddr, conn)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) RangeLocalConn(lAddr string, f func(key, value any) bool) {
|
||||||
|
entry, exist := t.getEntry(lAddr)
|
||||||
|
if !exist {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry.LocalUDPConnMap.Range(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) GetOrCreateLockForLocalConn(lAddr, key string) (*sync.Cond, bool) {
|
||||||
|
entry, loaded := t.getEntry(lAddr)
|
||||||
|
if !loaded {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
item, loaded := entry.LocalUDPConnMap.LoadOrStore(key, sync.NewCond(&sync.Mutex{}))
|
||||||
|
return item.(*sync.Cond), loaded
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) DeleteLocalConnMap(lAddr, key string) {
|
||||||
|
entry, loaded := t.getEntry(lAddr)
|
||||||
|
if !loaded {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry.LocalUDPConnMap.Delete(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Table) getEntry(key string) (*Entry, bool) {
|
||||||
|
item, ok := t.mapping.Load(key)
|
||||||
|
// This should not happen usually since this function called after PacketConn created
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
entry, ok := item.(*Entry)
|
||||||
|
return entry, ok
|
||||||
|
}
|
||||||
|
|
||||||
// New return *Cache
|
// New return *Cache
|
||||||
func New() *Table {
|
func New() *Table {
|
||||||
return &Table{}
|
return &Table{}
|
||||||
|
57
component/process/find_process_mode.go
Normal file
57
component/process/find_process_mode.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
FindProcessAlways = "always"
|
||||||
|
FindProcessStrict = "strict"
|
||||||
|
FindProcessOff = "off"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
validModes = map[string]struct{}{
|
||||||
|
FindProcessAlways: {},
|
||||||
|
FindProcessOff: {},
|
||||||
|
FindProcessStrict: {},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
type FindProcessMode string
|
||||||
|
|
||||||
|
func (m FindProcessMode) Always() bool {
|
||||||
|
return m == FindProcessAlways
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m FindProcessMode) Off() bool {
|
||||||
|
return m == FindProcessOff
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *FindProcessMode) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var tp string
|
||||||
|
if err := unmarshal(&tp); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.Set(tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *FindProcessMode) UnmarshalJSON(data []byte) error {
|
||||||
|
var tp string
|
||||||
|
if err := json.Unmarshal(data, &tp); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return m.Set(tp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *FindProcessMode) Set(value string) error {
|
||||||
|
mode := strings.ToLower(value)
|
||||||
|
_, exist := validModes[mode]
|
||||||
|
if !exist {
|
||||||
|
return errors.New("invalid find process mode")
|
||||||
|
}
|
||||||
|
*m = FindProcessMode(mode)
|
||||||
|
return nil
|
||||||
|
}
|
@ -16,14 +16,6 @@ const (
|
|||||||
UDP = "udp"
|
UDP = "udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
|
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessName(network, srcIP, srcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func FindUid(network string, srcIP netip.Addr, srcPort int) (int32, error) {
|
|
||||||
_, uid, err := resolveSocketByNetlink(network, srcIP, srcPort)
|
|
||||||
if err != nil {
|
|
||||||
return -1, err
|
|
||||||
}
|
|
||||||
return uid, nil
|
|
||||||
}
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user