Compare commits
286 Commits
Author | SHA1 | Date | |
---|---|---|---|
9b7aab1fc7 | |||
3c717097cb | |||
991de009be | |||
2fef329319 | |||
db7623968d | |||
7c80c88feb | |||
2c7153cd7a | |||
d730feecb4 | |||
1fdd1f702e | |||
34c91e5fe0 | |||
6d40de2179 | |||
6ca14c814e | |||
545cbeeec0 | |||
431dcfa914 | |||
4d30788738 | |||
e4364cc985 | |||
99ede63a9a | |||
291b5be986 | |||
a7944f1369 | |||
7e10d78d53 | |||
fd0580bfdd | |||
5737fbc23c | |||
e026ac6a2a | |||
e7bb1f42b1 | |||
a22000c41b | |||
0336435ebc | |||
154fbb34ea | |||
3e47bfacf0 | |||
9316c1293e | |||
f6f02bb5eb | |||
84967ace53 | |||
c7362fce9c | |||
8cb67b6480 | |||
3ae4285702 | |||
998d407d44 | |||
520cc807d6 | |||
7404bfdc44 | |||
e8d4f8ae7b | |||
f7610ce2ad | |||
516c219580 | |||
5d0efb5472 | |||
9d9bd245f3 | |||
53928eb895 | |||
8dda9fdb70 | |||
cf7520ec22 | |||
68d7a6da7f | |||
09c53e7cb7 | |||
0f24c2f849 | |||
88116d9032 | |||
6ba82c6d85 | |||
5816dc2955 | |||
f4251e58a5 | |||
2fef00d2a8 | |||
2f992e9863 | |||
13111081be | |||
5de043acc6 | |||
7d230139a0 | |||
0a6c848c9e | |||
074fee2b48 | |||
7f588935ea | |||
4b72ae7aab | |||
09b4a7ff15 | |||
7944522188 | |||
ae4d114802 | |||
07f3cd2ae5 | |||
035d878a9f | |||
913ed62095 | |||
8c135e4a91 | |||
5bcfe1a6c6 | |||
2ccef31f75 | |||
2c4783ff8b | |||
7cc1c1b561 | |||
d309c6311d | |||
e7f9072911 | |||
fe298bd53f | |||
6fe7f4641e | |||
9ae0bd9c2b | |||
dca98b7aa1 | |||
c0fc5d142f | |||
a973a6c7d2 | |||
a454a7f736 | |||
bae61a8152 | |||
0c984644b4 | |||
921b2c3aa4 | |||
8ba7ce73d8 | |||
76a8fe3839 | |||
1e6f0f28f6 | |||
6040803b60 | |||
04ae812a11 | |||
a0ad12c45b | |||
9cc7fdaca9 | |||
545a79d406 | |||
7c34964f87 | |||
6a97ab9ecb | |||
ad6336231c | |||
2f36c9d66d | |||
ae966833a4 | |||
3b037acb01 | |||
8771fa5c17 | |||
bccc6aa8d1 | |||
da27be6de5 | |||
838c5c7770 | |||
02395413ba | |||
4c1682b365 | |||
e7613e4f8b | |||
685fd49dd7 | |||
6061f3d4fa | |||
d55025ecae | |||
e3e0e9796b | |||
ecb2a5f3c6 | |||
76ccebf099 | |||
78100aa963 | |||
0b56fc7598 | |||
c1199f1a8a | |||
c8c078e78a | |||
d36f9c2ac8 | |||
e1dd4ac9e7 | |||
e6a35199e0 | |||
3cd1c92162 | |||
be5ce6249f | |||
0321fe93cf | |||
2cbfac2c89 | |||
0a6705f43e | |||
97e14337e3 | |||
5e7d644efd | |||
40ae019e1d | |||
efbde4a179 | |||
f565edd76d | |||
a3b8c9c233 | |||
de92bc0234 | |||
e6377eac9b | |||
22726c1de8 | |||
bce3aeb218 | |||
81722610d5 | |||
5bfad04b41 | |||
880664c6ab | |||
8f0c61ed14 | |||
7d524668e0 | |||
75680c5866 | |||
a1d008e6f0 | |||
d5d62a4ffd | |||
b72bd5bb37 | |||
7fecd20a1d | |||
f586f22ce3 | |||
21848d6bf1 | |||
28c57c4144 | |||
4a6ebff473 | |||
5c8d955f61 | |||
baaf509637 | |||
db3e1b9ed5 | |||
1a1e3345f4 | |||
8293b7fdae | |||
0ba415866e | |||
527fc2790b | |||
cd7d9fc4f5 | |||
a61685ce01 | |||
b9e63d3f7d | |||
cc3a9dd553 | |||
6a89cc15c3 | |||
fc50392ec7 | |||
59cd89a9c9 | |||
d6ff5f7d96 | |||
8e4dfbd10d | |||
b2d1cea759 | |||
6fe1766c83 | |||
e59c35a308 | |||
b50071ed37 | |||
28c7de6185 | |||
6fb4ebba15 | |||
d00d83abd4 | |||
e6d16e458f | |||
ae42d35184 | |||
ce8929d153 | |||
cc2a775271 | |||
83d719cf79 | |||
4643b5835e | |||
a991bf9045 | |||
3fd3d83029 | |||
24419551a9 | |||
c83eb2e0c9 | |||
929b1675e3 | |||
db54b438e6 | |||
967254d9ca | |||
2d806df9b9 | |||
4fe798ec3b | |||
3555ff5f4e | |||
05ca819823 | |||
c8b8b60b93 | |||
287986d524 | |||
4c25f5e73b | |||
cbc217e80a | |||
fe348e89c5 | |||
e1e1984d3e | |||
99662b616f | |||
857d6e419f | |||
a298b9ea01 | |||
61097d0826 | |||
2ee0f634e6 | |||
61b3b4f775 | |||
dc4b9753d3 | |||
f1ef6c2096 | |||
872c915cf7 | |||
fb9f09c97f | |||
884db8a8b5 | |||
53b41ca166 | |||
ee21b7bc37 | |||
32c53b9584 | |||
4e5f3fbe84 | |||
2ce193877b | |||
e52d599326 | |||
2cf66f41cb | |||
a06b387acc | |||
03520e0d6f | |||
a6a72a5b54 | |||
85db58aeb5 | |||
596bf32caa | |||
2b2644a76f | |||
02684a868f | |||
1924b308fd | |||
0d62e42c50 | |||
d3193cf8b7 | |||
f7538568c0 | |||
4629ecb8ee | |||
5bcea37d59 | |||
6decaef050 | |||
248578086f | |||
87553c6aa0 | |||
a2aa267e43 | |||
a563e9375e | |||
9a4be1fbec | |||
80f48518ca | |||
16c4b55e31 | |||
023a96a6d3 | |||
39394e49ae | |||
b54ddc3aa9 | |||
97537bd185 | |||
1225173a43 | |||
096bb8d439 | |||
df1f6e2b99 | |||
d1f5bef25d | |||
d426db43ec | |||
3bace07948 | |||
24e31d0a40 | |||
fb623c0929 | |||
4f641ce12d | |||
8cd1e40fb3 | |||
8a7027e8d6 | |||
5bbf73e3b5 | |||
106a58779d | |||
fa5b5ca02d | |||
ba6163574e | |||
37eca8af24 | |||
421c91a58c | |||
c90bf1c6e2 | |||
5b1de296af | |||
f4414566d3 | |||
db4f3eda55 | |||
f3b76df13b | |||
bb79272020 | |||
926ef9e33d | |||
ead21f37d7 | |||
49a2602329 | |||
e88bddc24f | |||
a5821e5785 | |||
4e4d741075 | |||
bec66e9e69 | |||
50832aab47 | |||
643fdd0bce | |||
d1565bb46f | |||
8fa66c13a9 | |||
c0ffa06b95 | |||
3b53f5bca3 | |||
2c80155c6f | |||
8a9b3b3d59 | |||
5dd691aa95 | |||
27ceae580a | |||
b6b6413d04 | |||
2095f4f670 | |||
606e8948c0 | |||
3b6fc1c496 | |||
f96bf65557 | |||
804cff8c55 | |||
8a75f78e63 | |||
d9692c6366 | |||
f4b0062dfc | |||
633b9c0426 |
26
.github/release.sh
vendored
Normal file
26
.github/release.sh
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
||||||
|
gzip -S ".gz" $FILENAME
|
||||||
|
elif [[ $FILENAME =~ ".exe" ]];then
|
||||||
|
zip -m ${FILENAME%.*}.zip $FILENAME
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ ".zip" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.zip
|
||||||
|
elif [[ $FILENAME =~ ".gz" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.gz
|
||||||
|
else
|
||||||
|
echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
35
.github/rename-cgo.sh
vendored
Normal file
35
.github/rename-cgo.sh
vendored
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||||
|
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-darwin-arm64-cgo
|
||||||
|
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||||
|
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-darwin-amd64-cgo
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||||
|
echo "rename windows 386 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-windows-386-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
|
echo "rename windows amd64 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-5" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv5-cgo
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv6-cgo
|
||||||
|
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
||||||
|
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
||||||
|
mv $FILENAME clash.meta-linux-armv7-cgo
|
||||||
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
|
echo "rename linux $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
elif [[ $FILENAME =~ "android" ]];then
|
||||||
|
echo "rename android $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
16
.github/workflows/Delete.yml
vendored
Normal file
16
.github/workflows/Delete.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
name: Delete old workflow runs
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 1 * *'
|
||||||
|
# Run monthly, at 00:00 on the 1st day of month.
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
del_runs:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Delete workflow runs
|
||||||
|
uses: GitRML/delete-workflow-runs@main
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.AUTH_PAT }}
|
||||||
|
repository: ${{ github.repository }}
|
||||||
|
retain_days: 30
|
22
.github/workflows/build.yaml
vendored
22
.github/workflows/build.yaml
vendored
@ -1,22 +0,0 @@
|
|||||||
name: Build All
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
- name: Build
|
|
||||||
run: make all
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
357
.github/workflows/build.yml
vendored
Normal file
357
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,357 @@
|
|||||||
|
name: Build
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
- Meta
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request_target:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
- Meta
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.ref }}-${{ github.workflow }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
permissions: write-all
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
job:
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-amd64 linux-amd64-compatible",
|
||||||
|
id: "1",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-armv5 linux-armv6 linux-armv7",
|
||||||
|
id: "2",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-arm64 linux-mips64 linux-mips64le",
|
||||||
|
id: "3",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||||
|
id: "4",
|
||||||
|
}
|
||||||
|
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
|
id: "6",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
|
id: "7",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "windows-arm64 windows-arm32v7",
|
||||||
|
id: "8",
|
||||||
|
}
|
||||||
|
- {
|
||||||
|
type: "WithoutCGO",
|
||||||
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
|
id: "9",
|
||||||
|
}
|
||||||
|
- { type: "WithCGO", target: "windows/*", id: "1" }
|
||||||
|
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||||
|
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
||||||
|
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
||||||
|
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
||||||
|
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
||||||
|
- { type: "WithCGO", target: "android", id: "11" }
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Alpha'}}
|
||||||
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Beta'}}
|
||||||
|
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='Meta'}}
|
||||||
|
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
||||||
|
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set ENV
|
||||||
|
run: |
|
||||||
|
sudo timedatectl set-timezone "Asia/Shanghai"
|
||||||
|
echo "NAME=clash.meta" >> $GITHUB_ENV
|
||||||
|
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||||
|
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
||||||
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
|
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Set ENV
|
||||||
|
run: |
|
||||||
|
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
||||||
|
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@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 ..
|
||||||
|
|
||||||
|
- name: Save version
|
||||||
|
run: echo ${VERSION} > bin/version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
Upload-Prerelease:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.ref_type=='branch' }}
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- name: Set Env
|
||||||
|
run: |
|
||||||
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
cat > release.txt << 'EOF'
|
||||||
|
Release created at ${{ env.BUILDTIME }}
|
||||||
|
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||||
|
<br>
|
||||||
|
### release version
|
||||||
|
`default(not specified in file name)`: compiled with GOAMD64=v3
|
||||||
|
`cgo`: support lwip tun stack, compiled with GOAMD64=v1
|
||||||
|
`compatible`: compiled with GOAMD64=v1
|
||||||
|
Check details between different architectural levels [here](https://github.com/golang/go/wiki/MinimumRequirements#amd64).
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- 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
|
||||||
|
body_path: release.txt
|
||||||
|
|
||||||
|
Upload-Release:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.ref_type=='tag' }}
|
||||||
|
needs: [Build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: artifact
|
||||||
|
path: bin/
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag: ${{ 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
|
||||||
|
linux/arm/v7
|
||||||
|
# linux/riscv64
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
16
.github/workflows/delete.yml
vendored
Normal file
16
.github/workflows/delete.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
name: Delete old workflow runs
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 1 * *'
|
||||||
|
# Run monthly, at 00:00 on the 1st day of month.
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
del_runs:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Delete workflow runs
|
||||||
|
uses: GitRML/delete-workflow-runs@main
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.AUTH_PAT }}
|
||||||
|
repository: ${{ github.repository }}
|
||||||
|
retain_days: 30
|
61
.github/workflows/docker.yaml
vendored
61
.github/workflows/docker.yaml
vendored
@ -1,61 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Beta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
61
.github/workflows/prerelease.yml
vendored
61
.github/workflows/prerelease.yml
vendored
@ -1,61 +0,0 @@
|
|||||||
name: Prerelease
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: mknejp/delete-release-assets@v1
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
assets: |
|
|
||||||
*.zip
|
|
||||||
*.gz
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Alpha
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
36
.github/workflows/release.yaml
vendored
36
.github/workflows/release.yaml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: '1.19'
|
|
||||||
check-latest: true
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -24,4 +24,5 @@ vendor
|
|||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
/output
|
||||||
/.vscode
|
.vscode/
|
||||||
|
.fleet/
|
21
Dockerfile
21
Dockerfile
@ -1,18 +1,19 @@
|
|||||||
FROM golang:alpine as builder
|
FROM alpine:latest as builder
|
||||||
|
ARG TARGETPLATFORM
|
||||||
|
RUN echo "I'm building for $TARGETPLATFORM"
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /clash-config && \
|
mkdir /clash-config && \
|
||||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
|
|
||||||
|
COPY docker/file-name.sh /clash/file-name.sh
|
||||||
COPY . /clash-src
|
WORKDIR /clash
|
||||||
WORKDIR /clash-src
|
COPY bin/ bin/
|
||||||
RUN go mod download &&\
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
make docker &&\
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
||||||
mv ./bin/Clash.Meta-docker /clash
|
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
|
||||||
@ -21,6 +22,6 @@ RUN apk add --no-cache ca-certificates tzdata iptables
|
|||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
COPY --from=builder /clash /clash
|
COPY --from=builder /clash/clash /clash
|
||||||
RUN chmod +x /clash
|
RUN chmod +x /clash
|
||||||
ENTRYPOINT [ "/clash" ]
|
ENTRYPOINT [ "/clash" ]
|
||||||
|
14
Makefile
14
Makefile
@ -47,14 +47,17 @@ all:linux-amd64 linux-arm64\
|
|||||||
darwin-amd64 darwin-arm64\
|
darwin-amd64 darwin-arm64\
|
||||||
windows-amd64 windows-arm64\
|
windows-amd64 windows-arm64\
|
||||||
|
|
||||||
|
|
||||||
|
darwin-all: darwin-amd64 darwin-arm64
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64-compatible:
|
darwin-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -66,7 +69,7 @@ linux-amd64:
|
|||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64-compatible:
|
linux-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -98,6 +101,9 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-riscv64:
|
||||||
|
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
android-arm64:
|
android-arm64:
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -117,7 +123,7 @@ windows-amd64:
|
|||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64-compatible:
|
windows-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
89
README.md
89
README.md
@ -29,32 +29,41 @@
|
|||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Getting Started
|
## Wiki
|
||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
Configuration examples can be found at [/docs/config.yaml](https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml), while documentation can be found [Clash.Meta Wiki](https://clash-meta.wiki).
|
||||||
|
|
||||||
## Advanced usage for this branch
|
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
You should install [golang](https://go.dev) first.
|
You should install [golang](https://go.dev) first.
|
||||||
|
|
||||||
Then get the source code of Clash.Meta:
|
Then get the source code of Clash.Meta:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||||
cd Clash.Meta && go mod download
|
cd Clash.Meta && go mod download
|
||||||
```
|
```
|
||||||
|
|
||||||
If you can't visit github,you should set proxy first:
|
If you can't visit github,you should set proxy first:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
```
|
```
|
||||||
|
|
||||||
So now you can build it:
|
Now you can build it:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go build
|
go build
|
||||||
```
|
```
|
||||||
|
|
||||||
### DNS configuration
|
If you need gvisor for tun stack, build with:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go build -tags with_gvisor
|
||||||
|
```
|
||||||
|
|
||||||
|
<!-- ## Advanced usage of this fork -->
|
||||||
|
|
||||||
|
<!-- ### DNS configuration
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
@ -64,7 +73,6 @@ Support resolve ip with a `Proxy Tunnel`.
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: DNS
|
- name: DNS
|
||||||
type: url-test
|
type: url-test
|
||||||
use:
|
use:
|
||||||
@ -73,6 +81,7 @@ proxy-groups:
|
|||||||
interval: 180
|
interval: 180
|
||||||
lazy: true
|
lazy: true
|
||||||
```
|
```
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
@ -88,12 +97,12 @@ dns:
|
|||||||
- https://doh.pub/dns-query
|
- https://doh.pub/dns-query
|
||||||
- tls://223.5.5.5:853
|
- tls://223.5.5.5:853
|
||||||
fallback:
|
fallback:
|
||||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
- "https://1.0.0.1/dns-query#DNS" # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||||
- 'tls://8.8.4.4:853#DNS'
|
- "tls://8.8.4.4:853#DNS"
|
||||||
fallback-filter:
|
fallback-filter:
|
||||||
geoip: false
|
geoip: false
|
||||||
geosite:
|
geosite:
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||||
domain:
|
domain:
|
||||||
- +.example.com
|
- +.example.com
|
||||||
ipcidr:
|
ipcidr:
|
||||||
@ -110,21 +119,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
|
||||||
@ -153,7 +164,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)
|
||||||
@ -162,18 +172,17 @@ Support `Policy Group Filter`
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: 🚀 HK Group
|
- name: 🚀 HK Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: 'HK'
|
filter: "HK"
|
||||||
|
|
||||||
- name: 🚀 US Group
|
- name: 🚀 US Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: 'US'
|
filter: "US"
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
ALL:
|
ALL:
|
||||||
@ -185,14 +194,12 @@ proxy-providers:
|
|||||||
enable: true
|
enable: true
|
||||||
interval: 600
|
interval: 600
|
||||||
url: http://www.gstatic.com/generate_204
|
url: http://www.gstatic.com/generate_204
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
Support outbound transport protocol `VLESS`.
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "vless"
|
- name: "vless"
|
||||||
@ -232,8 +239,8 @@ proxies:
|
|||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `Wireguard`
|
Support outbound transport protocol `Wireguard`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "wg"
|
- name: "wg"
|
||||||
@ -248,6 +255,7 @@ proxies:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `Tuic`
|
Support outbound transport protocol `Tuic`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "tuic"
|
- name: "tuic"
|
||||||
@ -266,11 +274,11 @@ proxies:
|
|||||||
# max-udp-relay-packet-size: 1500
|
# max-udp-relay-packet-size: 1500
|
||||||
# fast-open: true
|
# fast-open: true
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
|
``` -->
|
||||||
```
|
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
Work on Linux OS who's supported `iptables`
|
|
||||||
|
Work on Linux OS which supported `iptables`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@ -281,17 +289,15 @@ iptables:
|
|||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### General installation guide for Linux
|
### General installation guide for Linux
|
||||||
+ Create user given name `clash-meta`
|
|
||||||
|
|
||||||
+ 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.
|
||||||
|
|
||||||
@ -317,10 +323,13 @@ ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ systemctl enable Clash-Meta
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
@ -331,23 +340,29 @@ $ systemctl start Clash-Meta
|
|||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
|
|
||||||
To display process name in GUI please use [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
To display process name in GUI please use [Razord-meta](https://github.com/MetaCubeX/Razord-meta).
|
||||||
|
|
||||||

|
### Dashboard
|
||||||
|
|
||||||
|
We also made a custom fork of yacd provide better support for this project, check it out at [Yacd-meta](https://github.com/MetaCubeX/Yacd-meta)
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
If you want to build an application that uses clash as a library, check out the
|
If you want to build an application that uses clash as a library, check out the
|
||||||
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
||||||
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
* [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -92,6 +92,7 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
mapping["tfo"] = p.SupportTFO()
|
mapping["tfo"] = p.SupportTFO()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
@ -16,11 +16,11 @@ func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Ad
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
if ip, port, err := parseAddr(source); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@ func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *cont
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/database64128/tfo-go/v2"
|
"github.com/sagernet/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -24,12 +24,12 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
if ip, port, err := parseAddr(p.InAddr().String()); err == nil {
|
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -18,22 +18,13 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
|||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
remoteAddr := conn.RemoteAddr()
|
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
// Filter when net.Addr interface is nil
|
metadata.SrcPort = port
|
||||||
if remoteAddr != nil {
|
|
||||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
localAddr := conn.LocalAddr()
|
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||||
// Filter when net.Addr interface is nil
|
metadata.InIP = ip
|
||||||
if localAddr != nil {
|
metadata.InPort = port
|
||||||
if ip, port, err := parseAddr(localAddr.String()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
@ -43,7 +34,7 @@ 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.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 {
|
||||||
@ -51,6 +42,8 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|||||||
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
|
||||||
|
} else {
|
||||||
|
metadata.Host = h
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -57,8 +58,19 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr string) (netip.Addr, string, error) {
|
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||||
host, port, err := net.SplitHostPort(addr)
|
// Filter when net.Addr interface is nil
|
||||||
|
if addr == nil {
|
||||||
|
return netip.Addr{}, "", errors.New("nil addr")
|
||||||
|
}
|
||||||
|
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
||||||
|
ip, port, err := parseAddr(rawAddr.RawAddr())
|
||||||
|
if err == nil {
|
||||||
|
return ip, port, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addrStr := addr.String()
|
||||||
|
host, port, err := net.SplitHostPort(addrStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return netip.Addr{}, "", err
|
return netip.Addr{}, "", err
|
||||||
}
|
}
|
||||||
|
@ -4,10 +4,11 @@ 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/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -18,6 +19,7 @@ type Base struct {
|
|||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
|
xudp bool
|
||||||
tfo bool
|
tfo bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
@ -32,12 +34,7 @@ func (b *Base) Name() string {
|
|||||||
// Id implements C.ProxyAdapter
|
// Id implements C.ProxyAdapter
|
||||||
func (b *Base) Id() string {
|
func (b *Base) Id() string {
|
||||||
if b.id == "" {
|
if b.id == "" {
|
||||||
id, err := uuid.NewV6()
|
b.id = utils.NewUUIDV6().String()
|
||||||
if err != nil {
|
|
||||||
b.id = b.name
|
|
||||||
} else {
|
|
||||||
b.id = id.String()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return b.id
|
return b.id
|
||||||
@ -87,6 +84,11 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SupportXUDP implements C.ProxyAdapter
|
||||||
|
func (b *Base) SupportXUDP() bool {
|
||||||
|
return b.xudp
|
||||||
|
}
|
||||||
|
|
||||||
// SupportTFO implements C.ProxyAdapter
|
// SupportTFO implements C.ProxyAdapter
|
||||||
func (b *Base) SupportTFO() bool {
|
func (b *Base) SupportTFO() bool {
|
||||||
return b.tfo
|
return b.tfo
|
||||||
@ -132,10 +134,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"`
|
||||||
@ -146,6 +153,7 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
|
XUDP bool
|
||||||
TFO bool
|
TFO bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
@ -158,6 +166,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
|
xudp: opt.XUDP,
|
||||||
tfo: opt.TFO,
|
tfo: opt.TFO,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
@ -166,7 +175,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
N.ExtendedConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
@ -185,13 +194,19 @@ 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 {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
adapterName string
|
||||||
|
connID string
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,8 +224,13 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) LocalAddr() net.Addr {
|
||||||
|
lAddr := c.PacketConn.LocalAddr()
|
||||||
|
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
||||||
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
return &packetConn{pc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
|
@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -150,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,
|
||||||
})
|
})
|
||||||
@ -170,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),
|
||||||
|
@ -178,7 +178,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
|
35
adapter/outbound/reality.go
Normal file
35
adapter/outbound/reality.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/curve25519"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RealityOptions struct {
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
ShortID string `proxy:"short-id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
||||||
|
if o.PublicKey != "" {
|
||||||
|
config := new(tlsC.RealityConfig)
|
||||||
|
|
||||||
|
n, err := base64.RawURLEncoding.Decode(config.PublicKey[:], []byte(o.PublicKey))
|
||||||
|
if err != nil || n != curve25519.ScalarSize {
|
||||||
|
return nil, errors.New("invalid REALITY public key")
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
||||||
|
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
||||||
|
return nil, errors.New("invalid REALITY short ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
@ -6,6 +6,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/buf"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -16,12 +17,12 @@ type Reject struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
return NewConn(&nopConn{}, r), nil
|
return NewConn(nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return newPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
@ -48,27 +49,37 @@ func NewPass() *Reject {
|
|||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw *nopConn) Read(b []byte) (int, error) {
|
func (rw nopConn) Read(b []byte) (int, error) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw *nopConn) Write(b []byte) (int, error) {
|
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw nopConn) Write(b []byte) (int, error) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw *nopConn) Close() error { return nil }
|
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
return io.EOF
|
||||||
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
|
}
|
||||||
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
|
func (rw nopConn) Close() error { return nil }
|
||||||
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
|
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||||
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
func (npc *nopPacketConn) Close() error { return nil }
|
func (npc nopPacketConn) Close() error { return nil }
|
||||||
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||||
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
@ -2,21 +2,23 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/shadowtls"
|
"github.com/Dreamacro/clash/transport/restls"
|
||||||
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"
|
||||||
|
|
||||||
|
restlsC "github.com/3andne/restls-client-go"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
@ -33,21 +35,23 @@ type ShadowSocks struct {
|
|||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
shadowTLSOption *shadowTLSOption
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
tlsConfig *tls.Config
|
restlsConfig *restlsC.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
||||||
|
UDPOverTCPVersion int `proxy:"udp-over-tcp-version,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -71,10 +75,26 @@ type shadowTLSOption struct {
|
|||||||
Host string `obfs:"host"`
|
Host string `obfs:"host"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Version int `obfs:"version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type restlsOption struct {
|
||||||
|
Password string `obfs:"password"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
VersionHint string `obfs:"version-hint"`
|
||||||
|
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
|
// fix tls handshake not timeout
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return ss.StreamConnContext(ctx, c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
useEarly := false
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -88,12 +108,34 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
case shadowtls.Mode:
|
case shadowtls.Mode:
|
||||||
c = shadowtls.NewShadowTLS(c, ss.shadowTLSOption.Password, ss.tlsConfig)
|
var err error
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
|
case restls.Mode:
|
||||||
|
var err error
|
||||||
|
c, err = restls.NewRestls(ctx, c, ss.restlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
}
|
}
|
||||||
|
useEarly = useEarly || N.NeedHandshake(c)
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
uotDestination := uot.RequestDestination(uint8(ss.option.UDPOverTCPVersion))
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, uotDestination), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, uotDestination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -113,7 +155,7 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,7 +171,12 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
destination := M.ParseSocksaddr(metadata.RemoteAddress())
|
||||||
|
if ss.option.UDPOverTCPVersion == 1 {
|
||||||
|
return newPacketConn(uot.NewConn(tcpConn, uot.Request{Destination: destination}), ss), nil
|
||||||
|
} else {
|
||||||
|
return newPacketConn(uot.NewLazyConn(tcpConn, uot.Request{Destination: destination}), ss), nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -152,7 +199,12 @@ func (ss *ShadowSocks) SupportWithDialer() bool {
|
|||||||
// 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 {
|
||||||
return newPacketConn(uot.NewClientConn(c), ss), nil
|
destination := M.ParseSocksaddr(metadata.RemoteAddress())
|
||||||
|
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||||
|
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
|
} else {
|
||||||
|
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
@ -164,15 +216,15 @@ func (ss *ShadowSocks) SupportUOT() bool {
|
|||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password, time.Now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
var shadowTLSOpt *shadowTLSOption
|
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||||
var tlsConfig *tls.Config
|
var restlsConfig *restlsC.Config
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -210,25 +262,41 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
obfsMode = shadowtls.Mode
|
obfsMode = shadowtls.Mode
|
||||||
shadowTLSOpt = &shadowTLSOption{}
|
opt := &shadowTLSOption{
|
||||||
if err := decoder.Decode(option.PluginOpts, shadowTLSOpt); err != nil {
|
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)
|
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig = &tls.Config{
|
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
||||||
NextProtos: shadowtls.DefaultALPN,
|
Password: opt.Password,
|
||||||
MinVersion: tls.VersionTLS12,
|
Host: opt.Host,
|
||||||
InsecureSkipVerify: shadowTLSOpt.SkipCertVerify,
|
Fingerprint: opt.Fingerprint,
|
||||||
ServerName: shadowTLSOpt.Host,
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
|
Version: opt.Version,
|
||||||
|
}
|
||||||
|
} else if option.Plugin == restls.Mode {
|
||||||
|
obfsMode = restls.Mode
|
||||||
|
restlsOpt := &restlsOption{}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, restlsOpt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(shadowTLSOpt.Fingerprint) == 0 {
|
restlsConfig, err = restlsC.NewRestlsConfig(restlsOpt.Host, restlsOpt.Password, restlsOpt.VersionHint, restlsOpt.RestlsScript, option.ClientFingerprint)
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
restlsConfig.SessionTicketsDisabled = true
|
||||||
} else {
|
if err != nil {
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, shadowTLSOpt.Fingerprint); err != nil {
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
switch option.UDPOverTCPVersion {
|
||||||
|
case uot.Version, uot.LegacyVersion:
|
||||||
|
case 0:
|
||||||
|
option.UDPOverTCPVersion = uot.Version
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -237,6 +305,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),
|
||||||
@ -248,7 +317,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
shadowTLSOption: shadowTLSOpt,
|
shadowTLSOption: shadowTLSOpt,
|
||||||
tlsConfig: tlsConfig,
|
restlsConfig: restlsConfig,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -163,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),
|
||||||
|
@ -167,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"
|
||||||
)
|
)
|
||||||
@ -167,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 {
|
||||||
@ -182,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),
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"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"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -25,24 +26,28 @@ type Trojan struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
@ -75,8 +80,13 @@ 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, t.realityConfig)
|
||||||
} else {
|
} else {
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(c)
|
||||||
}
|
}
|
||||||
@ -95,7 +105,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
|
||||||
@ -211,12 +221,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
tOption := &trojan.Option{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
Fingerprint: option.Fingerprint,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
@ -242,6 +253,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),
|
||||||
@ -250,6 +262,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
t.realityConfig, err = option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tOption.Reality = t.realityConfig
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
||||||
@ -268,7 +287,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 {
|
||||||
@ -276,7 +295,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
|
@ -42,15 +42,17 @@ type TuicOption struct {
|
|||||||
DisableSni bool `proxy:"disable-sni,omitempty"`
|
DisableSni bool `proxy:"disable-sni,omitempty"`
|
||||||
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
||||||
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
|
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -106,12 +108,14 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.Pack
|
|||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: serverName,
|
ServerName: serverName,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
|
if option.SNI != "" {
|
||||||
|
tlsConfig.ServerName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
var bs []byte
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
@ -143,7 +147,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
@ -165,13 +169,22 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
option.MaxUdpRelayPacketSize = 1500
|
option.MaxUdpRelayPacketSize = 1252
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxOpenStreams == 0 {
|
if option.MaxOpenStreams == 0 {
|
||||||
option.MaxOpenStreams = 100
|
option.MaxOpenStreams = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize == 0 {
|
||||||
|
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + tuic.PacketOverHead
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize > 1400 {
|
||||||
|
option.MaxDatagramFrameSize = 1400
|
||||||
|
}
|
||||||
|
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - tuic.PacketOverHead
|
||||||
|
|
||||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
||||||
@ -184,6 +197,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
MaxIncomingUniStreams: quicMaxOpenStreams,
|
MaxIncomingUniStreams: quicMaxOpenStreams,
|
||||||
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
if option.ReceiveWindowConn == 0 {
|
if option.ReceiveWindowConn == 0 {
|
||||||
@ -213,12 +227,18 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
udp: true,
|
udp: true,
|
||||||
tfo: option.FastOpen,
|
tfo: option.FastOpen,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
|
||||||
|
// to avoid tuic's "too many open streams", decrease to 0.9x
|
||||||
|
if clientMaxOpenStreams == 100 {
|
||||||
|
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
||||||
|
}
|
||||||
|
|
||||||
if clientMaxOpenStreams < 1 {
|
if clientMaxOpenStreams < 1 {
|
||||||
clientMaxOpenStreams = 1
|
clientMaxOpenStreams = 1
|
||||||
}
|
}
|
||||||
|
@ -12,19 +12,20 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
vmessSing "github.com/sagernet/sing-vmess"
|
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"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"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
vmessSing "github.com/sagernet/sing-vmess"
|
||||||
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -41,38 +42,46 @@ type Vless struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) 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":
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -80,6 +89,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{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,9 +108,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 != "" {
|
||||||
@ -144,7 +157,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":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS And XTLS
|
// handle TLS And XTLS
|
||||||
@ -161,7 +174,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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() && !isH2 {
|
if v.isLegacyXTLSEnabled() && !isH2 {
|
||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
@ -176,9 +189,11 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
} else if v.option.TLS {
|
} else if v.option.TLS {
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -195,8 +210,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
|
||||||
@ -233,12 +248,15 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
}(c)
|
}(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(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -279,7 +297,7 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -465,6 +483,9 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
switch option.Flow {
|
||||||
|
case vless.XRV:
|
||||||
|
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
||||||
|
fallthrough
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
@ -474,6 +495,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
|
||||||
@ -485,6 +516,8 @@ 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,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -493,14 +526,9 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
case "packetaddr", "packet":
|
if err != nil {
|
||||||
option.PacketAddr = true
|
return nil, err
|
||||||
case "xudp":
|
|
||||||
option.XUDP = true
|
|
||||||
}
|
|
||||||
if option.XUDP {
|
|
||||||
option.PacketAddr = false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
@ -519,10 +547,11 @@ 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,
|
||||||
})
|
})
|
||||||
@ -535,7 +564,8 @@ func NewVless(option VlessOption) (*Vless, 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, v.realityConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -5,20 +5,21 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
@ -34,31 +35,35 @@ type Vmess struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -86,9 +91,13 @@ 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":
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &clashVMess.WebsocketConfig{
|
wsOpts := &clashVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -96,6 +105,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Headers: http.Header{},
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,7 +124,7 @@ 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 {
|
||||||
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
|
||||||
@ -133,14 +143,15 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -159,9 +170,11 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := clashVMess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -180,14 +193,16 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -203,12 +218,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
if v.option.XUDP {
|
if v.option.XUDP {
|
||||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
} else {
|
||||||
|
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
} else {
|
||||||
|
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
return v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
|
} else {
|
||||||
|
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -251,7 +278,7 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -279,9 +306,17 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
if v.option.XUDP {
|
if v.option.XUDP {
|
||||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
c = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
if N.NeedHandshake(c) {
|
||||||
|
c = v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -294,7 +329,7 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -366,7 +401,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -376,6 +411,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),
|
||||||
@ -400,8 +437,9 @@ 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,
|
||||||
@ -416,8 +454,15 @@ 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, v.realityConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ 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"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/listener/sing"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
@ -34,7 +34,7 @@ type WireGuard struct {
|
|||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer *wgDialer
|
dialer *wgSingDialer
|
||||||
startOnce sync.Once
|
startOnce sync.Once
|
||||||
startErr error
|
startErr error
|
||||||
}
|
}
|
||||||
@ -56,16 +56,28 @@ type WireGuardOption struct {
|
|||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type wgDialer struct {
|
type wgSingDialer struct {
|
||||||
options []dialer.Option
|
dialer dialer.Dialer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
var _ N.Dialer = &wgSingDialer{}
|
||||||
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
|
||||||
|
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
return d.dialer.DialContext(ctx, network, destination.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", destination.Addr), "", d.options...)
|
return d.dialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgNetDialer struct {
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ dialer.NetDialer = &wgNetDialer{}
|
||||||
|
|
||||||
|
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
@ -79,7 +91,7 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
dialer: &wgDialer{},
|
dialer: &wgSingDialer{dialer: dialer.NewDialer()},
|
||||||
}
|
}
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
@ -174,14 +186,14 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
sing.Logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
log.SingLogger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
},
|
},
|
||||||
Errorf: func(format string, args ...interface{}) {
|
Errorf: func(format string, args ...interface{}) {
|
||||||
sing.Logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
log.SingLogger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
},
|
},
|
||||||
}, option.Workers)
|
}, option.Workers)
|
||||||
if debug.Enabled {
|
if debug.Enabled {
|
||||||
sing.Logger.Trace("created wireguard ipc conf: \n", ipcConf)
|
log.SingLogger.Trace("created wireguard ipc conf: \n", ipcConf)
|
||||||
}
|
}
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -199,7 +211,8 @@ func closeWireGuard(w *WireGuard) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
w.dialer.options = opts
|
options := w.Base.DialOptions(opts...)
|
||||||
|
w.dialer.dialer = dialer.NewDialer(options...)
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -208,15 +221,12 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
return nil, w.startErr
|
return nil, w.startErr
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
var addrs []netip.Addr
|
options = append(options, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
addrs, err = resolver.LookupIP(ctx, metadata.Host)
|
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||||
if err != nil {
|
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn, err = N.DialSerial(ctx, w.tunDevice, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()), addrs)
|
|
||||||
} else {
|
} else {
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -228,7 +238,8 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
w.dialer.options = opts
|
options := w.Base.DialOptions(opts...)
|
||||||
|
w.dialer.dialer = dialer.NewDialer(options...)
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -247,7 +258,7 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/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"
|
||||||
@ -30,11 +32,23 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
f.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
f.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -165,6 +165,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
for i := range gb.excludeTypeArray {
|
for i := range gb.excludeTypeArray {
|
||||||
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
||||||
flag = true
|
flag = true
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -6,11 +6,14 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -18,7 +21,7 @@ import (
|
|||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
@ -83,17 +86,27 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := lb.Unwrap(metadata, true)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(lb)
|
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,12 +129,25 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
idxMutex := sync.Mutex{}
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
|
idxMutex.Lock()
|
||||||
|
defer idxMutex.Unlock()
|
||||||
|
|
||||||
|
i := 0
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
for i := 0; i < length; i++ {
|
|
||||||
idx = (idx + 1) % length
|
if touch {
|
||||||
proxy := proxies[idx]
|
defer func() {
|
||||||
|
idx = (idx + i) % length
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
for ; i < length; i++ {
|
||||||
|
id := (idx + i) % length
|
||||||
|
proxy := proxies[id]
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
|
i++
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,7 +158,7 @@ func strategyRoundRobin() strategyFn {
|
|||||||
|
|
||||||
func strategyConsistentHashing() strategyFn {
|
func strategyConsistentHashing() strategyFn {
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(proxies))
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
@ -160,7 +186,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
lruCache := cache.New[uint64, int](
|
lruCache := cache.New[uint64, int](
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
cache.WithSize[uint64, int](1000))
|
cache.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
idx, has := lruCache.Get(key)
|
idx, has := lruCache.Get(key)
|
||||||
@ -192,7 +218,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(touch)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata, touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
|
@ -78,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 {
|
||||||
|
@ -176,7 +176,7 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Addr() string {
|
func (r *Relay) Addr() string {
|
||||||
proxies, _ := r.proxies(nil, true)
|
proxies, _ := r.proxies(nil, false)
|
||||||
return proxies[len(proxies)-1].Addr()
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,6 +6,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -38,10 +40,23 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = &callback.FirstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
u.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
u.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,6 +2,9 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -20,7 +23,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
)
|
)
|
||||||
switch proxyType {
|
switch proxyType {
|
||||||
case "ss":
|
case "ss":
|
||||||
ssOption := &outbound.ShadowSocksOption{}
|
ssOption := &outbound.ShadowSocksOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, ssOption)
|
err = decoder.Decode(mapping, ssOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -53,14 +56,16 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
|
ClientFingerprint: tlsC.GetGlobalFingerprint(),
|
||||||
}
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -74,7 +79,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{}
|
trojanOption := &outbound.TrojanOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
|
@ -6,10 +6,10 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -34,16 +34,15 @@ type HealthCheck struct {
|
|||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go func() {
|
|
||||||
time.Sleep(30 * time.Second)
|
|
||||||
hc.lazyCheck()
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
hc.lazyCheck()
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
} else {
|
||||||
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -51,17 +50,6 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) lazyCheck() bool {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -76,10 +64,7 @@ func (hc *HealthCheck) touch() {
|
|||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
id := ""
|
id := utils.NewUUIDV4().String()
|
||||||
if uid, err := uuid.NewV4(); err == nil {
|
|
||||||
id = uid.String()
|
|
||||||
}
|
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
|
@ -80,6 +80,7 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pp.OnUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
|
pp.getSubscriptionInfo()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,7 +100,7 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
defer func() { go pp.healthCheck.lazyCheck() }()
|
go pp.healthCheck.check()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,8 +173,6 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg), 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
|
||||||
@ -301,6 +300,7 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
for i := range excludeTypeArray {
|
for i := range excludeTypeArray {
|
||||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
||||||
flag = true
|
flag = true
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
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
|
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"
|
||||||
@ -81,7 +83,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["port"] = urlTrojan.Port()
|
trojan["port"] = urlTrojan.Port()
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
trojan["password"] = urlTrojan.User.Username()
|
||||||
trojan["udp"] = true
|
trojan["udp"] = true
|
||||||
trojan["skip-cert-verify"] = false
|
trojan["skip-cert-verify"], _ = strconv.ParseBool(query.Get("allowInsecure"))
|
||||||
|
|
||||||
sni := query.Get("sni")
|
sni := query.Get("sni")
|
||||||
if sni != "" {
|
if sni != "" {
|
||||||
@ -111,6 +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 != "" {
|
||||||
@ -272,16 +288,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
cipher string
|
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(cipherRaw)
|
dcBuf, err := base64.RawURLEncoding.DecodeString(cipherRaw)
|
||||||
|
if err != nil {
|
||||||
|
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)
|
err = VerifyMethod(cipher, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dcBuf, _ := encRaw.DecodeString(cipherRaw)
|
dcBuf, _ = encRaw.DecodeString(cipherRaw)
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,12 +2,14 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
|
||||||
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@ -292,8 +294,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func RandHost() string {
|
func RandHost() string {
|
||||||
id, _ := uuid.NewV4()
|
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(utils.NewUUIDV4().Bytes()))
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
base = strings.ReplaceAll(base, "-", "")
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
base = strings.ReplaceAll(base, "_", "")
|
||||||
buf := []byte(base)
|
buf := []byte(base)
|
||||||
@ -301,11 +302,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[rand.Intn(uaLen)]
|
return userAgents[fastrand.Intn(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
@ -317,6 +318,6 @@ func SetUserAgent(header http.Header) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func VerifyMethod(cipher, password string) (err error) {
|
func VerifyMethod(cipher, password string) (err error) {
|
||||||
_, err = shadowimpl.FetchMethod(cipher, password)
|
_, err = shadowimpl.FetchMethod(cipher, password, time.Now)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,24 @@
|
|||||||
package convert
|
package convert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) error {
|
||||||
// Xray VMessAEAD / VLESS share link standard
|
// Xray VMessAEAD / VLESS share link standard
|
||||||
// https://github.com/XTLS/Xray-core/discussions/716
|
// https://github.com/XTLS/Xray-core/discussions/716
|
||||||
query := url.Query()
|
query := url.Query()
|
||||||
proxy["name"] = uniqueName(names, url.Fragment)
|
proxy["name"] = uniqueName(names, url.Fragment)
|
||||||
|
if url.Hostname() == "" {
|
||||||
|
return errors.New("url.Hostname() is empty")
|
||||||
|
}
|
||||||
|
if url.Port() == "" {
|
||||||
|
return errors.New("url.Port() is empty")
|
||||||
|
}
|
||||||
proxy["type"] = scheme
|
proxy["type"] = scheme
|
||||||
proxy["server"] = url.Hostname()
|
proxy["server"] = url.Hostname()
|
||||||
proxy["port"] = url.Port()
|
proxy["port"] = url.Port()
|
||||||
@ -18,12 +27,23 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
proxy["skip-cert-verify"] = false
|
proxy["skip-cert-verify"] = false
|
||||||
proxy["tls"] = false
|
proxy["tls"] = false
|
||||||
tls := strings.ToLower(query.Get("security"))
|
tls := strings.ToLower(query.Get("security"))
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if strings.HasSuffix(tls, "tls") || tls == "reality" {
|
||||||
proxy["tls"] = true
|
proxy["tls"] = true
|
||||||
|
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||||
|
proxy["client-fingerprint"] = "chrome"
|
||||||
|
} else {
|
||||||
|
proxy["client-fingerprint"] = fingerprint
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if sni := query.Get("sni"); sni != "" {
|
if sni := query.Get("sni"); sni != "" {
|
||||||
proxy["servername"] = sni
|
proxy["servername"] = sni
|
||||||
}
|
}
|
||||||
|
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
|
||||||
|
proxy["reality-opts"] = map[string]any{
|
||||||
|
"public-key": realityPublicKey,
|
||||||
|
"short-id": query.Get("sid"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
switch query.Get("packetEncoding") {
|
switch query.Get("packetEncoding") {
|
||||||
case "none":
|
case "none":
|
||||||
@ -87,6 +107,17 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
if earlyData := query.Get("ed"); earlyData != "" {
|
||||||
|
med, err := strconv.Atoi(earlyData)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
||||||
|
}
|
||||||
|
wsOpts["max-early-data"] = med
|
||||||
|
}
|
||||||
|
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
||||||
|
wsOpts["early-data-header-name"] = earlyDataHeader
|
||||||
|
}
|
||||||
|
|
||||||
proxy["ws-opts"] = wsOpts
|
proxy["ws-opts"] = wsOpts
|
||||||
|
|
||||||
case "grpc":
|
case "grpc":
|
||||||
@ -94,4 +125,5 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
proxy["grpc-opts"] = grpcOpts
|
proxy["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -5,10 +5,10 @@
|
|||||||
// Package list implements a doubly linked list.
|
// Package list implements a doubly linked list.
|
||||||
//
|
//
|
||||||
// To iterate over a list (where l is a *List):
|
// To iterate over a list (where l is a *List):
|
||||||
|
//
|
||||||
// for e := l.Front(); e != nil; e = e.Next() {
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
// // do something with e.Value
|
// // do something with e.Value
|
||||||
// }
|
// }
|
||||||
//
|
|
||||||
package list
|
package list
|
||||||
|
|
||||||
// Element is an element of a linked list.
|
// Element is an element of a linked list.
|
||||||
|
36
common/net/addr.go
Normal file
36
common/net/addr.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CustomAddr interface {
|
||||||
|
net.Addr
|
||||||
|
RawAddr() net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
type customAddr struct {
|
||||||
|
networkStr string
|
||||||
|
addrStr string
|
||||||
|
rawAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) Network() string {
|
||||||
|
return a.networkStr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) String() string {
|
||||||
|
return a.addrStr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a customAddr) RawAddr() net.Addr {
|
||||||
|
return a.rawAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCustomAddr(networkStr string, addrStr string, rawAddr net.Addr) CustomAddr {
|
||||||
|
return customAddr{
|
||||||
|
networkStr: networkStr,
|
||||||
|
addrStr: addrStr,
|
||||||
|
rawAddr: rawAddr,
|
||||||
|
}
|
||||||
|
}
|
@ -3,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
|
||||||
|
}
|
||||||
|
@ -51,6 +51,10 @@ func (c *refConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return c.conn.SetWriteDeadline(t)
|
return c.conn.SetWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *refConn) Upstream() any {
|
||||||
|
return c.conn
|
||||||
|
}
|
||||||
|
|
||||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||||
return &refConn{conn: conn, ref: ref}
|
return &refConn{conn: conn, ref: ref}
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,24 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
//import (
|
||||||
"io"
|
// "io"
|
||||||
"net"
|
// "net"
|
||||||
"time"
|
// "time"
|
||||||
)
|
//)
|
||||||
|
//
|
||||||
// Relay copies between left and right bidirectionally.
|
//// Relay copies between left and right bidirectionally.
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
//func Relay(leftConn, rightConn net.Conn) {
|
||||||
ch := make(chan error)
|
// ch := make(chan error)
|
||||||
|
//
|
||||||
go func() {
|
// go func() {
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// // See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
leftConn.SetReadDeadline(time.Now())
|
// leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
// ch <- err
|
||||||
}()
|
// }()
|
||||||
|
//
|
||||||
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
rightConn.SetReadDeadline(time.Now())
|
// rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
// <-ch
|
||||||
}
|
//}
|
||||||
|
30
common/net/sing.go
Normal file
30
common/net/sing.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"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
|
||||||
|
|
||||||
|
func NeedHandshake(conn any) bool {
|
||||||
|
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
||||||
|
}
|
@ -1,11 +1,19 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/big"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
|
if certificate == "" || privateKey == "" {
|
||||||
|
return newRandomTLSKeyPair()
|
||||||
|
}
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||||
if painTextErr == nil {
|
if painTextErr == nil {
|
||||||
return cert, nil
|
return cert, nil
|
||||||
@ -17,3 +25,28 @@ func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
|||||||
}
|
}
|
||||||
return cert, nil
|
return cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
||||||
|
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
||||||
|
certDER, err := x509.CreateCertificate(
|
||||||
|
rand.Reader,
|
||||||
|
&template,
|
||||||
|
&template,
|
||||||
|
&key.PublicKey,
|
||||||
|
key)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||||
|
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||||
|
|
||||||
|
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
return tlsCert, nil
|
||||||
|
}
|
||||||
|
131
common/net/websocket.go
Normal file
131
common/net/websocket.go
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
// kanged from https://github.com/nhooyr/websocket/blob/master/frame.go
|
||||||
|
// License: MIT
|
||||||
|
|
||||||
|
// MaskWebSocket applies the WebSocket masking algorithm to p
|
||||||
|
// with the given key.
|
||||||
|
// See https://tools.ietf.org/html/rfc6455#section-5.3
|
||||||
|
//
|
||||||
|
// The returned value is the correctly rotated key to
|
||||||
|
// to continue to mask/unmask the message.
|
||||||
|
//
|
||||||
|
// It is optimized for LittleEndian and expects the key
|
||||||
|
// to be in little endian.
|
||||||
|
//
|
||||||
|
// See https://github.com/golang/go/issues/31586
|
||||||
|
func MaskWebSocket(key uint32, b []byte) uint32 {
|
||||||
|
if len(b) >= 8 {
|
||||||
|
key64 := uint64(key)<<32 | uint64(key)
|
||||||
|
|
||||||
|
// At some point in the future we can clean these unrolled loops up.
|
||||||
|
// See https://github.com/golang/go/issues/31586#issuecomment-487436401
|
||||||
|
|
||||||
|
// Then we xor until b is less than 128 bytes.
|
||||||
|
for len(b) >= 128 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[32:40])
|
||||||
|
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[40:48])
|
||||||
|
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[48:56])
|
||||||
|
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[56:64])
|
||||||
|
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[64:72])
|
||||||
|
binary.LittleEndian.PutUint64(b[64:72], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[72:80])
|
||||||
|
binary.LittleEndian.PutUint64(b[72:80], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[80:88])
|
||||||
|
binary.LittleEndian.PutUint64(b[80:88], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[88:96])
|
||||||
|
binary.LittleEndian.PutUint64(b[88:96], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[96:104])
|
||||||
|
binary.LittleEndian.PutUint64(b[96:104], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[104:112])
|
||||||
|
binary.LittleEndian.PutUint64(b[104:112], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[112:120])
|
||||||
|
binary.LittleEndian.PutUint64(b[112:120], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[120:128])
|
||||||
|
binary.LittleEndian.PutUint64(b[120:128], v^key64)
|
||||||
|
b = b[128:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 64 bytes.
|
||||||
|
for len(b) >= 64 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[32:40])
|
||||||
|
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[40:48])
|
||||||
|
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[48:56])
|
||||||
|
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[56:64])
|
||||||
|
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||||
|
b = b[64:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 32 bytes.
|
||||||
|
for len(b) >= 32 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[16:24])
|
||||||
|
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[24:32])
|
||||||
|
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||||
|
b = b[32:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 16 bytes.
|
||||||
|
for len(b) >= 16 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
v = binary.LittleEndian.Uint64(b[8:16])
|
||||||
|
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||||
|
b = b[16:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 8 bytes.
|
||||||
|
for len(b) >= 8 {
|
||||||
|
v := binary.LittleEndian.Uint64(b)
|
||||||
|
binary.LittleEndian.PutUint64(b, v^key64)
|
||||||
|
b = b[8:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then we xor until b is less than 4 bytes.
|
||||||
|
for len(b) >= 4 {
|
||||||
|
v := binary.LittleEndian.Uint32(b)
|
||||||
|
binary.LittleEndian.PutUint32(b, v^key)
|
||||||
|
b = b[4:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// xor remaining bytes.
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= byte(key)
|
||||||
|
key = bits.RotateLeft32(key, -8)
|
||||||
|
}
|
||||||
|
|
||||||
|
return key
|
||||||
|
}
|
@ -1,10 +1,10 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math/rand"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(rand.Int())
|
msb(fastrand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
8
common/utils/must.go
Normal file
8
common/utils/must.go
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
func MustOK[T any](result T, ok bool) T {
|
||||||
|
if ok {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
panic("operation failed")
|
||||||
|
}
|
34
common/utils/slice.go
Normal file
34
common/utils/slice.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
|
||||||
|
result := make([]T, 0)
|
||||||
|
for _, t := range tSlice {
|
||||||
|
if filter(t) {
|
||||||
|
result = append(result, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func ToStringSlice(value any) ([]string, error) {
|
||||||
|
strArr := make([]string, 0)
|
||||||
|
switch reflect.TypeOf(value).Kind() {
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
origin := reflect.ValueOf(value)
|
||||||
|
for i := 0; i < origin.Len(); i++ {
|
||||||
|
item := fmt.Sprintf("%v", origin.Index(i))
|
||||||
|
strArr = append(strArr, item)
|
||||||
|
}
|
||||||
|
case reflect.String:
|
||||||
|
strArr = append(strArr, fmt.Sprintf("%v", value))
|
||||||
|
default:
|
||||||
|
return nil, errors.New("value format error, must be string or array")
|
||||||
|
}
|
||||||
|
return strArr, nil
|
||||||
|
}
|
@ -2,15 +2,50 @@ package utils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
type fastRandReader struct{}
|
||||||
|
|
||||||
|
func (r fastRandReader) Read(p []byte) (int, error) {
|
||||||
|
return fastrand.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
|
||||||
|
|
||||||
|
func NewUUIDV1() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
|
||||||
|
return UnsafeUUIDGenerator.NewV3(ns, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV4() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
|
||||||
|
return UnsafeUUIDGenerator.NewV5(ns, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV6() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUUIDV7() uuid.UUID {
|
||||||
|
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
func UUIDMap(str string) (uuid.UUID, error) {
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
u, err := uuid.FromString(str)
|
u, err := uuid.FromString(str)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return uuid.NewV5(uuidNamespace, str), nil
|
return NewUUIDV5(uuid.Nil, str), nil
|
||||||
}
|
}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
@ -1,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)
|
||||||
|
}
|
||||||
|
}
|
@ -2,40 +2,27 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"runtime"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
tcpConcurrent = false
|
tcpConcurrent = false
|
||||||
DisableIPv6 = false
|
fallbackTimeout = 300 * time.Millisecond
|
||||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
|
||||||
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
if runtime.GOOS == "windows" { // fix bindIfaceToListenConfig() in windows force bind to an ipv4 address
|
|
||||||
if !strings.HasSuffix(network, "4") &&
|
|
||||||
!strings.HasSuffix(network, "6") &&
|
|
||||||
addr.Unmap().Is6() {
|
|
||||||
network += "6"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return network
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyOptions(options ...Option) *option {
|
func applyOptions(options ...Option) *option {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
@ -66,29 +53,23 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
network = fmt.Sprintf("%s%d", network, opt.network)
|
network = fmt.Sprintf("%s%d", network, opt.network)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleDialContext(ctx, network, address, opt)
|
return actualSingleStackDialContext(ctx, network, ips, port, opt)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return actualDualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, ips, port, opt)
|
||||||
default:
|
default:
|
||||||
return nil, ErrorInvalidedNetworkStack
|
return nil, ErrorInvalidedNetworkStack
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||||
cfg := &option{
|
cfg := applyOptions(options...)
|
||||||
interfaceName: DefaultInterface.Load(),
|
|
||||||
routingMark: int(DefaultRoutingMark.Load()),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range DefaultOptions {
|
|
||||||
o(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range options {
|
|
||||||
o(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
lc := &net.ListenConfig{}
|
lc := &net.ListenConfig{}
|
||||||
if cfg.interfaceName != "" {
|
if cfg.interfaceName != "" {
|
||||||
@ -108,26 +89,40 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetDial(concurrent bool) {
|
func SetTcpConcurrent(concurrent bool) {
|
||||||
dialMux.Lock()
|
dialMux.Lock()
|
||||||
|
defer dialMux.Unlock()
|
||||||
tcpConcurrent = concurrent
|
tcpConcurrent = concurrent
|
||||||
if concurrent {
|
if concurrent {
|
||||||
actualSingleDialContext = concurrentSingleDialContext
|
actualSingleStackDialContext = concurrentSingleStackDialContext
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
} else {
|
} else {
|
||||||
actualSingleDialContext = singleDialContext
|
actualSingleStackDialContext = serialSingleStackDialContext
|
||||||
actualDualStackDialContext = dualStackDialContext
|
actualDualStackDialContext = serialDualStackDialContext
|
||||||
}
|
}
|
||||||
|
|
||||||
dialMux.Unlock()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDial() bool {
|
func GetTcpConcurrent() bool {
|
||||||
|
dialMux.Lock()
|
||||||
|
defer dialMux.Unlock()
|
||||||
return tcpConcurrent
|
return tcpConcurrent
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
address := net.JoinHostPort(destination.String(), port)
|
||||||
|
|
||||||
|
netDialer := opt.netDialer
|
||||||
|
switch netDialer.(type) {
|
||||||
|
case nil:
|
||||||
|
netDialer = &net.Dialer{}
|
||||||
|
case *net.Dialer:
|
||||||
|
_netDialer := *netDialer.(*net.Dialer)
|
||||||
|
netDialer = &_netDialer // make a copy
|
||||||
|
default:
|
||||||
|
return netDialer.DialContext(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
dialer := netDialer.(*net.Dialer)
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -136,328 +131,213 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
if opt.routingMark != 0 {
|
if opt.routingMark != 0 {
|
||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
if opt.tfo {
|
||||||
if DisableIPv6 && destination.Is6() {
|
return dialTFO(ctx, *dialer, network, address)
|
||||||
return nil, ErrorDisableIPv6
|
|
||||||
}
|
}
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
return serialDialContext(ctx, network, ips, port, opt)
|
||||||
if err != nil {
|
}
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
func serialDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
return dualStackDialContext(ctx, serialDialContext, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
return parallelDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
if opt.prefer != 4 && opt.prefer != 6 {
|
||||||
|
return parallelDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
return dualStackDialContext(ctx, parallelDialContext, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
ipv4s, ipv6s := sortationAddr(ips)
|
||||||
|
preferIPVersion := opt.prefer
|
||||||
|
|
||||||
|
fallbackTicker := time.NewTicker(fallbackTimeout)
|
||||||
|
defer fallbackTicker.Stop()
|
||||||
|
results := make(chan dialResult)
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
|
racer := func(ips []netip.Addr, isPrimary bool) {
|
||||||
type dialResult struct {
|
result := dialResult{isPrimary: isPrimary}
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
resolved bool
|
|
||||||
ipv6 bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
results := make(chan dialResult)
|
|
||||||
var primary, fallback dialResult
|
|
||||||
|
|
||||||
startRacer := func(ctx context.Context, network, host string, r resolver.Resolver, ipv6 bool) {
|
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil {
|
if result.Conn != nil && result.error == nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
result.Conn, result.error = dialFn(ctx, network, ips, port, opt)
|
||||||
var ip netip.Addr
|
|
||||||
if ipv6 {
|
|
||||||
if r == nil {
|
|
||||||
ip, result.error = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv6WithResolver(ctx, host, r)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if r == nil {
|
|
||||||
ip, result.error = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv4WithResolver(ctx, host, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if result.error != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
result.resolved = true
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
}
|
||||||
|
go racer(ipv4s, preferIPVersion != 6)
|
||||||
go startRacer(ctx, network+"4", host, opt.resolver, false)
|
go racer(ipv6s, preferIPVersion != 4)
|
||||||
go startRacer(ctx, network+"6", host, opt.resolver, true)
|
var fallback dialResult
|
||||||
|
var errs []error
|
||||||
count := 2
|
for i := 0; i < 2; {
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
select {
|
select {
|
||||||
|
case <-fallbackTicker.C:
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
case res := <-results:
|
case res := <-results:
|
||||||
|
i++
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
return res.Conn, nil
|
if res.isPrimary {
|
||||||
}
|
return res.Conn, nil
|
||||||
|
}
|
||||||
if !res.ipv6 {
|
|
||||||
primary = res
|
|
||||||
} else {
|
|
||||||
fallback = res
|
fallback = res
|
||||||
}
|
} else {
|
||||||
|
if res.isPrimary {
|
||||||
if primary.done && fallback.done {
|
errs = append([]error{fmt.Errorf("connect failed: %w", res.error)}, errs...)
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
} else {
|
||||||
return nil, primary.error
|
errs = append(errs, fmt.Errorf("connect failed: %w", res.error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case <-ctx.Done():
|
|
||||||
err = ctx.Err()
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if fallback.error == nil && fallback.Conn != nil {
|
||||||
if err == nil {
|
return fallback.Conn, nil
|
||||||
err = fmt.Errorf("dual stack dial failed")
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("dual stack dial failed:%w", err)
|
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, errorsJoin(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
if len(ips) == 0 {
|
||||||
if err != nil {
|
return nil, ErrorNoIpAddress
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
results := make(chan dialResult)
|
||||||
var ips []netip.Addr
|
|
||||||
if opt.resolver != nil {
|
|
||||||
ips, err = resolver.LookupIPWithResolver(ctx, host, opt.resolver)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
|
racer := func(ctx context.Context, ip netip.Addr) {
|
||||||
type dialResult struct {
|
result := dialResult{isPrimary: true, ip: ip}
|
||||||
ip netip.Addr
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
isPrimary bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
|
|
||||||
preferCount := atomic.NewInt32(0)
|
|
||||||
results := make(chan dialResult)
|
|
||||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
result := dialResult{ip: ip, done: true}
|
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil {
|
if result.Conn != nil && result.error == nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if strings.Contains(network, "tcp") {
|
|
||||||
network = "tcp"
|
|
||||||
} else {
|
|
||||||
network = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is6() {
|
|
||||||
network += "6"
|
|
||||||
if opt.prefer != 4 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is4() {
|
|
||||||
network += "4"
|
|
||||||
if opt.prefer != 6 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.isPrimary {
|
|
||||||
preferCount.Add(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
go tcpRacer(ctx, ip)
|
go racer(ctx, ip)
|
||||||
}
|
}
|
||||||
|
var errs []error
|
||||||
connCount := len(ips)
|
for i := 0; i < len(ips); i++ {
|
||||||
var fallback dialResult
|
res := <-results
|
||||||
var primaryError error
|
if res.error == nil {
|
||||||
var finalError error
|
return res.Conn, nil
|
||||||
for i := 0; i < connCount; i++ {
|
|
||||||
select {
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
if res.isPrimary {
|
|
||||||
return res.Conn, nil
|
|
||||||
} else {
|
|
||||||
if !fallback.done || fallback.error != nil {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if res.isPrimary {
|
|
||||||
primaryError = res.error
|
|
||||||
preferCount.Add(-1)
|
|
||||||
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case <-ctx.Done():
|
|
||||||
if fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
finalError = ctx.Err()
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
errs = append(errs, res.error)
|
||||||
}
|
}
|
||||||
|
|
||||||
if fallback.done && fallback.error == nil {
|
if len(errs) > 0 {
|
||||||
return fallback.Conn, nil
|
return nil, errorsJoin(errs...)
|
||||||
}
|
}
|
||||||
|
return nil, os.ErrDeadlineExceeded
|
||||||
if primaryError != nil {
|
|
||||||
return nil, primaryError
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallback.error != nil {
|
|
||||||
return nil, fallback.error
|
|
||||||
}
|
|
||||||
|
|
||||||
if finalError == nil {
|
|
||||||
finalError = fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
|
||||||
} else {
|
|
||||||
finalError = fmt.Errorf("concurrent dial failed:%w", finalError)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, finalError
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, ErrorNoIpAddress
|
||||||
|
}
|
||||||
|
var errs []error
|
||||||
|
for _, ip := range ips {
|
||||||
|
if conn, err := dialContext(ctx, network, ip, port, opt); err == nil {
|
||||||
|
return conn, nil
|
||||||
|
} else {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, errorsJoin(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type dialResult struct {
|
||||||
|
ip netip.Addr
|
||||||
|
net.Conn
|
||||||
|
error
|
||||||
|
isPrimary bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAddr(ctx context.Context, network, address string, preferResolver resolver.Resolver) ([]netip.Addr, string, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, "-1", err
|
||||||
}
|
|
||||||
|
|
||||||
var ip netip.Addr
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
return concurrentIPv4DialContext(ctx, network, address, opt)
|
|
||||||
default:
|
|
||||||
return concurrentIPv6DialContext(ctx, network, address, opt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
if opt.resolver == nil {
|
switch network {
|
||||||
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
case "tcp4", "udp4":
|
||||||
} else {
|
if preferResolver == nil {
|
||||||
ips, err = resolver.LookupIPv4WithResolver(ctx, host, opt.resolver)
|
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPv4WithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPv6WithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if preferResolver == nil {
|
||||||
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPWithResolver(ctx, host, preferResolver)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, "-1", fmt.Errorf("dns resolve failed: %w", err)
|
||||||
}
|
}
|
||||||
|
for i, ip := range ips {
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
if ip.Is4In6() {
|
||||||
|
ips[i] = ip.Unmap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ips, port, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func sortationAddr(ips []netip.Addr) (ipv4s, ipv6s []netip.Addr) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
for _, v := range ips {
|
||||||
if err != nil {
|
if v.Is4() { // 4in6 parse was in parseAddr
|
||||||
return nil, err
|
ipv4s = append(ipv4s, v)
|
||||||
|
} else {
|
||||||
|
ipv6s = append(ipv6s, v)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return
|
||||||
var ips []netip.Addr
|
|
||||||
if opt.resolver == nil {
|
|
||||||
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPv6WithResolver(ctx, host, opt.resolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Dialer struct {
|
type Dialer struct {
|
||||||
Opt option
|
opt option
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
func (d Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
return DialContext(ctx, network, address, WithOption(d.Opt))
|
return DialContext(ctx, network, address, WithOption(d.opt))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, WithOption(d.Opt))
|
opt := WithOption(d.opt)
|
||||||
|
if rAddrPort.Addr().Unmap().IsLoopback() {
|
||||||
|
// avoid "The requested address is not valid in its context."
|
||||||
|
opt = WithInterface("")
|
||||||
|
}
|
||||||
|
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDialer(options ...Option) Dialer {
|
func NewDialer(options ...Option) Dialer {
|
||||||
opt := applyOptions(options...)
|
opt := applyOptions(options...)
|
||||||
return Dialer{Opt: *opt}
|
return Dialer{opt: *opt}
|
||||||
}
|
}
|
||||||
|
18
component/dialer/error.go
Normal file
18
component/dialer/error.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrorNoIpAddress = errors.New("no ip address")
|
||||||
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
|
)
|
||||||
|
|
||||||
|
func errorsJoin(errs ...error) error {
|
||||||
|
// compatibility with golang<1.20
|
||||||
|
// maybe use errors.Join(errs...) is better after we drop the old version's support
|
||||||
|
return E.Errors(errs...)
|
||||||
|
}
|
@ -3,26 +3,22 @@
|
|||||||
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() {
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
@ -12,13 +15,19 @@ var (
|
|||||||
DefaultRoutingMark = atomic.NewInt32(0)
|
DefaultRoutingMark = atomic.NewInt32(0)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type NetDialer interface {
|
||||||
|
DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
||||||
|
}
|
||||||
|
|
||||||
type option struct {
|
type option struct {
|
||||||
interfaceName string
|
interfaceName string
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
network int
|
network int
|
||||||
prefer int
|
prefer int
|
||||||
|
tfo bool
|
||||||
resolver resolver.Resolver
|
resolver resolver.Resolver
|
||||||
|
netDialer NetDialer
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -69,6 +78,18 @@ func WithOnlySingleStack(isIPv4 bool) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithTFO(tfo bool) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.tfo = tfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithNetDialer(netDialer NetDialer) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.netDialer = netDialer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func WithOption(o option) Option {
|
func WithOption(o option) Option {
|
||||||
return func(opt *option) {
|
return func(opt *option) {
|
||||||
*opt = o
|
*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)
|
||||||
})
|
})
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
123
component/dialer/tfo.go
Normal file
123
component/dialer/tfo.go
Normal file
@ -0,0 +1,123 @@
|
|||||||
|
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 (c *tfoConn) NeedHandshake() bool {
|
||||||
|
return c.Conn == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -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
|
||||||
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -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
|
||||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -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
|
||||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -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
|
||||||
|
@ -1,13 +1,10 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
"github.com/Dreamacro/clash/log"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type loader struct {
|
type loader struct {
|
||||||
@ -15,47 +12,7 @@ type loader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||||
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
return l.LoadSiteByPath(C.GeositeName, list)
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
|
||||||
parts := strings.Split(siteWithAttr, "@")
|
|
||||||
if len(parts) == 0 {
|
|
||||||
return nil, errors.New("empty rule")
|
|
||||||
}
|
|
||||||
list := strings.TrimSpace(parts[0])
|
|
||||||
attrVal := parts[1:]
|
|
||||||
|
|
||||||
if len(list) == 0 {
|
|
||||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
|
|
||||||
domains, err := l.LoadSiteByPath(file, list)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := parseAttrs(attrVal)
|
|
||||||
if attrs.IsEmpty() {
|
|
||||||
if strings.Contains(siteWithAttr, "@") {
|
|
||||||
log.Warnln("empty attribute list: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
return domains, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
filteredDomains := make([]*router.Domain, 0, len(domains))
|
|
||||||
hasAttrMatched := false
|
|
||||||
for _, domain := range domains {
|
|
||||||
if attrs.Match(domain) {
|
|
||||||
hasAttrMatched = true
|
|
||||||
filteredDomains = append(filteredDomains, domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hasAttrMatched {
|
|
||||||
log.Warnln("attribute match no rule: geosite: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return filteredDomains, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
|
@ -14,6 +14,5 @@ type LoaderImplementation interface {
|
|||||||
type Loader interface {
|
type Loader interface {
|
||||||
LoaderImplementation
|
LoaderImplementation
|
||||||
LoadGeoSite(list string) ([]*router.Domain, error)
|
LoadGeoSite(list string) ([]*router.Domain, error)
|
||||||
LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error)
|
|
||||||
LoadGeoIP(country string) ([]*router.CIDR, error)
|
LoadGeoIP(country string) ([]*router.CIDR, error)
|
||||||
}
|
}
|
||||||
|
@ -118,7 +118,7 @@ func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error)
|
|||||||
|
|
||||||
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
||||||
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
||||||
log.Warnln("failed to decode geoip file: %s%s", filename, ", fallback to the original ReadFile method")
|
log.Warnln("failed to decode geosite file: %s%s", filename, ", fallback to the original ReadFile method")
|
||||||
geositeBytes, err = os.ReadFile(asset)
|
geositeBytes, err = os.ReadFile(asset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -1,9 +1,14 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"golang.org/x/sync/singleflight"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
var geoLoaderName = "memconservative"
|
||||||
@ -34,6 +39,8 @@ func Verify(name string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var loadGeoSiteMatcherSF = singleflight.Group{}
|
||||||
|
|
||||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
||||||
if len(countryCode) == 0 {
|
if len(countryCode) == 0 {
|
||||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
@ -44,16 +51,53 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
not = true
|
not = true
|
||||||
countryCode = countryCode[1:]
|
countryCode = countryCode[1:]
|
||||||
}
|
}
|
||||||
|
countryCode = strings.ToLower(countryCode)
|
||||||
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
parts := strings.Split(countryCode, "@")
|
||||||
if err != nil {
|
if len(parts) == 0 {
|
||||||
return nil, 0, err
|
return nil, 0, errors.New("empty rule")
|
||||||
|
}
|
||||||
|
listName := strings.TrimSpace(parts[0])
|
||||||
|
attrVal := parts[1:]
|
||||||
|
|
||||||
|
if len(listName) == 0 {
|
||||||
|
return nil, 0, fmt.Errorf("empty listname in rule: %s", countryCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
domains, err := geoLoader.LoadGeoSite(countryCode)
|
v, err, shared := loadGeoSiteMatcherSF.Do(listName, func() (interface{}, error) {
|
||||||
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return geoLoader.LoadGeoSite(listName)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if !shared {
|
||||||
|
loadGeoSiteMatcherSF.Forget(listName) // don't store the error result
|
||||||
|
}
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
domains := v.([]*router.Domain)
|
||||||
|
|
||||||
|
attrs := parseAttrs(attrVal)
|
||||||
|
if attrs.IsEmpty() {
|
||||||
|
if strings.Contains(countryCode, "@") {
|
||||||
|
log.Warnln("empty attribute list: %s", countryCode)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
filteredDomains := make([]*router.Domain, 0, len(domains))
|
||||||
|
hasAttrMatched := false
|
||||||
|
for _, domain := range domains {
|
||||||
|
if attrs.Match(domain) {
|
||||||
|
hasAttrMatched = true
|
||||||
|
filteredDomains = append(filteredDomains, domain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hasAttrMatched {
|
||||||
|
log.Warnln("attribute match no rule: geosite: %s", countryCode)
|
||||||
|
}
|
||||||
|
domains = filteredDomains
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
linear: linear algorithm
|
linear: linear algorithm
|
||||||
@ -68,25 +112,34 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
return matcher, len(domains), nil
|
return matcher, len(domains), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var loadGeoIPMatcherSF = singleflight.Group{}
|
||||||
|
|
||||||
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
||||||
if len(country) == 0 {
|
if len(country) == 0 {
|
||||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
}
|
}
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
not := false
|
not := false
|
||||||
if country[0] == '!' {
|
if country[0] == '!' {
|
||||||
not = true
|
not = true
|
||||||
country = country[1:]
|
country = country[1:]
|
||||||
}
|
}
|
||||||
|
country = strings.ToLower(country)
|
||||||
|
|
||||||
records, err := geoLoader.LoadGeoIP(country)
|
v, err, shared := loadGeoIPMatcherSF.Do(country, func() (interface{}, error) {
|
||||||
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return geoLoader.LoadGeoIP(country)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if !shared {
|
||||||
|
loadGeoIPMatcherSF.Forget(country) // don't store the error result
|
||||||
|
}
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
records := v.([]*router.CIDR)
|
||||||
|
|
||||||
geoIP := &router.GeoIP{
|
geoIP := &router.GeoIP{
|
||||||
CountryCode: country,
|
CountryCode: country,
|
||||||
@ -98,6 +151,10 @@ func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return matcher, len(records), nil
|
return matcher, len(records), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ClearCache() {
|
||||||
|
loadGeoSiteMatcherSF = singleflight.Group{}
|
||||||
|
loadGeoIPMatcherSF = singleflight.Group{}
|
||||||
|
}
|
||||||
|
@ -2,18 +2,19 @@ package http
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/Dreamacro/clash/component/tls"
|
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
URL "net/url"
|
URL "net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/listener/inner"
|
||||||
)
|
)
|
||||||
|
|
||||||
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) {
|
||||||
@ -52,7 +53,7 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
conn := inner.HandleTcp(address, urlRes.Hostname())
|
conn := inner.HandleTcp(address, "")
|
||||||
return conn, nil
|
return conn, nil
|
||||||
},
|
},
|
||||||
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
||||||
|
@ -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{}
|
||||||
|
@ -16,14 +16,6 @@ const (
|
|||||||
UDP = "udp"
|
UDP = "udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (*uint32, 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) (*uint32, error) {
|
|
||||||
_, uid, err := resolveSocketByNetlink(network, srcIP, srcPort)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &uid, nil
|
|
||||||
}
|
|
||||||
|
@ -33,11 +33,7 @@ var structSize = func() int {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
func findProcessName(network string, ip netip.Addr, port int) (uint32, string, error) {
|
||||||
return 0, 0, ErrPlatformNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, port int) (*uint32, string, error) {
|
|
||||||
var spath string
|
var spath string
|
||||||
switch network {
|
switch network {
|
||||||
case TCP:
|
case TCP:
|
||||||
@ -45,14 +41,14 @@ func findProcessName(network string, ip netip.Addr, port int) (*uint32, string,
|
|||||||
case UDP:
|
case UDP:
|
||||||
spath = "net.inet.udp.pcblist_n"
|
spath = "net.inet.udp.pcblist_n"
|
||||||
default:
|
default:
|
||||||
return nil, "", ErrInvalidNetwork
|
return 0, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
isIPv4 := ip.Is4()
|
isIPv4 := ip.Is4()
|
||||||
|
|
||||||
value, err := syscall.Sysctl(spath)
|
value, err := syscall.Sysctl(spath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := []byte(value)
|
buf := []byte(value)
|
||||||
@ -96,7 +92,7 @@ func findProcessName(network string, ip netip.Addr, port int) (*uint32, string,
|
|||||||
// xsocket_n.so_last_pid
|
// xsocket_n.so_last_pid
|
||||||
pid := readNativeUint32(buf[so+68 : so+72])
|
pid := readNativeUint32(buf[so+68 : so+72])
|
||||||
pp, err := getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
return nil, pp, err
|
return 0, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// udp packet connection may be not equal with srcIP
|
// udp packet connection may be not equal with srcIP
|
||||||
@ -106,10 +102,10 @@ func findProcessName(network string, ip netip.Addr, port int) (*uint32, string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
if network == UDP && fallbackUDPProcess != "" {
|
if network == UDP && fallbackUDPProcess != "" {
|
||||||
return nil, fallbackUDPProcess, nil
|
return 0, fallbackUDPProcess, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, "", ErrNotFound
|
return 0, "", ErrNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExecPathFromPID(pid uint32) (string, error) {
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
@ -21,11 +21,7 @@ var (
|
|||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
return 0, 0, ErrPlatformNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
if err := initSearcher(); err != nil {
|
if err := initSearcher(); err != nil {
|
||||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||||
@ -35,7 +31,7 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, strin
|
|||||||
})
|
})
|
||||||
|
|
||||||
if defaultSearcher == nil {
|
if defaultSearcher == nil {
|
||||||
return nil, "", ErrPlatformNotSupport
|
return 0, "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
var spath string
|
var spath string
|
||||||
@ -46,22 +42,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, strin
|
|||||||
case UDP:
|
case UDP:
|
||||||
spath = "net.inet.udp.pcblist"
|
spath = "net.inet.udp.pcblist"
|
||||||
default:
|
default:
|
||||||
return nil, "", ErrInvalidNetwork
|
return 0, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
value, err := syscall.Sysctl(spath)
|
value, err := syscall.Sysctl(spath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
buf := []byte(value)
|
buf := []byte(value)
|
||||||
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
pp, err := getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
return nil, pp, err
|
return 0, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExecPathFromPID(pid uint32) (string, error) {
|
func getExecPathFromPID(pid uint32) (string, error) {
|
||||||
|
@ -59,14 +59,14 @@ type inetDiagResponse struct {
|
|||||||
INode uint32
|
INode uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
uid, inode, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
pp, err := resolveProcessNameByProcSearch(inode, uid)
|
||||||
return &uid, pp, err
|
return uid, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
||||||
@ -119,7 +119,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32,
|
|||||||
|
|
||||||
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
|
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
|
||||||
|
|
||||||
return response.INode, response.UID, nil
|
return response.UID, response.INode, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0, 0, ErrNotFound
|
return 0, 0, ErrNotFound
|
||||||
|
@ -4,8 +4,8 @@ package process
|
|||||||
|
|
||||||
import "net/netip"
|
import "net/netip"
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
return nil, "", ErrPlatformNotSupport
|
return 0, "", ErrPlatformNotSupport
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
||||||
|
@ -62,7 +62,7 @@ func initWin32API() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
err := initWin32API()
|
err := initWin32API()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -86,22 +86,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, strin
|
|||||||
fn = getExUDPTable
|
fn = getExUDPTable
|
||||||
class = udpTablePid
|
class = udpTablePid
|
||||||
default:
|
default:
|
||||||
return nil, "", ErrInvalidNetwork
|
return 0, "", ErrInvalidNetwork
|
||||||
}
|
}
|
||||||
|
|
||||||
buf, err := getTransportTable(fn, family, class)
|
buf, err := getTransportTable(fn, family, class)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
s := newSearcher(family == windows.AF_INET, network == TCP)
|
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||||
|
|
||||||
pid, err := s.Search(buf, ip, uint16(srcPort))
|
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
pp, err := getExecPathFromPID(pid)
|
pp, err := getExecPathFromPID(pid)
|
||||||
return nil, pp, err
|
return 0, pp, err
|
||||||
}
|
}
|
||||||
|
|
||||||
type searcher struct {
|
type searcher struct {
|
||||||
|
113
component/resolver/host.go
Normal file
113
component/resolver/host.go
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
package resolver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Hosts struct {
|
||||||
|
*trie.DomainTrie[HostValue]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHosts(hosts *trie.DomainTrie[HostValue]) Hosts {
|
||||||
|
return Hosts{
|
||||||
|
hosts,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the search result and whether to match the parameter `isDomain`
|
||||||
|
func (h *Hosts) Search(domain string, isDomain bool) (*HostValue, bool) {
|
||||||
|
value := h.DomainTrie.Search(domain)
|
||||||
|
if value == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
hostValue := value.Data()
|
||||||
|
for {
|
||||||
|
if isDomain && hostValue.IsDomain {
|
||||||
|
return &hostValue, true
|
||||||
|
} else {
|
||||||
|
if node := h.DomainTrie.Search(hostValue.Domain); node != nil {
|
||||||
|
hostValue = node.Data()
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if isDomain == hostValue.IsDomain {
|
||||||
|
return &hostValue, true
|
||||||
|
}
|
||||||
|
return &hostValue, false
|
||||||
|
}
|
||||||
|
|
||||||
|
type HostValue struct {
|
||||||
|
IsDomain bool
|
||||||
|
IPs []netip.Addr
|
||||||
|
Domain string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHostValue(value any) (HostValue, error) {
|
||||||
|
isDomain := true
|
||||||
|
ips := make([]netip.Addr, 0)
|
||||||
|
domain := ""
|
||||||
|
if valueArr, err := utils.ToStringSlice(value); err != nil {
|
||||||
|
return HostValue{}, err
|
||||||
|
} else {
|
||||||
|
if len(valueArr) > 1 {
|
||||||
|
isDomain = false
|
||||||
|
for _, str := range valueArr {
|
||||||
|
if ip, err := netip.ParseAddr(str); err == nil {
|
||||||
|
ips = append(ips, ip)
|
||||||
|
} else {
|
||||||
|
return HostValue{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if len(valueArr) == 1 {
|
||||||
|
host := valueArr[0]
|
||||||
|
if ip, err := netip.ParseAddr(host); err == nil {
|
||||||
|
ips = append(ips, ip)
|
||||||
|
isDomain = false
|
||||||
|
} else {
|
||||||
|
domain = host
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if isDomain {
|
||||||
|
return NewHostValueByDomain(domain)
|
||||||
|
} else {
|
||||||
|
return NewHostValueByIPs(ips)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHostValueByIPs(ips []netip.Addr) (HostValue, error) {
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return HostValue{}, errors.New("ip list is empty")
|
||||||
|
}
|
||||||
|
return HostValue{
|
||||||
|
IsDomain: false,
|
||||||
|
IPs: ips,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHostValueByDomain(domain string) (HostValue, error) {
|
||||||
|
domain = strings.Trim(domain, ".")
|
||||||
|
item := strings.Split(domain, ".")
|
||||||
|
if len(item) < 2 {
|
||||||
|
return HostValue{}, errors.New("invaild domain")
|
||||||
|
}
|
||||||
|
return HostValue{
|
||||||
|
IsDomain: true,
|
||||||
|
Domain: domain,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hv HostValue) RandIP() (netip.Addr, error) {
|
||||||
|
if hv.IsDomain {
|
||||||
|
return netip.Addr{}, errors.New("value type is error")
|
||||||
|
}
|
||||||
|
return hv.IPs[fastrand.Intn(len(hv.IPs))], nil
|
||||||
|
}
|
@ -4,13 +4,16 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
|
||||||
|
"github.com/miekg/dns"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -25,7 +28,7 @@ var (
|
|||||||
DisableIPv6 = true
|
DisableIPv6 = true
|
||||||
|
|
||||||
// DefaultHosts aim to resolve hosts
|
// DefaultHosts aim to resolve hosts
|
||||||
DefaultHosts = trie.New[netip.Addr]()
|
DefaultHosts = NewHosts(trie.New[HostValue]())
|
||||||
|
|
||||||
// DefaultDNSTimeout defined the default dns request timeout
|
// DefaultDNSTimeout defined the default dns request timeout
|
||||||
DefaultDNSTimeout = time.Second * 5
|
DefaultDNSTimeout = time.Second * 5
|
||||||
@ -44,13 +47,16 @@ type Resolver interface {
|
|||||||
ResolveIP(ctx context.Context, host string) (ip netip.Addr, err error)
|
ResolveIP(ctx context.Context, host string) (ip netip.Addr, err error)
|
||||||
ResolveIPv4(ctx context.Context, host string) (ip netip.Addr, err error)
|
ResolveIPv4(ctx context.Context, host string) (ip netip.Addr, err error)
|
||||||
ResolveIPv6(ctx context.Context, host string) (ip netip.Addr, err error)
|
ResolveIPv6(ctx context.Context, host string) (ip netip.Addr, err error)
|
||||||
|
ExchangeContext(ctx context.Context, m *dns.Msg) (msg *dns.Msg, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LookupIPv4WithResolver same as LookupIPv4, but with a resolver
|
// LookupIPv4WithResolver same as LookupIPv4, but with a resolver
|
||||||
func LookupIPv4WithResolver(ctx context.Context, host string, r Resolver) ([]netip.Addr, error) {
|
func LookupIPv4WithResolver(ctx context.Context, host string, r Resolver) ([]netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node, ok := DefaultHosts.Search(host, false); ok {
|
||||||
if ip := node.Data(); ip.Is4() {
|
if addrs := utils.Filter(node.IPs, func(ip netip.Addr) bool {
|
||||||
return []netip.Addr{node.Data()}, nil
|
return ip.Is4()
|
||||||
|
}); len(addrs) > 0 {
|
||||||
|
return addrs, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,10 +72,6 @@ func LookupIPv4WithResolver(ctx context.Context, host string, r Resolver) ([]net
|
|||||||
return r.LookupIPv4(ctx, host)
|
return r.LookupIPv4(ctx, host)
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver != nil {
|
|
||||||
return DefaultResolver.LookupIPv4(ctx, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
ipAddrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host)
|
ipAddrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -93,7 +95,7 @@ func ResolveIPv4WithResolver(ctx context.Context, host string, r Resolver) (neti
|
|||||||
} else if len(ips) == 0 {
|
} else if len(ips) == 0 {
|
||||||
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
}
|
}
|
||||||
return ips[rand.Intn(len(ips))], nil
|
return ips[fastrand.Intn(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv4 with a host, return ipv4
|
// ResolveIPv4 with a host, return ipv4
|
||||||
@ -107,9 +109,11 @@ func LookupIPv6WithResolver(ctx context.Context, host string, r Resolver) ([]net
|
|||||||
return nil, ErrIPv6Disabled
|
return nil, ErrIPv6Disabled
|
||||||
}
|
}
|
||||||
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node, ok := DefaultHosts.Search(host, false); ok {
|
||||||
if ip := node.Data(); ip.Is6() {
|
if addrs := utils.Filter(node.IPs, func(ip netip.Addr) bool {
|
||||||
return []netip.Addr{ip}, nil
|
return ip.Is6()
|
||||||
|
}); len(addrs) > 0 {
|
||||||
|
return addrs, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -123,9 +127,6 @@ func LookupIPv6WithResolver(ctx context.Context, host string, r Resolver) ([]net
|
|||||||
if r != nil {
|
if r != nil {
|
||||||
return r.LookupIPv6(ctx, host)
|
return r.LookupIPv6(ctx, host)
|
||||||
}
|
}
|
||||||
if DefaultResolver != nil {
|
|
||||||
return DefaultResolver.LookupIPv6(ctx, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
ipAddrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip6", host)
|
ipAddrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip6", host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -150,7 +151,7 @@ func ResolveIPv6WithResolver(ctx context.Context, host string, r Resolver) (neti
|
|||||||
} else if len(ips) == 0 {
|
} else if len(ips) == 0 {
|
||||||
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
}
|
}
|
||||||
return ips[rand.Intn(len(ips))], nil
|
return ips[fastrand.Intn(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
|
func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
|
||||||
@ -159,8 +160,8 @@ func ResolveIPv6(ctx context.Context, host string) (netip.Addr, error) {
|
|||||||
|
|
||||||
// LookupIPWithResolver same as LookupIP, but with a resolver
|
// LookupIPWithResolver same as LookupIP, but with a resolver
|
||||||
func LookupIPWithResolver(ctx context.Context, host string, r Resolver) ([]netip.Addr, error) {
|
func LookupIPWithResolver(ctx context.Context, host string, r Resolver) ([]netip.Addr, error) {
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node, ok := DefaultHosts.Search(host, false); ok {
|
||||||
return []netip.Addr{node.Data()}, nil
|
return node.IPs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
if r != nil {
|
||||||
@ -169,7 +170,7 @@ func LookupIPWithResolver(ctx context.Context, host string, r Resolver) ([]netip
|
|||||||
}
|
}
|
||||||
return r.LookupIP(ctx, host)
|
return r.LookupIP(ctx, host)
|
||||||
} else if DisableIPv6 {
|
} else if DisableIPv6 {
|
||||||
return LookupIPv4(ctx, host)
|
return LookupIPv4WithResolver(ctx, host, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip, err := netip.ParseAddr(host); err == nil {
|
if ip, err := netip.ParseAddr(host); err == nil {
|
||||||
@ -199,7 +200,7 @@ func ResolveIPWithResolver(ctx context.Context, host string, r Resolver) (netip.
|
|||||||
} else if len(ips) == 0 {
|
} else if len(ips) == 0 {
|
||||||
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
return netip.Addr{}, fmt.Errorf("%w: %s", ErrIPNotFound, host)
|
||||||
}
|
}
|
||||||
return ips[rand.Intn(len(ips))], nil
|
return ips[fastrand.Intn(len(ips))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIP with a host, return ip
|
// ResolveIP with a host, return ip
|
||||||
|
@ -57,7 +57,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
|||||||
f.UpdatedAt = &modTime
|
f.UpdatedAt = &modTime
|
||||||
isLocal = true
|
isLocal = true
|
||||||
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
||||||
log.Infoln("[Provider] %s not updated for a long time, force refresh", f.Name())
|
log.Warnln("[Provider] %s not updated for a long time, force refresh", f.Name())
|
||||||
forceUpdate = true
|
forceUpdate = true
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -162,7 +162,7 @@ func (f *Fetcher[V]) pullLoop() {
|
|||||||
case <-f.ticker.C:
|
case <-f.ticker.C:
|
||||||
elm, same, err := f.Update()
|
elm, same, err := f.Update()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
log.Errorln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
53
component/sniffer/base_sniffer.go
Normal file
53
component/sniffer/base_sniffer.go
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package sniffer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
"github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SnifferConfig struct {
|
||||||
|
OverrideDest bool
|
||||||
|
Ports []utils.Range[uint16]
|
||||||
|
}
|
||||||
|
|
||||||
|
type BaseSniffer struct {
|
||||||
|
ports []utils.Range[uint16]
|
||||||
|
supportNetworkType constant.NetWork
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protocol implements sniffer.Sniffer
|
||||||
|
func (*BaseSniffer) Protocol() string {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
// SniffTCP implements sniffer.Sniffer
|
||||||
|
func (*BaseSniffer) SniffTCP(bytes []byte) (string, error) {
|
||||||
|
return "", errors.New("TODO")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportNetwork implements sniffer.Sniffer
|
||||||
|
func (bs *BaseSniffer) SupportNetwork() constant.NetWork {
|
||||||
|
return bs.supportNetworkType
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportPort implements sniffer.Sniffer
|
||||||
|
func (bs *BaseSniffer) SupportPort(port uint16) bool {
|
||||||
|
for _, portRange := range bs.ports {
|
||||||
|
if portRange.Contains(port) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBaseSniffer(ports []utils.Range[uint16], networkType constant.NetWork) *BaseSniffer {
|
||||||
|
return &BaseSniffer{
|
||||||
|
ports: ports,
|
||||||
|
supportNetworkType: networkType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ sniffer.Sniffer = (*BaseSniffer)(nil)
|
@ -11,7 +11,6 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/sniffer"
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
@ -27,26 +26,17 @@ var (
|
|||||||
var Dispatcher *SnifferDispatcher
|
var Dispatcher *SnifferDispatcher
|
||||||
|
|
||||||
type SnifferDispatcher struct {
|
type SnifferDispatcher struct {
|
||||||
enable bool
|
enable bool
|
||||||
|
sniffers map[sniffer.Sniffer]SnifferConfig
|
||||||
sniffers []sniffer.Sniffer
|
forceDomain *trie.DomainTrie[struct{}]
|
||||||
|
skipSNI *trie.DomainTrie[struct{}]
|
||||||
forceDomain *trie.DomainTrie[struct{}]
|
skipList *cache.LruCache[string, uint8]
|
||||||
skipSNI *trie.DomainTrie[struct{}]
|
rwMux sync.RWMutex
|
||||||
portRanges *[]utils.Range[uint16]
|
|
||||||
skipList *cache.LruCache[string, uint8]
|
|
||||||
rwMux sync.RWMutex
|
|
||||||
|
|
||||||
forceDnsMapping bool
|
forceDnsMapping bool
|
||||||
parsePureIp bool
|
parsePureIp bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata) {
|
||||||
bufConn, ok := conn.(*N.BufferedConn)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (metadata.Host == "" && sd.parsePureIp) || sd.forceDomain.Search(metadata.Host) != nil || (metadata.DNSMode == C.DNSMapping && sd.forceDnsMapping) {
|
if (metadata.Host == "" && sd.parsePureIp) || sd.forceDomain.Search(metadata.Host) != nil || (metadata.DNSMode == C.DNSMapping && sd.forceDnsMapping) {
|
||||||
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, err := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -55,10 +45,14 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inWhitelist := false
|
inWhitelist := false
|
||||||
for _, portRange := range *sd.portRanges {
|
overrideDest := false
|
||||||
if portRange.Contains(uint16(port)) {
|
for sniffer, config := range sd.sniffers {
|
||||||
inWhitelist = true
|
if sniffer.SupportNetwork() == C.TCP || sniffer.SupportNetwork() == C.ALLNet {
|
||||||
break
|
inWhitelist = sniffer.SupportPort(uint16(port))
|
||||||
|
if inWhitelist {
|
||||||
|
overrideDest = config.OverrideDest
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,7 +69,7 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
|||||||
}
|
}
|
||||||
sd.rwMux.RUnlock()
|
sd.rwMux.RUnlock()
|
||||||
|
|
||||||
if host, err := sd.sniffDomain(bufConn, metadata); err != nil {
|
if host, err := sd.sniffDomain(conn, metadata); err != nil {
|
||||||
sd.cacheSniffFailed(metadata)
|
sd.cacheSniffFailed(metadata)
|
||||||
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%s] to [%s:%s]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
log.Debugln("[Sniffer] All sniffing sniff failed with from [%s:%s] to [%s:%s]", metadata.SrcIP, metadata.SrcPort, metadata.String(), metadata.DstPort)
|
||||||
return
|
return
|
||||||
@ -89,31 +83,21 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
|||||||
sd.skipList.Delete(dst)
|
sd.skipList.Delete(dst)
|
||||||
sd.rwMux.RUnlock()
|
sd.rwMux.RUnlock()
|
||||||
|
|
||||||
sd.replaceDomain(metadata, host)
|
sd.replaceDomain(metadata, host, overrideDest)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string) {
|
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string, overrideDest bool) {
|
||||||
dstIP := ""
|
metadata.SniffHost = host
|
||||||
if metadata.DstIP.IsValid() {
|
if overrideDest {
|
||||||
dstIP = metadata.DstIP.String()
|
metadata.Host = host
|
||||||
}
|
}
|
||||||
originHost := metadata.Host
|
|
||||||
if originHost != host {
|
|
||||||
log.Infoln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
|
||||||
metadata.SrcIP, metadata.SrcPort,
|
|
||||||
dstIP, metadata.DstPort,
|
|
||||||
metadata.Host, host)
|
|
||||||
} else {
|
|
||||||
log.Debugln("[Sniffer] Sniff TCP [%s:%s]-->[%s:%s] success, replace domain [%s]-->[%s]",
|
|
||||||
metadata.SrcIP, metadata.SrcPort,
|
|
||||||
dstIP, metadata.DstPort,
|
|
||||||
metadata.Host, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
metadata.Host = host
|
|
||||||
metadata.DNSMode = C.DNSNormal
|
metadata.DNSMode = C.DNSNormal
|
||||||
|
log.Debugln("[Sniffer] Sniff TCP [%s]-->[%s] success, replace domain [%s]-->[%s]",
|
||||||
|
metadata.SourceDetail(),
|
||||||
|
metadata.RemoteAddress(),
|
||||||
|
metadata.Host, host)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) Enable() bool {
|
func (sd *SnifferDispatcher) Enable() bool {
|
||||||
@ -121,7 +105,7 @@ func (sd *SnifferDispatcher) Enable() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (sd *SnifferDispatcher) sniffDomain(conn *N.BufferedConn, metadata *C.Metadata) (string, error) {
|
func (sd *SnifferDispatcher) sniffDomain(conn *N.BufferedConn, metadata *C.Metadata) (string, error) {
|
||||||
for _, s := range sd.sniffers {
|
for s := range sd.sniffers {
|
||||||
if s.SupportNetwork() == C.TCP {
|
if s.SupportNetwork() == C.TCP {
|
||||||
_ = conn.SetReadDeadline(time.Now().Add(1 * time.Second))
|
_ = conn.SetReadDeadline(time.Now().Add(1 * time.Second))
|
||||||
_, err := conn.Peek(1)
|
_, err := conn.Peek(1)
|
||||||
@ -182,38 +166,37 @@ func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
|||||||
return &dispatcher, nil
|
return &dispatcher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnifferDispatcher(needSniffer []sniffer.Type, forceDomain *trie.DomainTrie[struct{}],
|
func NewSnifferDispatcher(snifferConfig map[sniffer.Type]SnifferConfig, forceDomain *trie.DomainTrie[struct{}],
|
||||||
skipSNI *trie.DomainTrie[struct{}], ports *[]utils.Range[uint16],
|
skipSNI *trie.DomainTrie[struct{}],
|
||||||
forceDnsMapping bool, parsePureIp bool) (*SnifferDispatcher, error) {
|
forceDnsMapping bool, parsePureIp bool) (*SnifferDispatcher, error) {
|
||||||
dispatcher := SnifferDispatcher{
|
dispatcher := SnifferDispatcher{
|
||||||
enable: true,
|
enable: true,
|
||||||
forceDomain: forceDomain,
|
forceDomain: forceDomain,
|
||||||
skipSNI: skipSNI,
|
skipSNI: skipSNI,
|
||||||
portRanges: ports,
|
skipList: cache.New(cache.WithSize[string, uint8](128), cache.WithAge[string, uint8](600)),
|
||||||
skipList: cache.New[string, uint8](cache.WithSize[string, uint8](128), cache.WithAge[string, uint8](600)),
|
|
||||||
forceDnsMapping: forceDnsMapping,
|
forceDnsMapping: forceDnsMapping,
|
||||||
parsePureIp: parsePureIp,
|
parsePureIp: parsePureIp,
|
||||||
|
sniffers: make(map[sniffer.Sniffer]SnifferConfig, 0),
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, snifferName := range needSniffer {
|
for snifferName, config := range snifferConfig {
|
||||||
s, err := NewSniffer(snifferName)
|
s, err := NewSniffer(snifferName, config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorln("Sniffer name[%s] is error", snifferName)
|
log.Errorln("Sniffer name[%s] is error", snifferName)
|
||||||
return &SnifferDispatcher{enable: false}, err
|
return &SnifferDispatcher{enable: false}, err
|
||||||
}
|
}
|
||||||
|
dispatcher.sniffers[s] = config
|
||||||
dispatcher.sniffers = append(dispatcher.sniffers, s)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &dispatcher, nil
|
return &dispatcher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSniffer(name sniffer.Type) (sniffer.Sniffer, error) {
|
func NewSniffer(name sniffer.Type, snifferConfig SnifferConfig) (sniffer.Sniffer, error) {
|
||||||
switch name {
|
switch name {
|
||||||
case sniffer.TLS:
|
case sniffer.TLS:
|
||||||
return &TLSSniffer{}, nil
|
return NewTLSSniffer(snifferConfig)
|
||||||
case sniffer.HTTP:
|
case sniffer.HTTP:
|
||||||
return &HTTPSniffer{}, nil
|
return NewHTTPSniffer(snifferConfig)
|
||||||
default:
|
default:
|
||||||
return nil, ErrorUnsupportedSniffer
|
return nil, ErrorUnsupportedSniffer
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,9 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -24,10 +26,25 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type HTTPSniffer struct {
|
type HTTPSniffer struct {
|
||||||
|
*BaseSniffer
|
||||||
version version
|
version version
|
||||||
host string
|
host string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ sniffer.Sniffer = (*HTTPSniffer)(nil)
|
||||||
|
|
||||||
|
func NewHTTPSniffer(snifferConfig SnifferConfig) (*HTTPSniffer, error) {
|
||||||
|
ports := make([]utils.Range[uint16], 0)
|
||||||
|
if len(snifferConfig.Ports) == 0 {
|
||||||
|
ports = append(ports, *utils.NewRange[uint16](80, 80))
|
||||||
|
} else {
|
||||||
|
ports = append(ports, snifferConfig.Ports...)
|
||||||
|
}
|
||||||
|
return &HTTPSniffer{
|
||||||
|
BaseSniffer: NewBaseSniffer(ports, C.TCP),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (http *HTTPSniffer) Protocol() string {
|
func (http *HTTPSniffer) Protocol() string {
|
||||||
switch http.version {
|
switch http.version {
|
||||||
case HTTP1:
|
case HTTP1:
|
||||||
|
@ -5,7 +5,9 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/sniffer"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -13,7 +15,22 @@ var (
|
|||||||
errNotClientHello = errors.New("not client hello")
|
errNotClientHello = errors.New("not client hello")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ sniffer.Sniffer = (*TLSSniffer)(nil)
|
||||||
|
|
||||||
type TLSSniffer struct {
|
type TLSSniffer struct {
|
||||||
|
*BaseSniffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTLSSniffer(snifferConfig SnifferConfig) (*TLSSniffer, error) {
|
||||||
|
ports := make([]utils.Range[uint16], 0)
|
||||||
|
if len(snifferConfig.Ports) == 0 {
|
||||||
|
ports = append(ports, *utils.NewRange[uint16](443, 443))
|
||||||
|
} else {
|
||||||
|
ports = append(ports, snifferConfig.Ports...)
|
||||||
|
}
|
||||||
|
return &TLSSniffer{
|
||||||
|
BaseSniffer: NewBaseSniffer(ports, C.TCP),
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tls *TLSSniffer) Protocol() string {
|
func (tls *TLSSniffer) Protocol() string {
|
||||||
|
@ -6,75 +6,81 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
xtls "github.com/xtls/go"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
xtls "github.com/xtls/go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var globalFingerprints = make([][32]byte, 0, 0)
|
var trustCerts []*x509.Certificate
|
||||||
var mutex sync.Mutex
|
|
||||||
|
|
||||||
func verifyPeerCertificateAndFingerprints(fingerprints *[][32]byte, insecureSkipVerify bool) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
var mutex sync.RWMutex
|
||||||
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
var errNotMacth error = errors.New("certificate fingerprints do not match")
|
||||||
if insecureSkipVerify {
|
|
||||||
return nil
|
func AddCertificate(certificate string) error {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
if certificate == "" {
|
||||||
|
return fmt.Errorf("certificate is empty")
|
||||||
|
}
|
||||||
|
if cert, err := x509.ParseCertificate([]byte(certificate)); err == nil {
|
||||||
|
trustCerts = append(trustCerts, cert)
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("add certificate failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResetCertificate() {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
trustCerts = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCertPool() *x509.CertPool {
|
||||||
|
certPool, err := x509.SystemCertPool()
|
||||||
|
if err == nil {
|
||||||
|
for _, cert := range trustCerts {
|
||||||
|
certPool.AddCert(cert)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
return certPool
|
||||||
|
}
|
||||||
|
|
||||||
var preErr error
|
func verifyFingerprint(fingerprint *[32]byte) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
|
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
|
// ssl pining
|
||||||
for i := range rawCerts {
|
for i := range rawCerts {
|
||||||
rawCert := rawCerts[i]
|
rawCert := rawCerts[i]
|
||||||
cert, err := x509.ParseCertificate(rawCert)
|
cert, err := x509.ParseCertificate(rawCert)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
opts := x509.VerifyOptions{
|
hash := sha256.Sum256(cert.Raw)
|
||||||
CurrentTime: time.Now(),
|
if bytes.Equal(fingerprint[:], hash[:]) {
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := cert.Verify(opts); err == nil {
|
|
||||||
return nil
|
return nil
|
||||||
} else {
|
|
||||||
fingerprint := sha256.Sum256(cert.Raw)
|
|
||||||
for _, fp := range *fingerprints {
|
|
||||||
if bytes.Equal(fingerprint[:], fp[:]) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
preErr = err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return errNotMacth
|
||||||
return preErr
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func AddCertFingerprint(fingerprint string) error {
|
|
||||||
fpByte, err2 := convertFingerprint(fingerprint)
|
|
||||||
if err2 != nil {
|
|
||||||
return err2
|
|
||||||
}
|
|
||||||
|
|
||||||
mutex.Lock()
|
|
||||||
globalFingerprints = append(globalFingerprints, *fpByte)
|
|
||||||
mutex.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertFingerprint(fingerprint string) (*[32]byte, error) {
|
func convertFingerprint(fingerprint string) (*[32]byte, error) {
|
||||||
|
fingerprint = strings.TrimSpace(strings.Replace(fingerprint, ":", "", -1))
|
||||||
fpByte, err := hex.DecodeString(fingerprint)
|
fpByte, err := hex.DecodeString(fingerprint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(fpByte) != 32 {
|
if len(fpByte) != 32 {
|
||||||
return nil, fmt.Errorf("fingerprint string length error,need sha25 fingerprint")
|
return nil, fmt.Errorf("fingerprint string length error,need sha256 fingerprint")
|
||||||
}
|
}
|
||||||
return (*[32]byte)(fpByte), nil
|
return (*[32]byte)(fpByte), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetDefaultTLSConfig() *tls.Config {
|
func GetDefaultTLSConfig() *tls.Config {
|
||||||
return GetGlobalFingerprintTLCConfig(nil)
|
return GetGlobalTLSConfig(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
||||||
@ -82,29 +88,21 @@ func GetSpecifiedFingerprintTLSConfig(tlsConfig *tls.Config, fingerprint string)
|
|||||||
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
if tlsConfig == nil {
|
tlsConfig = GetGlobalTLSConfig(tlsConfig)
|
||||||
return &tls.Config{
|
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
||||||
InsecureSkipVerify: true,
|
tlsConfig.InsecureSkipVerify = true
|
||||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
return tlsConfig, nil
|
||||||
}, nil
|
|
||||||
} else {
|
|
||||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
return tlsConfig, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetGlobalFingerprintTLCConfig(tlsConfig *tls.Config) *tls.Config {
|
func GetGlobalTLSConfig(tlsConfig *tls.Config) *tls.Config {
|
||||||
|
certPool := getCertPool()
|
||||||
if tlsConfig == nil {
|
if tlsConfig == nil {
|
||||||
return &tls.Config{
|
return &tls.Config{
|
||||||
InsecureSkipVerify: true,
|
RootCAs: certPool,
|
||||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tlsConfig.RootCAs = certPool
|
||||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
return tlsConfig
|
return tlsConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -113,28 +111,21 @@ func GetSpecifiedFingerprintXTLSConfig(tlsConfig *xtls.Config, fingerprint strin
|
|||||||
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
} else {
|
} else {
|
||||||
if tlsConfig == nil {
|
tlsConfig = GetGlobalXTLSConfig(tlsConfig)
|
||||||
return &xtls.Config{
|
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
||||||
InsecureSkipVerify: true,
|
tlsConfig.InsecureSkipVerify = true
|
||||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
return tlsConfig, nil
|
||||||
}, nil
|
|
||||||
} else {
|
|
||||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
return tlsConfig, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetGlobalFingerprintXTLCConfig(tlsConfig *xtls.Config) *xtls.Config {
|
func GetGlobalXTLSConfig(tlsConfig *xtls.Config) *xtls.Config {
|
||||||
|
certPool := getCertPool()
|
||||||
if tlsConfig == nil {
|
if tlsConfig == nil {
|
||||||
return &xtls.Config{
|
return &xtls.Config{
|
||||||
InsecureSkipVerify: true,
|
RootCAs: certPool,
|
||||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
tlsConfig.RootCAs = certPool
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
return tlsConfig
|
return tlsConfig
|
||||||
}
|
}
|
||||||
|
164
component/tls/reality.go
Normal file
164
component/tls/reality.go
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/sha512"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/utils"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
utls "github.com/sagernet/utls"
|
||||||
|
"github.com/zhangyunhao116/fastrand"
|
||||||
|
"golang.org/x/crypto/curve25519"
|
||||||
|
"golang.org/x/crypto/hkdf"
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const RealityMaxShortIDLen = 8
|
||||||
|
|
||||||
|
type RealityConfig struct {
|
||||||
|
PublicKey [curve25519.ScalarSize]byte
|
||||||
|
ShortID [RealityMaxShortIDLen]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRealityConn(ctx context.Context, conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config, realityConfig *RealityConfig) (net.Conn, error) {
|
||||||
|
if fingerprint, exists := GetFingerprint(ClientFingerprint); exists {
|
||||||
|
verifier := &realityVerifier{
|
||||||
|
serverName: tlsConfig.ServerName,
|
||||||
|
}
|
||||||
|
uConfig := &utls.Config{
|
||||||
|
ServerName: tlsConfig.ServerName,
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
SessionTicketsDisabled: true,
|
||||||
|
VerifyPeerCertificate: verifier.VerifyPeerCertificate,
|
||||||
|
}
|
||||||
|
clientID := utls.ClientHelloID{
|
||||||
|
Client: fingerprint.Client,
|
||||||
|
Version: fingerprint.Version,
|
||||||
|
Seed: fingerprint.Seed,
|
||||||
|
}
|
||||||
|
uConn := utls.UClient(conn, uConfig, clientID)
|
||||||
|
verifier.UConn = uConn
|
||||||
|
err := uConn.BuildHandshakeState()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
hello := uConn.HandshakeState.Hello
|
||||||
|
for i := range hello.SessionId { // https://github.com/golang/go/issues/5373
|
||||||
|
hello.SessionId[i] = 0
|
||||||
|
}
|
||||||
|
copy(hello.Raw[39:], hello.SessionId)
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint64(hello.SessionId, uint64(time.Now().Unix()))
|
||||||
|
|
||||||
|
hello.SessionId[0] = 1
|
||||||
|
hello.SessionId[1] = 8
|
||||||
|
hello.SessionId[2] = 0
|
||||||
|
copy(hello.SessionId[8:], realityConfig.ShortID[:])
|
||||||
|
|
||||||
|
//log.Debugln("REALITY hello.sessionId[:16]: %v", hello.SessionId[:16])
|
||||||
|
|
||||||
|
authKey := uConn.HandshakeState.State13.EcdheParams.SharedKey(realityConfig.PublicKey[:])
|
||||||
|
if authKey == nil {
|
||||||
|
return nil, errors.New("nil auth_key")
|
||||||
|
}
|
||||||
|
verifier.authKey = authKey
|
||||||
|
_, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
aesBlock, _ := aes.NewCipher(authKey)
|
||||||
|
aesGcmCipher, _ := cipher.NewGCM(aesBlock)
|
||||||
|
aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
||||||
|
copy(hello.Raw[39:], hello.SessionId)
|
||||||
|
//log.Debugln("REALITY hello.sessionId: %v", hello.SessionId)
|
||||||
|
//log.Debugln("REALITY uConn.AuthKey: %v", authKey)
|
||||||
|
|
||||||
|
err = uConn.HandshakeContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugln("REALITY Authentication: %v", verifier.verified)
|
||||||
|
|
||||||
|
if !verifier.verified {
|
||||||
|
go realityClientFallback(uConn, uConfig.ServerName, clientID)
|
||||||
|
return nil, errors.New("REALITY authentication failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
return uConn, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("unknown uTLS fingerprint")
|
||||||
|
}
|
||||||
|
|
||||||
|
func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
|
||||||
|
defer uConn.Close()
|
||||||
|
client := http.Client{
|
||||||
|
Transport: &http2.Transport{
|
||||||
|
DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
|
||||||
|
return uConn, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
request, _ := http.NewRequest("GET", "https://"+serverName, nil)
|
||||||
|
request.Header.Set("User-Agent", fingerprint.Client)
|
||||||
|
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", fastrand.Intn(32)+30)})
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
//_, _ = io.Copy(io.Discard, response.Body)
|
||||||
|
time.Sleep(time.Duration(5+fastrand.Int63n(10)) * time.Second)
|
||||||
|
response.Body.Close()
|
||||||
|
client.CloseIdleConnections()
|
||||||
|
}
|
||||||
|
|
||||||
|
type realityVerifier struct {
|
||||||
|
*utls.UConn
|
||||||
|
serverName string
|
||||||
|
authKey []byte
|
||||||
|
verified bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var pOffset = utils.MustOK(reflect.TypeOf((*utls.UConn)(nil)).Elem().FieldByName("peerCertificates")).Offset
|
||||||
|
|
||||||
|
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||||
|
//p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
|
||||||
|
certs := *(*[]*x509.Certificate)(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + pOffset))
|
||||||
|
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
|
||||||
|
h := hmac.New(sha512.New, c.authKey)
|
||||||
|
h.Write(pub)
|
||||||
|
if bytes.Equal(h.Sum(nil), certs[0].Signature) {
|
||||||
|
c.verified = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
opts := x509.VerifyOptions{
|
||||||
|
DNSName: c.serverName,
|
||||||
|
Intermediates: x509.NewCertPool(),
|
||||||
|
}
|
||||||
|
for _, cert := range certs[1:] {
|
||||||
|
opts.Intermediates.AddCert(cert)
|
||||||
|
}
|
||||||
|
if _, err := certs[0].Verify(opts); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
140
component/tls/utls.go
Normal file
140
component/tls/utls.go
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
package tls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/mroth/weightedrand/v2"
|
||||||
|
utls "github.com/sagernet/utls"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UConn struct {
|
||||||
|
*utls.UConn
|
||||||
|
}
|
||||||
|
|
||||||
|
type UClientHelloID struct {
|
||||||
|
*utls.ClientHelloID
|
||||||
|
}
|
||||||
|
|
||||||
|
var initRandomFingerprint UClientHelloID
|
||||||
|
var initUtlsClient string
|
||||||
|
|
||||||
|
func UClient(c net.Conn, config *tls.Config, fingerprint UClientHelloID) net.Conn {
|
||||||
|
utlsConn := utls.UClient(c, copyConfig(config), utls.ClientHelloID{
|
||||||
|
Client: fingerprint.Client,
|
||||||
|
Version: fingerprint.Version,
|
||||||
|
Seed: fingerprint.Seed,
|
||||||
|
})
|
||||||
|
return &UConn{UConn: utlsConn}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetFingerprint(ClientFingerprint string) (UClientHelloID, bool) {
|
||||||
|
if ClientFingerprint == "none" {
|
||||||
|
return UClientHelloID{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if initRandomFingerprint.ClientHelloID == nil {
|
||||||
|
initRandomFingerprint, _ = RollFingerprint()
|
||||||
|
}
|
||||||
|
|
||||||
|
if ClientFingerprint == "random" {
|
||||||
|
log.Debugln("use initial random HelloID:%s", initRandomFingerprint.Client)
|
||||||
|
return initRandomFingerprint, true
|
||||||
|
}
|
||||||
|
|
||||||
|
fingerprint, ok := Fingerprints[ClientFingerprint]
|
||||||
|
if ok {
|
||||||
|
log.Debugln("use specified fingerprint:%s", fingerprint.Client)
|
||||||
|
return fingerprint, ok
|
||||||
|
} else {
|
||||||
|
log.Warnln("wrong ClientFingerprint:%s", ClientFingerprint)
|
||||||
|
return UClientHelloID{}, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RollFingerprint() (UClientHelloID, bool) {
|
||||||
|
chooser, _ := weightedrand.NewChooser(
|
||||||
|
weightedrand.NewChoice("chrome", 6),
|
||||||
|
weightedrand.NewChoice("safari", 3),
|
||||||
|
weightedrand.NewChoice("ios", 2),
|
||||||
|
weightedrand.NewChoice("firefox", 1),
|
||||||
|
)
|
||||||
|
initClient := chooser.Pick()
|
||||||
|
log.Debugln("initial random HelloID:%s", initClient)
|
||||||
|
fingerprint, ok := Fingerprints[initClient]
|
||||||
|
return fingerprint, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
var Fingerprints = map[string]UClientHelloID{
|
||||||
|
"chrome": {&utls.HelloChrome_Auto},
|
||||||
|
"firefox": {&utls.HelloFirefox_Auto},
|
||||||
|
"safari": {&utls.HelloSafari_Auto},
|
||||||
|
"ios": {&utls.HelloIOS_Auto},
|
||||||
|
"android": {&utls.HelloAndroid_11_OkHttp},
|
||||||
|
"edge": {&utls.HelloEdge_Auto},
|
||||||
|
"360": {&utls.Hello360_Auto},
|
||||||
|
"qq": {&utls.HelloQQ_Auto},
|
||||||
|
"random": {nil},
|
||||||
|
"randomized": {nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
weights := utls.DefaultWeights
|
||||||
|
weights.TLSVersMax_Set_VersionTLS13 = 1
|
||||||
|
weights.FirstKeyShare_Set_CurveP256 = 0
|
||||||
|
randomized := utls.HelloRandomized
|
||||||
|
randomized.Seed, _ = utls.NewPRNGSeed()
|
||||||
|
randomized.Weights = &weights
|
||||||
|
Fingerprints["randomized"] = UClientHelloID{&randomized}
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyConfig(c *tls.Config) *utls.Config {
|
||||||
|
return &utls.Config{
|
||||||
|
RootCAs: c.RootCAs,
|
||||||
|
ServerName: c.ServerName,
|
||||||
|
InsecureSkipVerify: c.InsecureSkipVerify,
|
||||||
|
VerifyPeerCertificate: c.VerifyPeerCertificate,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebsocketHandshake basically calls UConn.Handshake inside it but it will only send
|
||||||
|
// http/1.1 in its ALPN.
|
||||||
|
// Copy from https://github.com/XTLS/Xray-core/blob/main/transport/internet/tls/tls.go
|
||||||
|
func (c *UConn) WebsocketHandshake() error {
|
||||||
|
// Build the handshake state. This will apply every variable of the TLS of the
|
||||||
|
// fingerprint in the UConn
|
||||||
|
if err := c.BuildHandshakeState(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Iterate over extensions and check for utls.ALPNExtension
|
||||||
|
hasALPNExtension := false
|
||||||
|
for _, extension := range c.Extensions {
|
||||||
|
if alpn, ok := extension.(*utls.ALPNExtension); ok {
|
||||||
|
hasALPNExtension = true
|
||||||
|
alpn.AlpnProtocols = []string{"http/1.1"}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hasALPNExtension { // Append extension if doesn't exists
|
||||||
|
c.Extensions = append(c.Extensions, &utls.ALPNExtension{AlpnProtocols: []string{"http/1.1"}})
|
||||||
|
}
|
||||||
|
// Rebuild the client hello and do the handshake
|
||||||
|
if err := c.BuildHandshakeState(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.Handshake()
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetGlobalUtlsClient(Client string) {
|
||||||
|
initUtlsClient = Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func HaveGlobalFingerprint() bool {
|
||||||
|
return len(initUtlsClient) != 0 && initUtlsClient != "none"
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetGlobalFingerprint() string {
|
||||||
|
return initUtlsClient
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user