Compare commits
158 Commits
Author | SHA1 | Date | |
---|---|---|---|
7468d08e4d | |||
72ab200faf | |||
8df44a7c3d | |||
cdd91f5132 | |||
05f877a324 | |||
f565edd76d | |||
a3b8c9c233 | |||
de92bc0234 | |||
e6377eac9b | |||
22726c1de8 | |||
bce3aeb218 | |||
81722610d5 | |||
5bfad04b41 | |||
880664c6ab | |||
8f0c61ed14 | |||
7d524668e0 | |||
75680c5866 | |||
a1d008e6f0 | |||
d5d62a4ffd | |||
b72bd5bb37 | |||
7fecd20a1d | |||
f586f22ce3 | |||
21848d6bf1 | |||
28c57c4144 | |||
4a6ebff473 | |||
5c8d955f61 | |||
baaf509637 | |||
db3e1b9ed5 | |||
1a1e3345f4 | |||
527fc2790b | |||
cd7d9fc4f5 | |||
a61685ce01 | |||
b9e63d3f7d | |||
cc3a9dd553 | |||
6a89cc15c3 | |||
fc50392ec7 | |||
59cd89a9c9 | |||
d6ff5f7d96 | |||
8e4dfbd10d | |||
b2d1cea759 | |||
6fe1766c83 | |||
e59c35a308 | |||
b50071ed37 | |||
28c7de6185 | |||
6fb4ebba15 | |||
d00d83abd4 | |||
e6d16e458f | |||
ae42d35184 | |||
ce8929d153 | |||
cc2a775271 | |||
83d719cf79 | |||
4643b5835e | |||
a991bf9045 | |||
3fd3d83029 | |||
24419551a9 | |||
c83eb2e0c9 | |||
929b1675e3 | |||
db54b438e6 | |||
967254d9ca | |||
2d806df9b9 | |||
4fe798ec3b | |||
3555ff5f4e | |||
05ca819823 | |||
c8b8b60b93 | |||
287986d524 | |||
4c25f5e73b | |||
cbc217e80a | |||
fe348e89c5 | |||
e1e1984d3e | |||
99662b616f | |||
857d6e419f | |||
a298b9ea01 | |||
61097d0826 | |||
2ee0f634e6 | |||
61b3b4f775 | |||
dc4b9753d3 | |||
f1ef6c2096 | |||
872c915cf7 | |||
fb9f09c97f | |||
884db8a8b5 | |||
ee21b7bc37 | |||
32c53b9584 | |||
4e5f3fbe84 | |||
2ce193877b | |||
e52d599326 | |||
2cf66f41cb | |||
a06b387acc | |||
03520e0d6f | |||
a6a72a5b54 | |||
85db58aeb5 | |||
596bf32caa | |||
2b2644a76f | |||
02684a868f | |||
1924b308fd | |||
0d62e42c50 | |||
d3193cf8b7 | |||
f7538568c0 | |||
4629ecb8ee | |||
5bcea37d59 | |||
6decaef050 | |||
248578086f | |||
87553c6aa0 | |||
a2aa267e43 | |||
a563e9375e | |||
9a4be1fbec | |||
80f48518ca | |||
16c4b55e31 | |||
023a96a6d3 | |||
39394e49ae | |||
b54ddc3aa9 | |||
97537bd185 | |||
1225173a43 | |||
096bb8d439 | |||
df1f6e2b99 | |||
d1f5bef25d | |||
d426db43ec | |||
3bace07948 | |||
24e31d0a40 | |||
fb623c0929 | |||
4f641ce12d | |||
8cd1e40fb3 | |||
8a7027e8d6 | |||
5bbf73e3b5 | |||
106a58779d | |||
fa5b5ca02d | |||
ba6163574e | |||
37eca8af24 | |||
421c91a58c | |||
c90bf1c6e2 | |||
5b1de296af | |||
f4414566d3 | |||
db4f3eda55 | |||
f3b76df13b | |||
bb79272020 | |||
926ef9e33d | |||
ead21f37d7 | |||
49a2602329 | |||
e88bddc24f | |||
a5821e5785 | |||
4e4d741075 | |||
bec66e9e69 | |||
50832aab47 | |||
643fdd0bce | |||
d1565bb46f | |||
8fa66c13a9 | |||
c0ffa06b95 | |||
3b53f5bca3 | |||
2c80155c6f | |||
8a9b3b3d59 | |||
5dd691aa95 | |||
27ceae580a | |||
b6b6413d04 | |||
2095f4f670 | |||
606e8948c0 | |||
3b6fc1c496 | |||
f96bf65557 | |||
804cff8c55 | |||
633b9c0426 |
26
.github/release.sh
vendored
Normal file
26
.github/release.sh
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
FILENAMES=$(ls)
|
||||
for FILENAME in $FILENAMES
|
||||
do
|
||||
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
||||
gzip -S ".gz" $FILENAME
|
||||
elif [[ $FILENAME =~ ".exe" ]];then
|
||||
zip -m ${FILENAME%.*}.zip $FILENAME
|
||||
else echo "skip $FILENAME"
|
||||
fi
|
||||
done
|
||||
|
||||
FILENAMES=$(ls)
|
||||
for FILENAME in $FILENAMES
|
||||
do
|
||||
if [[ $FILENAME =~ ".zip" ]];then
|
||||
echo "rename $FILENAME"
|
||||
mv $FILENAME ${FILENAME%.*}-${VERSION}.zip
|
||||
elif [[ $FILENAME =~ ".gz" ]];then
|
||||
echo "rename $FILENAME"
|
||||
mv $FILENAME ${FILENAME%.*}-${VERSION}.gz
|
||||
else
|
||||
echo "skip $FILENAME"
|
||||
fi
|
||||
done
|
26
.github/rename-cgo.sh
vendored
Normal file
26
.github/rename-cgo.sh
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
FILENAMES=$(ls)
|
||||
for FILENAME in $FILENAMES
|
||||
do
|
||||
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||
mv $FILENAME clash.meta-darwin-arm64-cgo
|
||||
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||
mv $FILENAME clash.meta-darwin-amd64-cgo
|
||||
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||
echo "rename windows 386 $FILENAME"
|
||||
mv $FILENAME clash.meta-windows-386-cgo.exe
|
||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||
echo "rename windows amd64 $FILENAME"
|
||||
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
||||
elif [[ $FILENAME =~ "linux" ]];then
|
||||
echo "rename linux $FILENAME"
|
||||
mv $FILENAME $FILENAME-cgo
|
||||
elif [[ $FILENAME =~ "android" ]];then
|
||||
echo "rename android $FILENAME"
|
||||
mv $FILENAME $FILENAME-cgo
|
||||
else echo "skip $FILENAME"
|
||||
fi
|
||||
done
|
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
|
325
.github/workflows/build.yml
vendored
Normal file
325
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,325 @@
|
||||
name: Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths-ignore:
|
||||
- "docs/**"
|
||||
- "README.md"
|
||||
branches:
|
||||
- Alpha
|
||||
- Beta
|
||||
- Meta
|
||||
tags:
|
||||
- "v*"
|
||||
pull_request_target:
|
||||
branches:
|
||||
- Alpha
|
||||
- Beta
|
||||
- Meta
|
||||
env:
|
||||
REGISTRY: docker.io
|
||||
jobs:
|
||||
Build:
|
||||
permissions: write-all
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "linux-amd64 linux-amd64-compatible",
|
||||
id: "1",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
||||
id: "2",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
||||
id: "3",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||
id: "4",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||
id: "5",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||
id: "6",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "windows-arm64 windows-arm32v7",
|
||||
id: "7",
|
||||
}
|
||||
- {
|
||||
type: "WithoutCGO",
|
||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||
id: "8",
|
||||
}
|
||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
||||
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
||||
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
||||
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
||||
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
||||
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
||||
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
||||
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
||||
- { type: "WithCGO", target: "android", id: "11" }
|
||||
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set variables
|
||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='Alpha'}}
|
||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='Beta'}}
|
||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='Meta'}}
|
||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set variables
|
||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set ENV
|
||||
run: |
|
||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
||||
echo "BUILDTIME=$(date -u)" >> $GITHUB_ENV
|
||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Set ENV
|
||||
run: |
|
||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
||||
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
||||
shell: bash
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: "1.20"
|
||||
check-latest: true
|
||||
|
||||
- name: Test
|
||||
if: ${{ matrix.job.id=='1' && matrix.job.type=='WithoutCGO' }}
|
||||
run: |
|
||||
go test ./...
|
||||
|
||||
- name: Build WithoutCGO
|
||||
if: ${{ matrix.job.type=='WithoutCGO' }}
|
||||
env:
|
||||
NAME: Clash.Meta
|
||||
BINDIR: bin
|
||||
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
||||
|
||||
- uses: nttld/setup-ndk@v1
|
||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||
id: setup-ndk
|
||||
with:
|
||||
ndk-version: r25b
|
||||
add-to-path: false
|
||||
local-cache: true
|
||||
|
||||
- name: Build Android
|
||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
run: |
|
||||
mkdir bin
|
||||
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
||||
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
||||
|
||||
- name: Set up xgo
|
||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||
run: |
|
||||
docker pull techknowlogick/xgo:latest
|
||||
go install src.techknowlogick.com/xgo@latest
|
||||
|
||||
- name: Build by xgo
|
||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
run: |
|
||||
mkdir bin
|
||||
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
||||
|
||||
- name: Rename
|
||||
if: ${{ matrix.job.type=='WithCGO' }}
|
||||
run: |
|
||||
cd bin
|
||||
ls -la
|
||||
cp ../.github/rename-cgo.sh ./
|
||||
bash ./rename-cgo.sh
|
||||
rm ./rename-cgo.sh
|
||||
ls -la
|
||||
cd ..
|
||||
|
||||
- name: Zip
|
||||
if: ${{ success() }}
|
||||
run: |
|
||||
cd bin
|
||||
ls -la
|
||||
chmod +x *
|
||||
cp ../.github/release.sh ./
|
||||
bash ./release.sh
|
||||
rm ./release.sh
|
||||
ls -la
|
||||
cd ..
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
name: artifact
|
||||
path: bin/
|
||||
|
||||
Upload-Prerelease:
|
||||
permissions: write-all
|
||||
if: ${{ github.ref_type=='branch' }}
|
||||
needs: [ Build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifact
|
||||
path: bin/
|
||||
|
||||
- name: Display structure of downloaded files
|
||||
run: ls -R
|
||||
working-directory: bin
|
||||
|
||||
- name: Delete current release assets
|
||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: Prerelease-${{ github.ref_name }}
|
||||
deleteOnlyFromDrafts: false
|
||||
|
||||
- name: Tag Repo
|
||||
uses: richardsimko/update-tag@v1.0.6
|
||||
with:
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload Prerelease
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
files: bin/*
|
||||
prerelease: true
|
||||
generate_release_notes: true
|
||||
|
||||
Upload-Release:
|
||||
permissions: write-all
|
||||
if: ${{ github.ref_type=='tag' }}
|
||||
needs: [ Build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifact
|
||||
path: bin/
|
||||
|
||||
- name: Display structure of downloaded files
|
||||
run: ls -R
|
||||
working-directory: bin
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: bin/*
|
||||
generate_release_notes: true
|
||||
|
||||
Docker:
|
||||
permissions: write-all
|
||||
needs: [ Build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: artifact
|
||||
path: bin/
|
||||
|
||||
- name: Display structure of downloaded files
|
||||
run: ls -R
|
||||
working-directory: bin
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
version: latest
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||
- name: Show files
|
||||
run: |
|
||||
ls .
|
||||
ls bin/
|
||||
- name: Log into registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
|
||||
# Build and push Docker image with Buildx (don't push on PR)
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
platforms: |
|
||||
linux/386
|
||||
linux/amd64
|
||||
linux/arm64/v8
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
61
.github/workflows/docker.yaml
vendored
61
.github/workflows/docker.yaml
vendored
@ -1,61 +0,0 @@
|
||||
name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Beta
|
||||
tags:
|
||||
- "v*"
|
||||
env:
|
||||
REGISTRY: docker.io
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Setup Docker buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
version: latest
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v3
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||
|
||||
- name: Log into registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||
|
||||
# Build and push Docker image with Buildx (don't push on PR)
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
platforms: |
|
||||
linux/386
|
||||
linux/amd64
|
||||
linux/arm64/v8
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
60
.github/workflows/prerelease.yml
vendored
60
.github/workflows/prerelease.yml
vendored
@ -1,60 +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: andreaswilli/delete-release-assets-action@v2.0.0
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: Prerelease-${{ github.ref_name }}
|
||||
deleteOnlyFromDrafts: false
|
||||
|
||||
- name: Tag Repo
|
||||
uses: richardsimko/update-tag@v1
|
||||
with:
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload Alpha
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
tag_name: Prerelease-${{ github.ref_name }}
|
||||
files: bin/*
|
||||
prerelease: true
|
||||
generate_release_notes: true
|
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/config/cache*
|
||||
/output
|
||||
/.vscode
|
||||
.vscode/
|
||||
.fleet/
|
19
Dockerfile
19
Dockerfile
@ -1,18 +1,17 @@
|
||||
FROM golang:alpine as builder
|
||||
FROM alpine:latest as builder
|
||||
|
||||
RUN apk add --no-cache make git && \
|
||||
RUN apk add --no-cache gzip && \
|
||||
mkdir /clash-config && \
|
||||
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/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
|
||||
|
||||
COPY . /clash-src
|
||||
WORKDIR /clash-src
|
||||
RUN go mod download &&\
|
||||
make docker &&\
|
||||
mv ./bin/Clash.Meta-docker /clash
|
||||
|
||||
COPY docker/file-name.sh /clash/file-name.sh
|
||||
WORKDIR /clash
|
||||
COPY bin/ bin/
|
||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && \
|
||||
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
||||
FROM alpine:latest
|
||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||
|
||||
@ -21,6 +20,6 @@ RUN apk add --no-cache ca-certificates tzdata iptables
|
||||
VOLUME ["/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
|
||||
ENTRYPOINT [ "/clash" ]
|
||||
|
13
Makefile
13
Makefile
@ -47,14 +47,17 @@ all:linux-amd64 linux-arm64\
|
||||
darwin-amd64 darwin-arm64\
|
||||
windows-amd64 windows-arm64\
|
||||
|
||||
|
||||
darwin-all: darwin-amd64 darwin-arm64
|
||||
|
||||
docker:
|
||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
darwin-amd64:
|
||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
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:
|
||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
@ -66,7 +69,7 @@ linux-amd64:
|
||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
|
||||
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:
|
||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||
@ -117,7 +120,7 @@ windows-amd64:
|
||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
|
||||
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:
|
||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||
@ -154,4 +157,4 @@ CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
||||
ebpf: export BPF_CLANG := $(CLANG)
|
||||
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||
ebpf:
|
||||
cd component/ebpf/ && go generate ./...
|
||||
cd component/ebpf/ && go generate ./...
|
||||
|
104
README.md
104
README.md
@ -29,32 +29,42 @@
|
||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||
- Comprehensive HTTP RESTful API controller
|
||||
|
||||
## Getting Started
|
||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||
## Wiki
|
||||
|
||||
## Advanced usage for this branch
|
||||
Documentation and configuring examples are available on [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki) and [Clash.Meta Wiki](https://docs.metacubex.one/).
|
||||
|
||||
## Build
|
||||
|
||||
You should install [golang](https://go.dev) first.
|
||||
|
||||
Then get the source code of Clash.Meta:
|
||||
|
||||
```shell
|
||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||
cd Clash.Meta && go mod download
|
||||
```
|
||||
|
||||
If you can't visit github,you should set proxy first:
|
||||
|
||||
```shell
|
||||
go env -w GOPROXY=https://goproxy.io,direct
|
||||
```
|
||||
|
||||
So now you can build it:
|
||||
Now you can build it:
|
||||
|
||||
```shell
|
||||
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`.
|
||||
|
||||
@ -64,7 +74,6 @@ Support resolve ip with a `Proxy Tunnel`.
|
||||
|
||||
```yaml
|
||||
proxy-groups:
|
||||
|
||||
- name: DNS
|
||||
type: url-test
|
||||
use:
|
||||
@ -73,6 +82,7 @@ proxy-groups:
|
||||
interval: 180
|
||||
lazy: true
|
||||
```
|
||||
|
||||
```yaml
|
||||
dns:
|
||||
enable: true
|
||||
@ -88,12 +98,12 @@ dns:
|
||||
- https://doh.pub/dns-query
|
||||
- tls://223.5.5.5:853
|
||||
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.
|
||||
- 'tls://8.8.4.4:853#DNS'
|
||||
- "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"
|
||||
fallback-filter:
|
||||
geoip: false
|
||||
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:
|
||||
- +.example.com
|
||||
ipcidr:
|
||||
@ -110,28 +120,30 @@ Built-in [Wintun](https://www.wintun.net) driver.
|
||||
# Enable the TUN listener
|
||||
tun:
|
||||
enable: true
|
||||
stack: gvisor # only gvisor
|
||||
dns-hijack:
|
||||
stack: system # system/gvisor
|
||||
dns-hijack:
|
||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||
auto-route: true # auto set global route
|
||||
```
|
||||
|
||||
### Rules configuration
|
||||
|
||||
- Support rule `GEOSITE`.
|
||||
- Support rule-providers `RULE-SET`.
|
||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||
- Support `network` condition for all rules.
|
||||
- Support source IPCIDR condition for all rules, just append to the end.
|
||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
|
||||
# network(tcp/udp) condition for all rules
|
||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||
|
||||
|
||||
# multiport condition for rules SRC-PORT and DST-PORT
|
||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||
|
||||
|
||||
# rule GEOSITE
|
||||
- GEOSITE,category-ads-all,REJECT
|
||||
- GEOSITE,icloud@cn,DIRECT
|
||||
@ -142,18 +154,17 @@ rules:
|
||||
- GEOSITE,youtube,PROXY
|
||||
- GEOSITE,geolocation-cn,DIRECT
|
||||
- GEOSITE,geolocation-!cn,PROXY
|
||||
|
||||
|
||||
# source IPCIDR condition for all rules in gateway proxy
|
||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||
|
||||
- GEOIP,telegram,PROXY,no-resolve
|
||||
- GEOIP,private,DIRECT,no-resolve
|
||||
- GEOIP,cn,DIRECT
|
||||
|
||||
|
||||
- MATCH,PROXY
|
||||
```
|
||||
|
||||
|
||||
### 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)
|
||||
@ -162,18 +173,17 @@ Support `Policy Group Filter`
|
||||
|
||||
```yaml
|
||||
proxy-groups:
|
||||
|
||||
- name: 🚀 HK Group
|
||||
type: select
|
||||
use:
|
||||
- ALL
|
||||
filter: 'HK'
|
||||
filter: "HK"
|
||||
|
||||
- name: 🚀 US Group
|
||||
type: select
|
||||
use:
|
||||
- ALL
|
||||
filter: 'US'
|
||||
filter: "US"
|
||||
|
||||
proxy-providers:
|
||||
ALL:
|
||||
@ -185,14 +195,12 @@ proxy-providers:
|
||||
enable: true
|
||||
interval: 600
|
||||
url: http://www.gstatic.com/generate_204
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
Support outbound transport protocol `VLESS`.
|
||||
|
||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||
|
||||
```yaml
|
||||
proxies:
|
||||
- name: "vless"
|
||||
@ -203,7 +211,7 @@ proxies:
|
||||
servername: example.com # AKA SNI
|
||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||
# skip-cert-verify: true
|
||||
|
||||
|
||||
- name: "vless-ws"
|
||||
type: vless
|
||||
server: server
|
||||
@ -228,12 +236,12 @@ proxies:
|
||||
network: grpc
|
||||
servername: example.com # priority over wss host
|
||||
# skip-cert-verify: true
|
||||
grpc-opts:
|
||||
grpc-opts:
|
||||
grpc-service-name: grpcname
|
||||
```
|
||||
|
||||
|
||||
Support outbound transport protocol `Wireguard`
|
||||
|
||||
```yaml
|
||||
proxies:
|
||||
- name: "wg"
|
||||
@ -248,6 +256,7 @@ proxies:
|
||||
```
|
||||
|
||||
Support outbound transport protocol `Tuic`
|
||||
|
||||
```yaml
|
||||
proxies:
|
||||
- name: "tuic"
|
||||
@ -266,11 +275,11 @@ proxies:
|
||||
# max-udp-relay-packet-size: 1500
|
||||
# fast-open: true
|
||||
# skip-cert-verify: true
|
||||
|
||||
```
|
||||
``` -->
|
||||
|
||||
### IPTABLES configuration
|
||||
Work on Linux OS who's supported `iptables`
|
||||
|
||||
Work on Linux OS which supported `iptables`
|
||||
|
||||
```yaml
|
||||
# Enable the TPROXY listener
|
||||
@ -281,17 +290,15 @@ iptables:
|
||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||
```
|
||||
|
||||
### General installation guide for Linux
|
||||
|
||||
### General installation guide for Linux
|
||||
+ Create user given name `clash-meta`
|
||||
- Create user given name `clash-meta`
|
||||
|
||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||
|
||||
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||
|
||||
+ Create folder `/etc/Clash-Meta/` as working directory
|
||||
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||
|
||||
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||
|
||||
- Create folder `/etc/Clash-Meta/` as working directory
|
||||
|
||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||
|
||||
@ -317,10 +324,13 @@ ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Launch clashd on system startup with:
|
||||
|
||||
```shell
|
||||
$ systemctl enable Clash-Meta
|
||||
```
|
||||
|
||||
Launch clashd immediately with:
|
||||
|
||||
```shell
|
||||
@ -331,23 +341,29 @@ $ systemctl start Clash-Meta
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
## Debugging
|
||||
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
||||
|
||||
|
||||
## Credits
|
||||
|
||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||
* [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||
|
||||
## License
|
||||
|
||||
|
@ -92,6 +92,7 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||
mapping["history"] = p.DelayHistory()
|
||||
mapping["name"] = p.Name()
|
||||
mapping["udp"] = p.SupportUDP()
|
||||
mapping["xudp"] = p.SupportXUDP()
|
||||
mapping["tfo"] = p.SupportTFO()
|
||||
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 {
|
||||
addition.Apply(metadata)
|
||||
}
|
||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||
if ip, port, err := parseAddr(source); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
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.InPort = port
|
||||
}
|
||||
|
@ -15,11 +15,11 @@ func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *cont
|
||||
for _, addition := range additions {
|
||||
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.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.InPort = port
|
||||
}
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/database64128/tfo-go/v2"
|
||||
"github.com/sagernet/tfo-go"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -24,12 +24,12 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions
|
||||
for _, addition := range additions {
|
||||
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.SrcPort = port
|
||||
}
|
||||
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.InPort = port
|
||||
}
|
||||
|
@ -18,22 +18,13 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
||||
addition.Apply(metadata)
|
||||
}
|
||||
|
||||
remoteAddr := conn.RemoteAddr()
|
||||
|
||||
// Filter when net.Addr interface is nil
|
||||
if remoteAddr != nil {
|
||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
||||
metadata.SrcIP = ip
|
||||
metadata.SrcPort = port
|
||||
}
|
||||
localAddr := conn.LocalAddr()
|
||||
// Filter when net.Addr interface is nil
|
||||
if localAddr != nil {
|
||||
if ip, port, err := parseAddr(localAddr.String()); err == nil {
|
||||
metadata.InIP = ip
|
||||
metadata.InPort = port
|
||||
}
|
||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
||||
metadata.InIP = ip
|
||||
metadata.InPort = port
|
||||
}
|
||||
|
||||
return context.NewConnContext(conn, metadata)
|
||||
@ -43,7 +34,7 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
||||
metadata := &C.Metadata{}
|
||||
metadata.NetWork = C.TCP
|
||||
metadata.Type = C.INNER
|
||||
metadata.DNSMode = C.DNSMapping
|
||||
metadata.DNSMode = C.DNSNormal
|
||||
metadata.Host = host
|
||||
metadata.Process = C.ClashName
|
||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||
|
@ -1,13 +1,14 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/common/nnip"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
)
|
||||
@ -57,8 +58,19 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
||||
return metadata
|
||||
}
|
||||
|
||||
func parseAddr(addr string) (netip.Addr, string, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||
// 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 {
|
||||
return netip.Addr{}, "", err
|
||||
}
|
||||
|
@ -4,12 +4,14 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gofrs/uuid"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
|
||||
"github.com/gofrs/uuid"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
@ -18,6 +20,7 @@ type Base struct {
|
||||
iface string
|
||||
tp C.AdapterType
|
||||
udp bool
|
||||
xudp bool
|
||||
tfo bool
|
||||
rmark int
|
||||
id string
|
||||
@ -87,6 +90,11 @@ func (b *Base) SupportUDP() bool {
|
||||
return b.udp
|
||||
}
|
||||
|
||||
// SupportXUDP implements C.ProxyAdapter
|
||||
func (b *Base) SupportXUDP() bool {
|
||||
return b.xudp
|
||||
}
|
||||
|
||||
// SupportTFO implements C.ProxyAdapter
|
||||
func (b *Base) SupportTFO() bool {
|
||||
return b.tfo
|
||||
@ -132,10 +140,15 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
||||
default:
|
||||
}
|
||||
|
||||
if b.tfo {
|
||||
opts = append(opts, dialer.WithTFO(true))
|
||||
}
|
||||
|
||||
return opts
|
||||
}
|
||||
|
||||
type BasicOption struct {
|
||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||
@ -146,6 +159,7 @@ type BaseOption struct {
|
||||
Addr string
|
||||
Type C.AdapterType
|
||||
UDP bool
|
||||
XUDP bool
|
||||
TFO bool
|
||||
Interface string
|
||||
RoutingMark int
|
||||
@ -158,6 +172,7 @@ func NewBase(opt BaseOption) *Base {
|
||||
addr: opt.Addr,
|
||||
tp: opt.Type,
|
||||
udp: opt.UDP,
|
||||
xudp: opt.XUDP,
|
||||
tfo: opt.TFO,
|
||||
iface: opt.Interface,
|
||||
rmark: opt.RoutingMark,
|
||||
@ -166,7 +181,7 @@ func NewBase(opt BaseOption) *Base {
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
net.Conn
|
||||
N.ExtendedConn
|
||||
chain C.Chain
|
||||
actualRemoteDestination string
|
||||
}
|
||||
@ -185,8 +200,12 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||
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 {
|
||||
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||
}
|
||||
|
||||
type packetConn struct {
|
||||
|
@ -7,7 +7,6 @@ import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@ -15,6 +14,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
@ -150,7 +150,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
||||
sni = option.SNI
|
||||
}
|
||||
if len(option.Fingerprint) == 0 {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
ServerName: sni,
|
||||
})
|
||||
@ -170,6 +170,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
||||
name: option.Name,
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Http,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -178,7 +178,7 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
}
|
||||
|
||||
if len(option.ALPN) > 0 {
|
||||
|
@ -53,6 +53,9 @@ func (rw *nopConn) Read(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (rw *nopConn) Write(b []byte) (int, error) {
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,6 @@ package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@ -10,10 +9,9 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/shadowtls"
|
||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||
|
||||
@ -33,8 +31,7 @@ type ShadowSocks struct {
|
||||
obfsMode string
|
||||
obfsOption *simpleObfsOption
|
||||
v2rayOption *v2rayObfs.Option
|
||||
shadowTLSOption *shadowTLSOption
|
||||
tlsConfig *tls.Config
|
||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||
}
|
||||
|
||||
type ShadowSocksOption struct {
|
||||
@ -67,14 +64,31 @@ type v2rayObfsOption struct {
|
||||
}
|
||||
|
||||
type shadowTLSOption struct {
|
||||
Password string `obfs:"password"`
|
||||
Host string `obfs:"host"`
|
||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||
Password string `obfs:"password"`
|
||||
Host string `obfs:"host"`
|
||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||
ClientFingerprint string `obfs:"client-fingerprint,omitempty"`
|
||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||
Version int `obfs:"version,omitempty"`
|
||||
}
|
||||
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
switch ss.obfsMode {
|
||||
case shadowtls.Mode:
|
||||
// fix tls handshake not timeout
|
||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||
defer cancel()
|
||||
var err error
|
||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ss.streamConn(c, metadata)
|
||||
}
|
||||
|
||||
func (ss *ShadowSocks) streamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
switch ss.obfsMode {
|
||||
case "tls":
|
||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||
@ -87,13 +101,11 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||
}
|
||||
case shadowtls.Mode:
|
||||
c = shadowtls.NewShadowTLS(c, ss.shadowTLSOption.Password, ss.tlsConfig)
|
||||
}
|
||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443")), nil
|
||||
}
|
||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -113,7 +125,15 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
||||
safeConnClose(c, err)
|
||||
}(c)
|
||||
|
||||
c, err = ss.StreamConn(c, metadata)
|
||||
switch ss.obfsMode {
|
||||
case shadowtls.Mode:
|
||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c, err = ss.streamConn(c, metadata)
|
||||
return NewConn(c, ss), err
|
||||
}
|
||||
|
||||
@ -171,8 +191,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
|
||||
var v2rayOption *v2rayObfs.Option
|
||||
var obfsOption *simpleObfsOption
|
||||
var shadowTLSOpt *shadowTLSOption
|
||||
var tlsConfig *tls.Config
|
||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||
obfsMode := ""
|
||||
|
||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||
@ -210,24 +229,20 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
}
|
||||
} else if option.Plugin == shadowtls.Mode {
|
||||
obfsMode = shadowtls.Mode
|
||||
shadowTLSOpt = &shadowTLSOption{}
|
||||
if err := decoder.Decode(option.PluginOpts, shadowTLSOpt); err != nil {
|
||||
opt := &shadowTLSOption{
|
||||
Version: 2,
|
||||
}
|
||||
if err := decoder.Decode(option.PluginOpts, opt); err != nil {
|
||||
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
||||
}
|
||||
|
||||
tlsConfig = &tls.Config{
|
||||
NextProtos: shadowtls.DefaultALPN,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: shadowTLSOpt.SkipCertVerify,
|
||||
ServerName: shadowTLSOpt.Host,
|
||||
}
|
||||
|
||||
if len(shadowTLSOpt.Fingerprint) == 0 {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
} else {
|
||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, shadowTLSOpt.Fingerprint); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
||||
Password: opt.Password,
|
||||
Host: opt.Host,
|
||||
Fingerprint: opt.Fingerprint,
|
||||
ClientFingerprint: opt.ClientFingerprint,
|
||||
SkipCertVerify: opt.SkipCertVerify,
|
||||
Version: opt.Version,
|
||||
}
|
||||
}
|
||||
|
||||
@ -237,6 +252,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
addr: addr,
|
||||
tp: C.Shadowsocks,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -248,7 +264,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||
v2rayOption: v2rayOption,
|
||||
obfsOption: obfsOption,
|
||||
shadowTLSOption: shadowTLSOpt,
|
||||
tlsConfig: tlsConfig,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
@ -163,6 +163,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||
addr: addr,
|
||||
tp: C.ShadowsocksR,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -167,6 +167,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
||||
addr: addr,
|
||||
tp: C.Snell,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -5,12 +5,12 @@ import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
)
|
||||
@ -167,7 +167,7 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||
}
|
||||
|
||||
if len(option.Fingerprint) == 0 {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
} else {
|
||||
var err error
|
||||
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)),
|
||||
tp: C.Socks5,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
|
@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -29,20 +30,21 @@ type Trojan struct {
|
||||
|
||||
type TrojanOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Password string `proxy:"password"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
Password string `proxy:"password"`
|
||||
ALPN []string `proxy:"alpn,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,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) {
|
||||
@ -75,6 +77,11 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
||||
t.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||
}
|
||||
|
||||
if t.transport != nil {
|
||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||
} else {
|
||||
@ -95,7 +102,7 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
||||
return c, err
|
||||
}
|
||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||
return c, err
|
||||
return N.NewExtendedConn(c), err
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -211,12 +218,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
|
||||
tOption := &trojan.Option{
|
||||
Password: option.Password,
|
||||
ALPN: option.ALPN,
|
||||
ServerName: option.Server,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FlowShow: option.FlowShow,
|
||||
Fingerprint: option.Fingerprint,
|
||||
Password: option.Password,
|
||||
ALPN: option.ALPN,
|
||||
ServerName: option.Server,
|
||||
SkipCertVerify: option.SkipCertVerify,
|
||||
FlowShow: option.FlowShow,
|
||||
Fingerprint: option.Fingerprint,
|
||||
ClientFingerprint: option.ClientFingerprint,
|
||||
}
|
||||
|
||||
switch option.Network {
|
||||
@ -242,6 +250,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
addr: addr,
|
||||
tp: C.Trojan,
|
||||
udp: option.UDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -268,7 +277,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
}
|
||||
|
||||
if len(option.Fingerprint) == 0 {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
} else {
|
||||
var err error
|
||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||
@ -276,7 +285,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||
}
|
||||
}
|
||||
|
||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint)
|
||||
|
||||
t.gunTLSConfig = tlsConfig
|
||||
t.gunConfig = &gun.Config{
|
||||
|
@ -51,6 +51,7 @@ type TuicOption struct {
|
||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||
SNI string `proxy:"sni,omitempty"`
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -106,12 +107,14 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.Pack
|
||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||
serverName := option.Server
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
ServerName: serverName,
|
||||
InsecureSkipVerify: option.SkipCertVerify,
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
if option.SNI != "" {
|
||||
tlsConfig.ServerName = option.SNI
|
||||
}
|
||||
|
||||
var bs []byte
|
||||
var err error
|
||||
@ -143,7 +146,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
}
|
||||
|
||||
if len(option.ALPN) > 0 {
|
||||
@ -165,7 +168,7 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
}
|
||||
|
||||
if option.MaxUdpRelayPacketSize == 0 {
|
||||
option.MaxUdpRelayPacketSize = 1500
|
||||
option.MaxUdpRelayPacketSize = 1252
|
||||
}
|
||||
|
||||
if option.MaxOpenStreams == 0 {
|
||||
@ -213,12 +216,18 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
||||
udp: true,
|
||||
tfo: option.FastOpen,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
},
|
||||
}
|
||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
||||
|
||||
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 {
|
||||
clientMaxOpenStreams = 1
|
||||
}
|
||||
|
@ -12,10 +12,6 @@ import (
|
||||
"strconv"
|
||||
"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/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
@ -25,6 +21,10 @@ import (
|
||||
"github.com/Dreamacro/clash/transport/socks5"
|
||||
"github.com/Dreamacro/clash/transport/vless"
|
||||
"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 (
|
||||
@ -45,31 +45,37 @@ type Vless struct {
|
||||
|
||||
type VlessOption struct {
|
||||
BasicOption
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
UUID string `proxy:"uuid"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||
XUDP bool `proxy:"xudp,omitempty"`
|
||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
WSPath string `proxy:"ws-path,omitempty"`
|
||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
ServerName string `proxy:"servername,omitempty"`
|
||||
Name string `proxy:"name"`
|
||||
Server string `proxy:"server"`
|
||||
Port int `proxy:"port"`
|
||||
UUID string `proxy:"uuid"`
|
||||
Flow string `proxy:"flow,omitempty"`
|
||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||
TLS bool `proxy:"tls,omitempty"`
|
||||
UDP bool `proxy:"udp,omitempty"`
|
||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||
XUDP bool `proxy:"xudp,omitempty"`
|
||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||
Network string `proxy:"network,omitempty"`
|
||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||
WSPath string `proxy:"ws-path,omitempty"`
|
||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||
ServerName string `proxy:"servername,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||
}
|
||||
|
||||
switch v.option.Network {
|
||||
case "ws":
|
||||
|
||||
@ -80,6 +86,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
Path: v.option.WSOpts.Path,
|
||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
Headers: http.Header{},
|
||||
}
|
||||
|
||||
@ -98,9 +105,12 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
}
|
||||
|
||||
if len(v.option.Fingerprint) == 0 {
|
||||
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
} else {
|
||||
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
@ -161,7 +171,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) {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
|
||||
if v.isXTLSEnabled() && !isH2 {
|
||||
if v.isLegacyXTLSEnabled() && !isH2 {
|
||||
xtlsOpts := vless.XTLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
@ -176,9 +186,10 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
|
||||
} else if v.option.TLS {
|
||||
tlsOpts := vmess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
FingerPrint: v.option.Fingerprint,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
|
||||
if isH2 {
|
||||
@ -195,8 +206,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (v *Vless) isXTLSEnabled() bool {
|
||||
return v.client.Addons != nil
|
||||
func (v *Vless) isLegacyXTLSEnabled() bool {
|
||||
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
||||
}
|
||||
|
||||
// DialContext implements C.ProxyAdapter
|
||||
@ -233,12 +244,15 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
||||
}(c)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// ListenPacketContext implements C.ProxyAdapter
|
||||
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() {
|
||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||
if err != nil {
|
||||
@ -279,7 +293,7 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
|
||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||
if !metadata.Resolved() {
|
||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||
if err != nil {
|
||||
@ -465,7 +479,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||
option.Flow = option.Flow[:16]
|
||||
switch option.Flow {
|
||||
case vless.XRO, vless.XRD, vless.XRS:
|
||||
case vless.XRO, vless.XRD, vless.XRS, vless.XRV:
|
||||
addons = &vless.Addons{
|
||||
Flow: option.Flow,
|
||||
}
|
||||
@ -474,6 +488,16 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
}
|
||||
|
||||
switch option.PacketEncoding {
|
||||
case "packetaddr", "packet":
|
||||
option.PacketAddr = true
|
||||
option.XUDP = false
|
||||
default: // https://github.com/XTLS/Xray-core/pull/1567#issuecomment-1407305458
|
||||
if !option.PacketAddr {
|
||||
option.XUDP = true
|
||||
}
|
||||
}
|
||||
|
||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -485,6 +509,8 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vless,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -493,16 +519,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
option: &option,
|
||||
}
|
||||
|
||||
switch option.PacketEncoding {
|
||||
case "packetaddr", "packet":
|
||||
option.PacketAddr = true
|
||||
case "xudp":
|
||||
option.XUDP = true
|
||||
}
|
||||
if option.XUDP {
|
||||
option.PacketAddr = false
|
||||
}
|
||||
|
||||
switch option.Network {
|
||||
case "h2":
|
||||
if len(option.HTTP2Opts.Host) == 0 {
|
||||
@ -519,10 +535,11 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
}
|
||||
|
||||
gunConfig := &gun.Config{
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
Host: v.option.ServerName,
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
ServerName: v.option.ServerName,
|
||||
})
|
||||
@ -535,7 +552,9 @@ func NewVless(option VlessOption) (*Vless, error) {
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
v.gunConfig = gunConfig
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint)
|
||||
|
||||
}
|
||||
|
||||
return v, nil
|
||||
|
@ -5,8 +5,6 @@ import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
vmess "github.com/sagernet/sing-vmess"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@ -15,10 +13,12 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/transport/gun"
|
||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||
|
||||
vmess "github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing-vmess/packetaddr"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
@ -59,6 +59,7 @@ type VmessOption struct {
|
||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
type HTTPOptions struct {
|
||||
@ -86,6 +87,11 @@ type WSOptions struct {
|
||||
// StreamConn implements C.ProxyAdapter
|
||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
var err error
|
||||
|
||||
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
||||
}
|
||||
|
||||
switch v.option.Network {
|
||||
case "ws":
|
||||
|
||||
@ -96,6 +102,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
Path: v.option.WSOpts.Path,
|
||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
Headers: http.Header{},
|
||||
}
|
||||
|
||||
@ -114,7 +121,7 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
}
|
||||
|
||||
if len(v.option.Fingerprint) == 0 {
|
||||
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||
} else {
|
||||
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||
return nil, err
|
||||
@ -133,8 +140,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &clashVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
@ -159,9 +167,10 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
case "h2":
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := clashVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
NextProtos: []string{"h2"},
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
NextProtos: []string{"h2"},
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
@ -186,8 +195,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
if v.option.TLS {
|
||||
host, _, _ := net.SplitHostPort(v.addr)
|
||||
tlsOpts := &clashVMess.TLSConfig{
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
Host: host,
|
||||
SkipCertVerify: v.option.SkipCertVerify,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
|
||||
if v.option.ServerName != "" {
|
||||
@ -203,12 +213,12 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||
}
|
||||
if metadata.NetWork == C.UDP {
|
||||
if v.option.XUDP {
|
||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||
} else {
|
||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||
}
|
||||
} else {
|
||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
return v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||
}
|
||||
}
|
||||
|
||||
@ -251,7 +261,7 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
||||
|
||||
// ListenPacketContext implements C.ProxyAdapter
|
||||
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() {
|
||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||
if err != nil {
|
||||
@ -279,9 +289,9 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
}(c)
|
||||
|
||||
if v.option.XUDP {
|
||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
c = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
} else {
|
||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
c = v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@ -294,7 +304,7 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
||||
|
||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||
if !metadata.Resolved() {
|
||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||
if err != nil {
|
||||
@ -366,7 +376,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
switch option.Network {
|
||||
case "h2", "grpc":
|
||||
if !option.TLS {
|
||||
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||
option.TLS = true
|
||||
}
|
||||
}
|
||||
|
||||
@ -376,6 +386,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||
tp: C.Vmess,
|
||||
udp: option.UDP,
|
||||
xudp: option.XUDP,
|
||||
tfo: option.TFO,
|
||||
iface: option.Interface,
|
||||
rmark: option.RoutingMark,
|
||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||
@ -400,8 +412,9 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
}
|
||||
|
||||
gunConfig := &gun.Config{
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
Host: v.option.ServerName,
|
||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||
Host: v.option.ServerName,
|
||||
ClientFingerprint: v.option.ClientFingerprint,
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||
@ -416,7 +429,9 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
||||
|
||||
v.gunTLSConfig = tlsConfig
|
||||
v.gunConfig = gunConfig
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||
|
||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint)
|
||||
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ import (
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/listener/sing"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
wireguard "github.com/metacubex/sing-wireguard"
|
||||
|
||||
@ -174,14 +174,14 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||
}
|
||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||
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{}) {
|
||||
sing.Logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||
log.SingLogger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||
},
|
||||
}, option.Workers)
|
||||
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)
|
||||
if err != nil {
|
||||
|
@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/callback"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/provider"
|
||||
@ -30,11 +31,21 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||
if err == nil {
|
||||
c.AppendToChains(f)
|
||||
f.onDialSuccess()
|
||||
} else {
|
||||
f.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
|
||||
c = &callback.FirstWriteCallBackConn{
|
||||
Conn: c,
|
||||
Callback: func(err error) {
|
||||
if err == nil {
|
||||
f.onDialSuccess()
|
||||
} else {
|
||||
f.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
return c, err
|
||||
}
|
||||
|
||||
|
@ -165,6 +165,7 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||
for i := range gb.excludeTypeArray {
|
||||
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
||||
flag = true
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/common/callback"
|
||||
"github.com/Dreamacro/clash/common/murmur3"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -83,17 +84,24 @@ func jumpHash(key uint64, buckets int32) int32 {
|
||||
// DialContext implements C.ProxyAdapter
|
||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||
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...)...)
|
||||
|
||||
if err == nil {
|
||||
c.AppendToChains(lb)
|
||||
} else {
|
||||
lb.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
|
||||
c = &callback.FirstWriteCallBackConn{
|
||||
Conn: c,
|
||||
Callback: func(err error) {
|
||||
if err == nil {
|
||||
lb.onDialSuccess()
|
||||
} else {
|
||||
lb.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
},
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@ -115,11 +123,20 @@ func (lb *LoadBalance) SupportUDP() bool {
|
||||
}
|
||||
|
||||
func strategyRoundRobin() strategyFn {
|
||||
flag := true
|
||||
idx := 0
|
||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||
length := len(proxies)
|
||||
for i := 0; i < length; i++ {
|
||||
idx = (idx + 1) % length
|
||||
flag = !flag
|
||||
if flag {
|
||||
idx = (idx - 1) % length
|
||||
} else {
|
||||
idx = (idx + 2) % length
|
||||
}
|
||||
if idx < 0 {
|
||||
idx = idx + length
|
||||
}
|
||||
proxy := proxies[idx]
|
||||
if proxy.Alive() {
|
||||
return proxy
|
||||
|
@ -78,7 +78,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
||||
providersMap[groupName] = pd
|
||||
} else {
|
||||
if groupOption.URL == "" {
|
||||
groupOption.URL = "http://www.gstatic.com/generate_204"
|
||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
||||
}
|
||||
|
||||
if groupOption.Interval == 0 {
|
||||
|
@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/callback"
|
||||
"github.com/Dreamacro/clash/common/singledo"
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -38,10 +39,20 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||
if err == nil {
|
||||
c.AppendToChains(u)
|
||||
u.onDialSuccess()
|
||||
} else {
|
||||
u.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
|
||||
c = &callback.FirstWriteCallBackConn{
|
||||
Conn: c,
|
||||
Callback: func(err error) {
|
||||
if err == nil {
|
||||
u.onDialSuccess()
|
||||
} else {
|
||||
u.onDialFailed(proxy.Type(), err)
|
||||
}
|
||||
},
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
|
@ -2,6 +2,9 @@ package adapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
|
||||
"github.com/Dreamacro/clash/adapter/outbound"
|
||||
"github.com/Dreamacro/clash/common/structure"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -54,6 +57,11 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||
Path: []string{"/"},
|
||||
},
|
||||
}
|
||||
|
||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||
vmessOption.ClientFingerprint = GlobalUtlsClient
|
||||
}
|
||||
|
||||
err = decoder.Decode(mapping, vmessOption)
|
||||
if err != nil {
|
||||
break
|
||||
@ -61,6 +69,11 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||
proxy, err = outbound.NewVmess(*vmessOption)
|
||||
case "vless":
|
||||
vlessOption := &outbound.VlessOption{}
|
||||
|
||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||
vlessOption.ClientFingerprint = GlobalUtlsClient
|
||||
}
|
||||
|
||||
err = decoder.Decode(mapping, vlessOption)
|
||||
if err != nil {
|
||||
break
|
||||
@ -75,6 +88,11 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||
proxy, err = outbound.NewSnell(*snellOption)
|
||||
case "trojan":
|
||||
trojanOption := &outbound.TrojanOption{}
|
||||
|
||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||
trojanOption.ClientFingerprint = GlobalUtlsClient
|
||||
}
|
||||
|
||||
err = decoder.Decode(mapping, trojanOption)
|
||||
if err != nil {
|
||||
break
|
||||
|
@ -301,6 +301,7 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
||||
for i := range excludeTypeArray {
|
||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
||||
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 (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -111,6 +113,12 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
trojan["grpc-opts"] = grpcOpts
|
||||
}
|
||||
|
||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||
trojan["client-fingerprint"] = "chrome"
|
||||
} else {
|
||||
trojan["client-fingerprint"] = fingerprint
|
||||
}
|
||||
|
||||
proxies = append(proxies, trojan)
|
||||
|
||||
case "vless":
|
||||
@ -120,7 +128,11 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
}
|
||||
query := urlVLess.Query()
|
||||
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 != "" {
|
||||
vless["flow"] = strings.ToLower(flow)
|
||||
}
|
||||
@ -138,7 +150,11 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
}
|
||||
query := urlVMess.Query()
|
||||
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["cipher"] = "auto"
|
||||
if encryption := query.Get("encryption"); encryption != "" {
|
||||
@ -272,16 +288,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||
cipher string
|
||||
password string
|
||||
)
|
||||
|
||||
cipher = cipherRaw
|
||||
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), ":")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
err := VerifyMethod(cipher, password)
|
||||
err = VerifyMethod(cipher, password)
|
||||
if err != nil {
|
||||
dcBuf, _ := encRaw.DecodeString(cipherRaw)
|
||||
dcBuf, _ = encRaw.DecodeString(cipherRaw)
|
||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,24 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"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
|
||||
// https://github.com/XTLS/Xray-core/discussions/716
|
||||
query := url.Query()
|
||||
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["server"] = url.Hostname()
|
||||
proxy["port"] = url.Port()
|
||||
@ -20,6 +29,11 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
tls := strings.ToLower(query.Get("security"))
|
||||
if strings.HasSuffix(tls, "tls") {
|
||||
proxy["tls"] = true
|
||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||
proxy["client-fingerprint"] = "chrome"
|
||||
} else {
|
||||
proxy["client-fingerprint"] = fingerprint
|
||||
}
|
||||
}
|
||||
if sni := query.Get("sni"); sni != "" {
|
||||
proxy["servername"] = sni
|
||||
@ -87,6 +101,17 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
wsOpts["path"] = query.Get("path")
|
||||
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
|
||||
|
||||
case "grpc":
|
||||
@ -94,4 +119,5 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||
proxy["grpc-opts"] = grpcOpts
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -5,10 +5,10 @@
|
||||
// Package list implements a doubly linked list.
|
||||
//
|
||||
// To iterate over a list (where l is a *List):
|
||||
//
|
||||
// for e := l.Front(); e != nil; e = e.Next() {
|
||||
// // do something with e.Value
|
||||
// }
|
||||
//
|
||||
package list
|
||||
|
||||
// Element is an element of a linked list.
|
||||
|
@ -3,18 +3,23 @@ package net
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
|
||||
"github.com/Dreamacro/clash/common/buf"
|
||||
)
|
||||
|
||||
var _ ExtendedConn = (*BufferedConn)(nil)
|
||||
|
||||
type BufferedConn struct {
|
||||
r *bufio.Reader
|
||||
net.Conn
|
||||
ExtendedConn
|
||||
peeked bool
|
||||
}
|
||||
|
||||
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||
if bc, ok := c.(*BufferedConn); ok {
|
||||
return bc
|
||||
}
|
||||
return &BufferedConn{bufio.NewReader(c), c}
|
||||
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
||||
}
|
||||
|
||||
// Reader returns the internal bufio.Reader.
|
||||
@ -22,11 +27,24 @@ func (c *BufferedConn) Reader() *bufio.Reader {
|
||||
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.
|
||||
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||
c.peeked = true
|
||||
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) {
|
||||
return c.r.Read(p)
|
||||
}
|
||||
@ -42,3 +60,22 @@ func (c *BufferedConn) UnreadByte() error {
|
||||
func (c *BufferedConn) Buffered() int {
|
||||
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)
|
||||
}
|
||||
|
||||
func (c *refConn) Upstream() any {
|
||||
return c.conn
|
||||
}
|
||||
|
||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||
return &refConn{conn: conn, ref: ref}
|
||||
}
|
||||
|
@ -1,24 +1,24 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Relay copies between left and right bidirectionally.
|
||||
func Relay(leftConn, rightConn net.Conn) {
|
||||
ch := make(chan error)
|
||||
|
||||
go func() {
|
||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||
leftConn.SetReadDeadline(time.Now())
|
||||
ch <- err
|
||||
}()
|
||||
|
||||
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||
rightConn.SetReadDeadline(time.Now())
|
||||
<-ch
|
||||
}
|
||||
//import (
|
||||
// "io"
|
||||
// "net"
|
||||
// "time"
|
||||
//)
|
||||
//
|
||||
//// Relay copies between left and right bidirectionally.
|
||||
//func Relay(leftConn, rightConn net.Conn) {
|
||||
// ch := make(chan error)
|
||||
//
|
||||
// go func() {
|
||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||
// // See also https://github.com/Dreamacro/clash/pull/1209
|
||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||
// leftConn.SetReadDeadline(time.Now())
|
||||
// ch <- err
|
||||
// }()
|
||||
//
|
||||
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||
// rightConn.SetReadDeadline(time.Now())
|
||||
// <-ch
|
||||
//}
|
||||
|
22
common/net/sing.go
Normal file
22
common/net/sing.go
Normal file
@ -0,0 +1,22 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
"github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var NewExtendedConn = bufio.NewExtendedConn
|
||||
var NewExtendedWriter = bufio.NewExtendedWriter
|
||||
var NewExtendedReader = bufio.NewExtendedReader
|
||||
|
||||
type ExtendedConn = network.ExtendedConn
|
||||
type ExtendedWriter = network.ExtendedWriter
|
||||
type ExtendedReader = network.ExtendedReader
|
||||
|
||||
// Relay copies between left and right bidirectionally.
|
||||
func Relay(leftConn, rightConn net.Conn) {
|
||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
||||
}
|
@ -1,11 +1,19 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||
if certificate == "" || privateKey == "" {
|
||||
return newRandomTLSKeyPair()
|
||||
}
|
||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||
if painTextErr == nil {
|
||||
return cert, nil
|
||||
@ -17,3 +25,28 @@ func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
||||
certDER, err := x509.CreateCertificate(
|
||||
rand.Reader,
|
||||
&template,
|
||||
&template,
|
||||
&key.PublicKey,
|
||||
key)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||
|
||||
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
return tlsCert, nil
|
||||
}
|
||||
|
131
common/net/websocket.go
Normal file
131
common/net/websocket.go
Normal file
@ -0,0 +1,131 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
// kanged from https://github.com/nhooyr/websocket/blob/master/frame.go
|
||||
// License: MIT
|
||||
|
||||
// MaskWebSocket applies the WebSocket masking algorithm to p
|
||||
// with the given key.
|
||||
// See https://tools.ietf.org/html/rfc6455#section-5.3
|
||||
//
|
||||
// The returned value is the correctly rotated key to
|
||||
// to continue to mask/unmask the message.
|
||||
//
|
||||
// It is optimized for LittleEndian and expects the key
|
||||
// to be in little endian.
|
||||
//
|
||||
// See https://github.com/golang/go/issues/31586
|
||||
func MaskWebSocket(key uint32, b []byte) uint32 {
|
||||
if len(b) >= 8 {
|
||||
key64 := uint64(key)<<32 | uint64(key)
|
||||
|
||||
// At some point in the future we can clean these unrolled loops up.
|
||||
// See https://github.com/golang/go/issues/31586#issuecomment-487436401
|
||||
|
||||
// Then we xor until b is less than 128 bytes.
|
||||
for len(b) >= 128 {
|
||||
v := binary.LittleEndian.Uint64(b)
|
||||
binary.LittleEndian.PutUint64(b, v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[8:16])
|
||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[16:24])
|
||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[24:32])
|
||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[32:40])
|
||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[40:48])
|
||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[48:56])
|
||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[56:64])
|
||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[64:72])
|
||||
binary.LittleEndian.PutUint64(b[64:72], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[72:80])
|
||||
binary.LittleEndian.PutUint64(b[72:80], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[80:88])
|
||||
binary.LittleEndian.PutUint64(b[80:88], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[88:96])
|
||||
binary.LittleEndian.PutUint64(b[88:96], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[96:104])
|
||||
binary.LittleEndian.PutUint64(b[96:104], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[104:112])
|
||||
binary.LittleEndian.PutUint64(b[104:112], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[112:120])
|
||||
binary.LittleEndian.PutUint64(b[112:120], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[120:128])
|
||||
binary.LittleEndian.PutUint64(b[120:128], v^key64)
|
||||
b = b[128:]
|
||||
}
|
||||
|
||||
// Then we xor until b is less than 64 bytes.
|
||||
for len(b) >= 64 {
|
||||
v := binary.LittleEndian.Uint64(b)
|
||||
binary.LittleEndian.PutUint64(b, v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[8:16])
|
||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[16:24])
|
||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[24:32])
|
||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[32:40])
|
||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[40:48])
|
||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[48:56])
|
||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[56:64])
|
||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
||||
b = b[64:]
|
||||
}
|
||||
|
||||
// Then we xor until b is less than 32 bytes.
|
||||
for len(b) >= 32 {
|
||||
v := binary.LittleEndian.Uint64(b)
|
||||
binary.LittleEndian.PutUint64(b, v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[8:16])
|
||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[16:24])
|
||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[24:32])
|
||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
||||
b = b[32:]
|
||||
}
|
||||
|
||||
// Then we xor until b is less than 16 bytes.
|
||||
for len(b) >= 16 {
|
||||
v := binary.LittleEndian.Uint64(b)
|
||||
binary.LittleEndian.PutUint64(b, v^key64)
|
||||
v = binary.LittleEndian.Uint64(b[8:16])
|
||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
||||
b = b[16:]
|
||||
}
|
||||
|
||||
// Then we xor until b is less than 8 bytes.
|
||||
for len(b) >= 8 {
|
||||
v := binary.LittleEndian.Uint64(b)
|
||||
binary.LittleEndian.PutUint64(b, v^key64)
|
||||
b = b[8:]
|
||||
}
|
||||
}
|
||||
|
||||
// Then we xor until b is less than 4 bytes.
|
||||
for len(b) >= 4 {
|
||||
v := binary.LittleEndian.Uint32(b)
|
||||
binary.LittleEndian.PutUint32(b, v^key)
|
||||
b = b[4:]
|
||||
}
|
||||
|
||||
// xor remaining bytes.
|
||||
for i := range b {
|
||||
b[i] ^= byte(key)
|
||||
key = bits.RotateLeft32(key, -8)
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
@ -10,16 +11,8 @@ import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type controlFn = func(network, address string, c syscall.RawConn) 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)
|
||||
}
|
||||
}()
|
||||
|
||||
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
|
||||
@ -49,7 +42,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
||||
return err
|
||||
}
|
||||
|
||||
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
|
||||
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -59,6 +52,10 @@ func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address
|
||||
return "", err
|
||||
}
|
||||
|
||||
lc.Control = bindControl(ifaceObj.Index, lc.Control)
|
||||
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func ParseNetwork(network string, addr netip.Addr) string {
|
||||
return network
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
@ -8,16 +9,8 @@ import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type controlFn = func(network, address string, c syscall.RawConn) 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)
|
||||
}
|
||||
}()
|
||||
|
||||
func bindControl(ifaceName string) 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
|
||||
@ -37,13 +30,17 @@ func bindControl(ifaceName string, chain controlFn) controlFn {
|
||||
}
|
||||
|
||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
||||
dialer.Control = bindControl(ifaceName, dialer.Control)
|
||||
addControlToDialer(dialer, bindControl(ifaceName))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||
lc.Control = bindControl(ifaceName, lc.Control)
|
||||
addControlToListenConfig(lc, bindControl(ifaceName))
|
||||
|
||||
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
|
||||
|
||||
@ -91,3 +91,13 @@ func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, add
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
@ -6,36 +6,23 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
)
|
||||
|
||||
var (
|
||||
dialMux sync.Mutex
|
||||
actualSingleDialContext = singleDialContext
|
||||
actualDualStackDialContext = dualStackDialContext
|
||||
tcpConcurrent = false
|
||||
DisableIPv6 = false
|
||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
||||
dialMux sync.Mutex
|
||||
actualSingleStackDialContext = serialSingleStackDialContext
|
||||
actualDualStackDialContext = serialDualStackDialContext
|
||||
tcpConcurrent = false
|
||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||
ErrorConnTimeout = errors.New("connect timeout")
|
||||
fallbackTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
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 {
|
||||
opt := &option{
|
||||
interfaceName: DefaultInterface.Load(),
|
||||
@ -68,7 +55,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
||||
|
||||
switch network {
|
||||
case "tcp4", "tcp6", "udp4", "udp6":
|
||||
return actualSingleDialContext(ctx, network, address, opt)
|
||||
return actualSingleStackDialContext(ctx, network, address, opt)
|
||||
case "tcp", "udp":
|
||||
return actualDualStackDialContext(ctx, network, address, opt)
|
||||
default:
|
||||
@ -77,18 +64,7 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
||||
}
|
||||
|
||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||
cfg := &option{
|
||||
interfaceName: DefaultInterface.Load(),
|
||||
routingMark: int(DefaultRoutingMark.Load()),
|
||||
}
|
||||
|
||||
for _, o := range DefaultOptions {
|
||||
o(cfg)
|
||||
}
|
||||
|
||||
for _, o := range options {
|
||||
o(cfg)
|
||||
}
|
||||
cfg := applyOptions(options...)
|
||||
|
||||
lc := &net.ListenConfig{}
|
||||
if cfg.interfaceName != "" {
|
||||
@ -112,11 +88,11 @@ func SetDial(concurrent bool) {
|
||||
dialMux.Lock()
|
||||
tcpConcurrent = concurrent
|
||||
if concurrent {
|
||||
actualSingleDialContext = concurrentSingleDialContext
|
||||
actualSingleStackDialContext = concurrentSingleStackDialContext
|
||||
actualDualStackDialContext = concurrentDualStackDialContext
|
||||
} else {
|
||||
actualSingleDialContext = singleDialContext
|
||||
actualDualStackDialContext = dualStackDialContext
|
||||
actualSingleStackDialContext = serialSingleStackDialContext
|
||||
actualDualStackDialContext = serialDualStackDialContext
|
||||
}
|
||||
|
||||
dialMux.Unlock()
|
||||
@ -137,312 +113,64 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||
}
|
||||
|
||||
if DisableIPv6 && destination.Is6() {
|
||||
return nil, ErrorDisableIPv6
|
||||
address := net.JoinHostPort(destination.String(), port)
|
||||
if opt.tfo {
|
||||
return dialTFO(ctx, *dialer, network, address)
|
||||
}
|
||||
|
||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
|
||||
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
func serialSingleStackDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return serialDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func serialDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dualStackDialContext(
|
||||
ctx,
|
||||
func(ctx context.Context) (net.Conn, error) { return serialDialContext(ctx, network, ips, port, opt) },
|
||||
func(ctx context.Context) (net.Conn, error) { return serialDialContext(ctx, network, ips, port, opt) },
|
||||
opt.prefer == 4)
|
||||
}
|
||||
|
||||
func concurrentSingleStackDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
|
||||
type dialResult struct {
|
||||
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() {
|
||||
select {
|
||||
case results <- result:
|
||||
case <-returned:
|
||||
if result.Conn != nil {
|
||||
_ = result.Conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
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 startRacer(ctx, network+"4", host, opt.resolver, false)
|
||||
go startRacer(ctx, network+"6", host, opt.resolver, true)
|
||||
|
||||
count := 2
|
||||
for i := 0; i < count; i++ {
|
||||
select {
|
||||
case res := <-results:
|
||||
if res.error == nil {
|
||||
return res.Conn, nil
|
||||
}
|
||||
|
||||
if !res.ipv6 {
|
||||
primary = res
|
||||
} else {
|
||||
fallback = res
|
||||
}
|
||||
|
||||
if primary.done && fallback.done {
|
||||
if primary.resolved {
|
||||
return nil, primary.error
|
||||
} else if fallback.resolved {
|
||||
return nil, fallback.error
|
||||
} else {
|
||||
return nil, primary.error
|
||||
}
|
||||
}
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
err = fmt.Errorf("dual stack dial failed")
|
||||
if conn, err := parallelDialContext(ctx, network, ips, port, opt); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
err = fmt.Errorf("dual stack dial failed:%w", err)
|
||||
return conn, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ips []netip.Addr
|
||||
if opt.resolver != nil {
|
||||
ips, err = resolver.LookupIPWithResolver(ctx, host, opt.resolver)
|
||||
} else {
|
||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||
if opt.prefer != 4 && opt.prefer != 6 {
|
||||
return parallelDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
|
||||
type dialResult struct {
|
||||
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() {
|
||||
select {
|
||||
case results <- result:
|
||||
case <-returned:
|
||||
if result.Conn != nil {
|
||||
_ = result.Conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
if strings.Contains(network, "tcp") {
|
||||
network = "tcp"
|
||||
} else {
|
||||
network = "udp"
|
||||
}
|
||||
|
||||
if ip.Is6() {
|
||||
network += "6"
|
||||
if opt.prefer != 4 {
|
||||
result.isPrimary = true
|
||||
}
|
||||
}
|
||||
|
||||
if ip.Is4() {
|
||||
network += "4"
|
||||
if opt.prefer != 6 {
|
||||
result.isPrimary = true
|
||||
}
|
||||
}
|
||||
|
||||
if result.isPrimary {
|
||||
preferCount.Add(1)
|
||||
}
|
||||
|
||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||
}
|
||||
|
||||
for _, ip := range ips {
|
||||
go tcpRacer(ctx, ip)
|
||||
}
|
||||
|
||||
connCount := len(ips)
|
||||
var fallback dialResult
|
||||
var primaryError error
|
||||
var finalError error
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
if fallback.done && fallback.error == nil {
|
||||
return fallback.Conn, nil
|
||||
}
|
||||
|
||||
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) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, 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
|
||||
if opt.resolver == nil {
|
||||
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
||||
} else {
|
||||
ips, err = resolver.LookupIPv4WithResolver(ctx, host, opt.resolver)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||
}
|
||||
|
||||
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ips []netip.Addr
|
||||
if opt.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)
|
||||
ipv4s, ipv6s := sortationAddr(ips)
|
||||
return dualStackDialContext(
|
||||
ctx,
|
||||
func(ctx context.Context) (net.Conn, error) {
|
||||
return parallelDialContext(ctx, network, ipv4s, port, opt)
|
||||
},
|
||||
func(ctx context.Context) (net.Conn, error) {
|
||||
return parallelDialContext(ctx, network, ipv6s, port, opt)
|
||||
},
|
||||
opt.prefer == 4)
|
||||
}
|
||||
|
||||
type Dialer struct {
|
||||
@ -461,3 +189,162 @@ func NewDialer(options ...Option) Dialer {
|
||||
opt := applyOptions(options...)
|
||||
return Dialer{Opt: *opt}
|
||||
}
|
||||
|
||||
func dualStackDialContext(
|
||||
ctx context.Context,
|
||||
ipv4DialFn func(ctx context.Context) (net.Conn, error),
|
||||
ipv6DialFn func(ctx context.Context) (net.Conn, error),
|
||||
preferIPv4 bool) (net.Conn, error) {
|
||||
fallbackTicker := time.NewTicker(fallbackTimeout)
|
||||
defer fallbackTicker.Stop()
|
||||
results := make(chan dialResult)
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
racer := func(dial func(ctx context.Context) (net.Conn, error), isPrimary bool) {
|
||||
result := dialResult{isPrimary: isPrimary}
|
||||
defer func() {
|
||||
select {
|
||||
case results <- result:
|
||||
case <-returned:
|
||||
if result.Conn != nil {
|
||||
_ = result.Conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
result.Conn, result.error = dial(ctx)
|
||||
}
|
||||
go racer(ipv4DialFn, preferIPv4)
|
||||
go racer(ipv6DialFn, !preferIPv4)
|
||||
var fallback dialResult
|
||||
var err error
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if fallback.error == nil && fallback.Conn != nil {
|
||||
return fallback.Conn, nil
|
||||
}
|
||||
return nil, fmt.Errorf("dual stack connect failed: %w", err)
|
||||
case <-fallbackTicker.C:
|
||||
if fallback.error == nil && fallback.Conn != nil {
|
||||
return fallback.Conn, nil
|
||||
}
|
||||
case res := <-results:
|
||||
if res.error == nil {
|
||||
if res.isPrimary {
|
||||
return res.Conn, nil
|
||||
}
|
||||
fallback = res
|
||||
}
|
||||
err = res.error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
results := make(chan dialResult)
|
||||
returned := make(chan struct{})
|
||||
defer close(returned)
|
||||
tcpRacer := func(ctx context.Context, ip netip.Addr, port string) {
|
||||
result := dialResult{isPrimary: true}
|
||||
defer func() {
|
||||
select {
|
||||
case results <- result:
|
||||
case <-returned:
|
||||
if result.Conn != nil {
|
||||
_ = result.Conn.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
result.ip = ip
|
||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||
}
|
||||
|
||||
for _, ip := range ips {
|
||||
go tcpRacer(ctx, ip, port)
|
||||
}
|
||||
var err error
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return nil, ErrorConnTimeout
|
||||
}
|
||||
return nil, ctx.Err()
|
||||
case res := <-results:
|
||||
if res.error == nil {
|
||||
return res.Conn, nil
|
||||
}
|
||||
err = res.error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||
var (
|
||||
conn net.Conn
|
||||
err error
|
||||
errs []error
|
||||
)
|
||||
for _, ip := range ips {
|
||||
if conn, err = dialContext(ctx, network, ip, port, opt); err == nil {
|
||||
return conn, nil
|
||||
} else {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return nil, errors.Join(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)
|
||||
if err != nil {
|
||||
return nil, "-1", err
|
||||
}
|
||||
|
||||
var ips []netip.Addr
|
||||
switch network {
|
||||
case "tcp4", "udp4":
|
||||
if preferResolver == nil {
|
||||
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.LookupIP(ctx, host)
|
||||
} else {
|
||||
ips, err = resolver.LookupIPWithResolver(ctx, host, preferResolver)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "-1", fmt.Errorf("dns resolve failed: %w", err)
|
||||
}
|
||||
return ips, port, nil
|
||||
}
|
||||
|
||||
func sortationAddr(ips []netip.Addr) (ipv4s, ipv6s []netip.Addr) {
|
||||
for _, v := range ips {
|
||||
if v.Is4() || v.Is4In6() {
|
||||
ipv4s = append(ipv4s, v)
|
||||
} else {
|
||||
ipv6s = append(ipv6s, v)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@ -3,26 +3,22 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
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) {
|
||||
lc.Control = bindMarkToControl(mark, lc.Control)
|
||||
addControlToListenConfig(lc, bindMarkToControl(mark))
|
||||
}
|
||||
|
||||
func bindMarkToControl(mark 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)
|
||||
}
|
||||
}()
|
||||
func bindMarkToControl(mark 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() {
|
||||
|
@ -18,6 +18,7 @@ type option struct {
|
||||
routingMark int
|
||||
network int
|
||||
prefer int
|
||||
tfo bool
|
||||
resolver resolver.Resolver
|
||||
}
|
||||
|
||||
@ -69,6 +70,12 @@ func WithOnlySingleStack(isIPv4 bool) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func WithTFO(tfo bool) Option {
|
||||
return func(opt *option) {
|
||||
opt.tfo = tfo
|
||||
}
|
||||
}
|
||||
|
||||
func WithOption(o option) Option {
|
||||
return func(opt *option) {
|
||||
*opt = o
|
||||
|
@ -3,6 +3,7 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
@ -10,18 +11,10 @@ import (
|
||||
)
|
||||
|
||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||
chain := lc.Control
|
||||
|
||||
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||
defer func() {
|
||||
if err == nil && chain != nil {
|
||||
err = chain(network, address, c)
|
||||
}
|
||||
}()
|
||||
|
||||
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
||||
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_REUSEPORT, 1)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
@ -8,17 +9,9 @@ import (
|
||||
)
|
||||
|
||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||
chain := lc.Control
|
||||
|
||||
lc.Control = func(network, address string, c syscall.RawConn) (err error) {
|
||||
defer func() {
|
||||
if err == nil && chain != nil {
|
||||
err = chain(network, address, c)
|
||||
}
|
||||
}()
|
||||
|
||||
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
||||
return c.Control(func(fd uintptr) {
|
||||
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
119
component/dialer/tfo.go
Normal file
119
component/dialer/tfo.go
Normal file
@ -0,0 +1,119 @@
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sagernet/tfo-go"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type tfoConn struct {
|
||||
net.Conn
|
||||
closed bool
|
||||
dialed chan bool
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
dialFn func(ctx context.Context, earlyData []byte) (net.Conn, error)
|
||||
}
|
||||
|
||||
func (c *tfoConn) Dial(earlyData []byte) (err error) {
|
||||
c.Conn, err = c.dialFn(c.ctx, earlyData)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.dialed <- true
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *tfoConn) Read(b []byte) (n int, err error) {
|
||||
if c.closed {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if c.Conn == nil {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
case <-c.dialed:
|
||||
}
|
||||
}
|
||||
return c.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (c *tfoConn) Write(b []byte) (n int, err error) {
|
||||
if c.closed {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if c.Conn == nil {
|
||||
if err := c.Dial(b); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
return c.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (c *tfoConn) Close() error {
|
||||
c.closed = true
|
||||
c.cancel()
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func (c *tfoConn) LocalAddr() net.Addr {
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (c *tfoConn) RemoteAddr() net.Addr {
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (c *tfoConn) SetDeadline(t time.Time) error {
|
||||
if err := c.SetReadDeadline(t); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (c *tfoConn) SetReadDeadline(t time.Time) error {
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (c *tfoConn) SetWriteDeadline(t time.Time) error {
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (c *tfoConn) Upstream() any {
|
||||
if c.Conn == nil { // ensure return a nil interface not an interface with nil value
|
||||
return nil
|
||||
}
|
||||
return c.Conn
|
||||
}
|
||||
|
||||
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
||||
return &tfoConn{
|
||||
dialed: make(chan bool, 1),
|
||||
cancel: cancel,
|
||||
ctx: ctx,
|
||||
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
||||
return dialer.DialContext(ctx, network, address, earlyData)
|
||||
},
|
||||
}, nil
|
||||
}
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||
//
|
||||
// The following types are suitable as obj argument:
|
||||
//
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
//
|
||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||
@ -134,5 +134,6 @@ func _BpfClose(closers ...io.Closer) error {
|
||||
}
|
||||
|
||||
// Do not access this directly.
|
||||
//
|
||||
//go:embed bpf_bpfeb.o
|
||||
var _BpfBytes []byte
|
||||
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||
//
|
||||
// The following types are suitable as obj argument:
|
||||
//
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
//
|
||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||
@ -134,5 +134,6 @@ func _BpfClose(closers ...io.Closer) error {
|
||||
}
|
||||
|
||||
// Do not access this directly.
|
||||
//
|
||||
//go:embed bpf_bpfel.o
|
||||
var _BpfBytes []byte
|
||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||
//
|
||||
// The following types are suitable as obj argument:
|
||||
//
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
//
|
||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||
@ -115,5 +115,6 @@ func _BpfClose(closers ...io.Closer) error {
|
||||
}
|
||||
|
||||
// Do not access this directly.
|
||||
//
|
||||
//go:embed bpf_bpfeb.o
|
||||
var _BpfBytes []byte
|
||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||
//
|
||||
// The following types are suitable as obj argument:
|
||||
//
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
// *bpfObjects
|
||||
// *bpfPrograms
|
||||
// *bpfMaps
|
||||
//
|
||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||
@ -115,5 +115,6 @@ func _BpfClose(closers ...io.Closer) error {
|
||||
}
|
||||
|
||||
// Do not access this directly.
|
||||
//
|
||||
//go:embed bpf_bpfel.o
|
||||
var _BpfBytes []byte
|
||||
|
@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
UA = "Clash"
|
||||
UA = "clash.meta"
|
||||
)
|
||||
|
||||
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||
|
@ -1,6 +1,7 @@
|
||||
package nat
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
@ -10,16 +11,24 @@ type Table struct {
|
||||
mapping sync.Map
|
||||
}
|
||||
|
||||
func (t *Table) Set(key string, pc C.PacketConn) {
|
||||
t.mapping.Store(key, pc)
|
||||
type Entry struct {
|
||||
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 {
|
||||
item, exist := t.mapping.Load(key)
|
||||
entry, exist := t.getEntry(key)
|
||||
if !exist {
|
||||
return nil
|
||||
}
|
||||
return item.(C.PacketConn)
|
||||
return entry.PacketConn
|
||||
}
|
||||
|
||||
func (t *Table) GetOrCreateLock(key string) (*sync.Cond, bool) {
|
||||
@ -31,6 +40,62 @@ func (t *Table) Delete(key string) {
|
||||
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
|
||||
func New() *Table {
|
||||
return &Table{}
|
||||
|
@ -16,14 +16,6 @@ const (
|
||||
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)
|
||||
}
|
||||
|
||||
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) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, port int) (*uint32, string, error) {
|
||||
func findProcessName(network string, ip netip.Addr, port int) (uint32, string, error) {
|
||||
var spath string
|
||||
switch network {
|
||||
case TCP:
|
||||
@ -45,14 +41,14 @@ func findProcessName(network string, ip netip.Addr, port int) (*uint32, string,
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist_n"
|
||||
default:
|
||||
return nil, "", ErrInvalidNetwork
|
||||
return 0, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
isIPv4 := ip.Is4()
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
@ -96,7 +92,7 @@ func findProcessName(network string, ip netip.Addr, port int) (*uint32, string,
|
||||
// xsocket_n.so_last_pid
|
||||
pid := readNativeUint32(buf[so+68 : so+72])
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return nil, pp, err
|
||||
return 0, pp, err
|
||||
}
|
||||
|
||||
// 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 != "" {
|
||||
return nil, fallbackUDPProcess, nil
|
||||
return 0, fallbackUDPProcess, nil
|
||||
}
|
||||
|
||||
return nil, "", ErrNotFound
|
||||
return 0, "", ErrNotFound
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
|
@ -21,11 +21,7 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
||||
return 0, 0, ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
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() {
|
||||
if err := initSearcher(); err != nil {
|
||||
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 {
|
||||
return nil, "", ErrPlatformNotSupport
|
||||
return 0, "", ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
var spath string
|
||||
@ -46,22 +42,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, strin
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist"
|
||||
default:
|
||||
return nil, "", ErrInvalidNetwork
|
||||
return 0, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return nil, pp, err
|
||||
return 0, pp, err
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
|
@ -59,14 +59,14 @@ type inetDiagResponse struct {
|
||||
INode uint32
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
||||
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||
uid, inode, err := resolveSocketByNetlink(network, ip, srcPort)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
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) {
|
||||
@ -119,7 +119,7 @@ func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32,
|
||||
|
||||
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
|
||||
|
||||
return response.INode, response.UID, nil
|
||||
return response.UID, response.INode, nil
|
||||
}
|
||||
|
||||
return 0, 0, ErrNotFound
|
||||
|
@ -4,8 +4,8 @@ package process
|
||||
|
||||
import "net/netip"
|
||||
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, string, error) {
|
||||
return nil, "", ErrPlatformNotSupport
|
||||
func findProcessName(network string, ip netip.Addr, srcPort int) (uint32, string, error) {
|
||||
return 0, "", ErrPlatformNotSupport
|
||||
}
|
||||
|
||||
func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (uint32, uint32, error) {
|
||||
|
@ -62,7 +62,7 @@ func initWin32API() error {
|
||||
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() {
|
||||
err := initWin32API()
|
||||
if err != nil {
|
||||
@ -86,22 +86,22 @@ func findProcessName(network string, ip netip.Addr, srcPort int) (*uint32, strin
|
||||
fn = getExUDPTable
|
||||
class = udpTablePid
|
||||
default:
|
||||
return nil, "", ErrInvalidNetwork
|
||||
return 0, "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
buf, err := getTransportTable(fn, family, class)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||
|
||||
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return 0, "", err
|
||||
}
|
||||
pp, err := getExecPathFromPID(pid)
|
||||
return nil, pp, err
|
||||
return 0, pp, err
|
||||
}
|
||||
|
||||
type searcher struct {
|
||||
|
@ -11,6 +11,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -44,6 +46,7 @@ type Resolver interface {
|
||||
ResolveIP(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)
|
||||
ExchangeContext(ctx context.Context, m *dns.Msg) (msg *dns.Msg, err error)
|
||||
}
|
||||
|
||||
// LookupIPv4WithResolver same as LookupIPv4, but with a resolver
|
||||
|
@ -57,7 +57,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
||||
f.UpdatedAt = &modTime
|
||||
isLocal = true
|
||||
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
|
||||
}
|
||||
} else {
|
||||
@ -162,7 +162,7 @@ func (f *Fetcher[V]) pullLoop() {
|
||||
case <-f.ticker.C:
|
||||
elm, same, err := f.Update()
|
||||
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
|
||||
}
|
||||
|
||||
|
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"
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/sniffer"
|
||||
@ -27,26 +26,17 @@ var (
|
||||
var Dispatcher *SnifferDispatcher
|
||||
|
||||
type SnifferDispatcher struct {
|
||||
enable bool
|
||||
|
||||
sniffers []sniffer.Sniffer
|
||||
|
||||
forceDomain *trie.DomainTrie[struct{}]
|
||||
skipSNI *trie.DomainTrie[struct{}]
|
||||
portRanges *[]utils.Range[uint16]
|
||||
skipList *cache.LruCache[string, uint8]
|
||||
rwMux sync.RWMutex
|
||||
|
||||
enable bool
|
||||
sniffers map[sniffer.Sniffer]SnifferConfig
|
||||
forceDomain *trie.DomainTrie[struct{}]
|
||||
skipSNI *trie.DomainTrie[struct{}]
|
||||
skipList *cache.LruCache[string, uint8]
|
||||
rwMux sync.RWMutex
|
||||
forceDnsMapping bool
|
||||
parsePureIp bool
|
||||
}
|
||||
|
||||
func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
||||
bufConn, ok := conn.(*N.BufferedConn)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
func (sd *SnifferDispatcher) TCPSniff(conn *N.BufferedConn, metadata *C.Metadata) {
|
||||
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)
|
||||
if err != nil {
|
||||
@ -55,10 +45,14 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
||||
}
|
||||
|
||||
inWhitelist := false
|
||||
for _, portRange := range *sd.portRanges {
|
||||
if portRange.Contains(uint16(port)) {
|
||||
inWhitelist = true
|
||||
break
|
||||
overrideDest := false
|
||||
for sniffer, config := range sd.sniffers {
|
||||
if sniffer.SupportNetwork() == C.TCP || sniffer.SupportNetwork() == C.ALLNet {
|
||||
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()
|
||||
|
||||
if host, err := sd.sniffDomain(bufConn, metadata); err != nil {
|
||||
if host, err := sd.sniffDomain(conn, metadata); err != nil {
|
||||
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)
|
||||
return
|
||||
@ -89,31 +83,21 @@ func (sd *SnifferDispatcher) TCPSniff(conn net.Conn, metadata *C.Metadata) {
|
||||
sd.skipList.Delete(dst)
|
||||
sd.rwMux.RUnlock()
|
||||
|
||||
sd.replaceDomain(metadata, host)
|
||||
sd.replaceDomain(metadata, host, overrideDest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string) {
|
||||
dstIP := ""
|
||||
if metadata.DstIP.IsValid() {
|
||||
dstIP = metadata.DstIP.String()
|
||||
func (sd *SnifferDispatcher) replaceDomain(metadata *C.Metadata, host string, overrideDest bool) {
|
||||
metadata.SniffHost = host
|
||||
if overrideDest {
|
||||
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
|
||||
log.Debugln("[Sniffer] Sniff TCP [%s]-->[%s] success, replace domain [%s]-->[%s]",
|
||||
metadata.SourceDetail(),
|
||||
metadata.RemoteAddress(),
|
||||
metadata.Host, host)
|
||||
}
|
||||
|
||||
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) {
|
||||
for _, s := range sd.sniffers {
|
||||
for s := range sd.sniffers {
|
||||
if s.SupportNetwork() == C.TCP {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(1 * time.Second))
|
||||
_, err := conn.Peek(1)
|
||||
@ -182,38 +166,37 @@ func NewCloseSnifferDispatcher() (*SnifferDispatcher, error) {
|
||||
return &dispatcher, nil
|
||||
}
|
||||
|
||||
func NewSnifferDispatcher(needSniffer []sniffer.Type, forceDomain *trie.DomainTrie[struct{}],
|
||||
skipSNI *trie.DomainTrie[struct{}], ports *[]utils.Range[uint16],
|
||||
func NewSnifferDispatcher(snifferConfig map[sniffer.Type]SnifferConfig, forceDomain *trie.DomainTrie[struct{}],
|
||||
skipSNI *trie.DomainTrie[struct{}],
|
||||
forceDnsMapping bool, parsePureIp bool) (*SnifferDispatcher, error) {
|
||||
dispatcher := SnifferDispatcher{
|
||||
enable: true,
|
||||
forceDomain: forceDomain,
|
||||
skipSNI: skipSNI,
|
||||
portRanges: ports,
|
||||
skipList: cache.New[string, uint8](cache.WithSize[string, uint8](128), cache.WithAge[string, uint8](600)),
|
||||
skipList: cache.New(cache.WithSize[string, uint8](128), cache.WithAge[string, uint8](600)),
|
||||
forceDnsMapping: forceDnsMapping,
|
||||
parsePureIp: parsePureIp,
|
||||
sniffers: make(map[sniffer.Sniffer]SnifferConfig, 0),
|
||||
}
|
||||
|
||||
for _, snifferName := range needSniffer {
|
||||
s, err := NewSniffer(snifferName)
|
||||
for snifferName, config := range snifferConfig {
|
||||
s, err := NewSniffer(snifferName, config)
|
||||
if err != nil {
|
||||
log.Errorln("Sniffer name[%s] is error", snifferName)
|
||||
return &SnifferDispatcher{enable: false}, err
|
||||
}
|
||||
|
||||
dispatcher.sniffers = append(dispatcher.sniffers, s)
|
||||
dispatcher.sniffers[s] = config
|
||||
}
|
||||
|
||||
return &dispatcher, nil
|
||||
}
|
||||
|
||||
func NewSniffer(name sniffer.Type) (sniffer.Sniffer, error) {
|
||||
func NewSniffer(name sniffer.Type, snifferConfig SnifferConfig) (sniffer.Sniffer, error) {
|
||||
switch name {
|
||||
case sniffer.TLS:
|
||||
return &TLSSniffer{}, nil
|
||||
return NewTLSSniffer(snifferConfig)
|
||||
case sniffer.HTTP:
|
||||
return &HTTPSniffer{}, nil
|
||||
return NewHTTPSniffer(snifferConfig)
|
||||
default:
|
||||
return nil, ErrorUnsupportedSniffer
|
||||
}
|
||||
|
@ -7,7 +7,9 @@ import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/sniffer"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -24,10 +26,25 @@ const (
|
||||
)
|
||||
|
||||
type HTTPSniffer struct {
|
||||
*BaseSniffer
|
||||
version version
|
||||
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 {
|
||||
switch http.version {
|
||||
case HTTP1:
|
||||
|
@ -5,7 +5,9 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/Dreamacro/clash/common/utils"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/constant/sniffer"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -13,7 +15,22 @@ var (
|
||||
errNotClientHello = errors.New("not client hello")
|
||||
)
|
||||
|
||||
var _ sniffer.Sniffer = (*TLSSniffer)(nil)
|
||||
|
||||
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 {
|
||||
|
@ -6,75 +6,69 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
xtls "github.com/xtls/go"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
xtls "github.com/xtls/go"
|
||||
)
|
||||
|
||||
var globalFingerprints = make([][32]byte, 0, 0)
|
||||
var mutex sync.Mutex
|
||||
var trustCert,_ = x509.SystemCertPool()
|
||||
|
||||
func verifyPeerCertificateAndFingerprints(fingerprints *[][32]byte, insecureSkipVerify bool) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
var mutex sync.RWMutex
|
||||
var errNotMacth error = errors.New("certificate fingerprints do not match")
|
||||
|
||||
func AddCertificate(certificate string) error {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
if certificate == "" {
|
||||
return fmt.Errorf("certificate is empty")
|
||||
}
|
||||
if ok := trustCert.AppendCertsFromPEM([]byte(certificate)); !ok {
|
||||
return fmt.Errorf("add certificate failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ResetCertificate(){
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
trustCert,_=x509.SystemCertPool()
|
||||
}
|
||||
|
||||
func verifyFingerprint(fingerprint *[32]byte) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
||||
if insecureSkipVerify {
|
||||
return nil
|
||||
}
|
||||
|
||||
var preErr error
|
||||
// ssl pining
|
||||
for i := range rawCerts {
|
||||
rawCert := rawCerts[i]
|
||||
cert, err := x509.ParseCertificate(rawCert)
|
||||
if err == nil {
|
||||
opts := x509.VerifyOptions{
|
||||
CurrentTime: time.Now(),
|
||||
}
|
||||
|
||||
if _, err := cert.Verify(opts); err == nil {
|
||||
hash := sha256.Sum256(cert.Raw)
|
||||
if bytes.Equal(fingerprint[:], hash[:]) {
|
||||
return nil
|
||||
} else {
|
||||
fingerprint := sha256.Sum256(cert.Raw)
|
||||
for _, fp := range *fingerprints {
|
||||
if bytes.Equal(fingerprint[:], fp[:]) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
preErr = err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return preErr
|
||||
return errNotMacth
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
fingerprint = strings.TrimSpace(strings.Replace(fingerprint, ":", "", -1))
|
||||
fpByte, err := hex.DecodeString(fingerprint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func GetDefaultTLSConfig() *tls.Config {
|
||||
return GetGlobalFingerprintTLCConfig(nil)
|
||||
return GetGlobalTLSConfig(nil)
|
||||
}
|
||||
|
||||
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
||||
@ -82,29 +76,20 @@ func GetSpecifiedFingerprintTLSConfig(tlsConfig *tls.Config, fingerprint string)
|
||||
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
if tlsConfig == nil {
|
||||
return &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
||||
}, nil
|
||||
} else {
|
||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
return tlsConfig, nil
|
||||
}
|
||||
tlsConfig = GetGlobalTLSConfig(tlsConfig)
|
||||
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
return tlsConfig, nil
|
||||
}
|
||||
}
|
||||
|
||||
func GetGlobalFingerprintTLCConfig(tlsConfig *tls.Config) *tls.Config {
|
||||
func GetGlobalTLSConfig(tlsConfig *tls.Config) *tls.Config {
|
||||
if tlsConfig == nil {
|
||||
return &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
||||
RootCAs: trustCert,
|
||||
}
|
||||
}
|
||||
|
||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
tlsConfig.RootCAs = trustCert
|
||||
return tlsConfig
|
||||
}
|
||||
|
||||
@ -113,28 +98,20 @@ func GetSpecifiedFingerprintXTLSConfig(tlsConfig *xtls.Config, fingerprint strin
|
||||
if fingerprintBytes, err := convertFingerprint(fingerprint); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
if tlsConfig == nil {
|
||||
return &xtls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, false),
|
||||
}, nil
|
||||
} else {
|
||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&[][32]byte{*fingerprintBytes}, tlsConfig.InsecureSkipVerify)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
return tlsConfig, nil
|
||||
}
|
||||
tlsConfig = GetGlobalXTLSConfig(tlsConfig)
|
||||
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
return tlsConfig, nil
|
||||
}
|
||||
}
|
||||
|
||||
func GetGlobalFingerprintXTLCConfig(tlsConfig *xtls.Config) *xtls.Config {
|
||||
func GetGlobalXTLSConfig(tlsConfig *xtls.Config) *xtls.Config {
|
||||
if tlsConfig == nil {
|
||||
return &xtls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
VerifyPeerCertificate: verifyPeerCertificateAndFingerprints(&globalFingerprints, false),
|
||||
RootCAs: trustCert,
|
||||
}
|
||||
}
|
||||
|
||||
tlsConfig.VerifyPeerCertificate = verifyPeerCertificateAndFingerprints(&globalFingerprints, tlsConfig.InsecureSkipVerify)
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
tlsConfig.RootCAs = trustCert
|
||||
return tlsConfig
|
||||
}
|
||||
|
123
component/tls/utls.go
Normal file
123
component/tls/utls.go
Normal file
@ -0,0 +1,123 @@
|
||||
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]
|
||||
log.Debugln("use specified fingerprint:%s", fingerprint.Client)
|
||||
return fingerprint, ok
|
||||
}
|
||||
|
||||
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},
|
||||
"randomized": {&utls.HelloRandomized},
|
||||
}
|
||||
|
||||
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 {
|
||||
if len(initUtlsClient) != 0 && initUtlsClient != "none" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func GetGlobalFingerprint() string {
|
||||
return initUtlsClient
|
||||
}
|
366
config/config.go
366
config/config.go
@ -4,11 +4,12 @@ import (
|
||||
"container/list"
|
||||
"errors"
|
||||
"fmt"
|
||||
P "github.com/Dreamacro/clash/component/process"
|
||||
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -24,6 +25,9 @@ import (
|
||||
"github.com/Dreamacro/clash/component/fakeip"
|
||||
"github.com/Dreamacro/clash/component/geodata"
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
P "github.com/Dreamacro/clash/component/process"
|
||||
SNIFF "github.com/Dreamacro/clash/component/sniffer"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
||||
@ -43,19 +47,19 @@ import (
|
||||
type General struct {
|
||||
Inbound
|
||||
Controller
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"-"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
EnableProcess bool `json:"enable-process"`
|
||||
FindProcessMode P.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
EBpf EBpf `json:"-"`
|
||||
Mode T.TunnelMode `json:"mode"`
|
||||
UnifiedDelay bool
|
||||
LogLevel log.LogLevel `json:"log-level"`
|
||||
IPv6 bool `json:"ipv6"`
|
||||
Interface string `json:"interface-name"`
|
||||
RoutingMark int `json:"-"`
|
||||
GeodataMode bool `json:"geodata-mode"`
|
||||
GeodataLoader string `json:"geodata-loader"`
|
||||
TCPConcurrent bool `json:"tcp-concurrent"`
|
||||
FindProcessMode P.FindProcessMode `json:"find-process-mode"`
|
||||
Sniffing bool `json:"sniffing"`
|
||||
EBpf EBpf `json:"-"`
|
||||
GlobalClientFingerprint string `json:"global-client-fingerprint"`
|
||||
}
|
||||
|
||||
// Inbound config
|
||||
@ -96,7 +100,7 @@ type DNS struct {
|
||||
DefaultNameserver []dns.NameServer `yaml:"default-nameserver"`
|
||||
FakeIPRange *fakeip.Pool
|
||||
Hosts *trie.DomainTrie[netip.Addr]
|
||||
NameServerPolicy map[string]dns.NameServer
|
||||
NameServerPolicy map[string][]dns.NameServer
|
||||
ProxyServerNameserver []dns.NameServer
|
||||
}
|
||||
|
||||
@ -116,8 +120,9 @@ type Profile struct {
|
||||
}
|
||||
|
||||
type TLS struct {
|
||||
Certificate string `yaml:"certificate"`
|
||||
PrivateKey string `yaml:"private-key"`
|
||||
Certificate string `yaml:"certificate"`
|
||||
PrivateKey string `yaml:"private-key"`
|
||||
CustomTrustCert []string `yaml:"custom-certifactes"`
|
||||
}
|
||||
|
||||
// IPTables config
|
||||
@ -129,11 +134,10 @@ type IPTables struct {
|
||||
|
||||
type Sniffer struct {
|
||||
Enable bool
|
||||
Sniffers []snifferTypes.Type
|
||||
Sniffers map[snifferTypes.Type]SNIFF.SnifferConfig
|
||||
Reverses *trie.DomainTrie[struct{}]
|
||||
ForceDomain *trie.DomainTrie[struct{}]
|
||||
SkipDomain *trie.DomainTrie[struct{}]
|
||||
Ports *[]utils.Range[uint16]
|
||||
ForceDnsMapping bool
|
||||
ParsePureIp bool
|
||||
}
|
||||
@ -176,7 +180,7 @@ type RawDNS struct {
|
||||
FakeIPRange string `yaml:"fake-ip-range"`
|
||||
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
||||
DefaultNameserver []string `yaml:"default-nameserver"`
|
||||
NameServerPolicy map[string]string `yaml:"nameserver-policy"`
|
||||
NameServerPolicy map[string]any `yaml:"nameserver-policy"`
|
||||
ProxyServerNameserver []string `yaml:"proxy-server-nameserver"`
|
||||
}
|
||||
|
||||
@ -228,33 +232,33 @@ type RawTuicServer struct {
|
||||
}
|
||||
|
||||
type RawConfig struct {
|
||||
Port int `yaml:"port"`
|
||||
SocksPort int `yaml:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port"`
|
||||
TProxyPort int `yaml:"tproxy-port"`
|
||||
MixedPort int `yaml:"mixed-port"`
|
||||
ShadowSocksConfig string `yaml:"ss-config"`
|
||||
VmessConfig string `yaml:"vmess-config"`
|
||||
InboundTfo bool `yaml:"inbound-tfo"`
|
||||
Authentication []string `yaml:"authentication"`
|
||||
AllowLan bool `yaml:"allow-lan"`
|
||||
BindAddress string `yaml:"bind-address"`
|
||||
Mode T.TunnelMode `yaml:"mode"`
|
||||
UnifiedDelay bool `yaml:"unified-delay"`
|
||||
LogLevel log.LogLevel `yaml:"log-level"`
|
||||
IPv6 bool `yaml:"ipv6"`
|
||||
ExternalController string `yaml:"external-controller"`
|
||||
ExternalControllerTLS string `yaml:"external-controller-tls"`
|
||||
ExternalUI string `yaml:"external-ui"`
|
||||
Secret string `yaml:"secret"`
|
||||
Interface string `yaml:"interface-name"`
|
||||
RoutingMark int `yaml:"routing-mark"`
|
||||
Tunnels []LC.Tunnel `yaml:"tunnels"`
|
||||
GeodataMode bool `yaml:"geodata-mode"`
|
||||
GeodataLoader string `yaml:"geodata-loader"`
|
||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||
EnableProcess bool `yaml:"enable-process" json:"enable-process"`
|
||||
FindProcessMode P.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
||||
Port int `yaml:"port"`
|
||||
SocksPort int `yaml:"socks-port"`
|
||||
RedirPort int `yaml:"redir-port"`
|
||||
TProxyPort int `yaml:"tproxy-port"`
|
||||
MixedPort int `yaml:"mixed-port"`
|
||||
ShadowSocksConfig string `yaml:"ss-config"`
|
||||
VmessConfig string `yaml:"vmess-config"`
|
||||
InboundTfo bool `yaml:"inbound-tfo"`
|
||||
Authentication []string `yaml:"authentication"`
|
||||
AllowLan bool `yaml:"allow-lan"`
|
||||
BindAddress string `yaml:"bind-address"`
|
||||
Mode T.TunnelMode `yaml:"mode"`
|
||||
UnifiedDelay bool `yaml:"unified-delay"`
|
||||
LogLevel log.LogLevel `yaml:"log-level"`
|
||||
IPv6 bool `yaml:"ipv6"`
|
||||
ExternalController string `yaml:"external-controller"`
|
||||
ExternalControllerTLS string `yaml:"external-controller-tls"`
|
||||
ExternalUI string `yaml:"external-ui"`
|
||||
Secret string `yaml:"secret"`
|
||||
Interface string `yaml:"interface-name"`
|
||||
RoutingMark int `yaml:"routing-mark"`
|
||||
Tunnels []LC.Tunnel `yaml:"tunnels"`
|
||||
GeodataMode bool `yaml:"geodata-mode"`
|
||||
GeodataLoader string `yaml:"geodata-loader"`
|
||||
TCPConcurrent bool `yaml:"tcp-concurrent" json:"tcp-concurrent"`
|
||||
FindProcessMode P.FindProcessMode `yaml:"find-process-mode" json:"find-process-mode"`
|
||||
GlobalClientFingerprint string `yaml:"global-client-fingerprint"`
|
||||
|
||||
Sniffer RawSniffer `yaml:"sniffer"`
|
||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
||||
@ -283,13 +287,20 @@ type RawGeoXUrl struct {
|
||||
}
|
||||
|
||||
type RawSniffer struct {
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
Sniffing []string `yaml:"sniffing" json:"sniffing"`
|
||||
ForceDomain []string `yaml:"force-domain" json:"force-domain"`
|
||||
SkipDomain []string `yaml:"skip-domain" json:"skip-domain"`
|
||||
Ports []string `yaml:"port-whitelist" json:"port-whitelist"`
|
||||
ForceDnsMapping bool `yaml:"force-dns-mapping" json:"force-dns-mapping"`
|
||||
ParsePureIp bool `yaml:"parse-pure-ip" json:"parse-pure-ip"`
|
||||
Enable bool `yaml:"enable" json:"enable"`
|
||||
OverrideDest bool `yaml:"override-destination" json:"override-destination"`
|
||||
Sniffing []string `yaml:"sniffing" json:"sniffing"`
|
||||
ForceDomain []string `yaml:"force-domain" json:"force-domain"`
|
||||
SkipDomain []string `yaml:"skip-domain" json:"skip-domain"`
|
||||
Ports []string `yaml:"port-whitelist" json:"port-whitelist"`
|
||||
ForceDnsMapping bool `yaml:"force-dns-mapping" json:"force-dns-mapping"`
|
||||
ParsePureIp bool `yaml:"parse-pure-ip" json:"parse-pure-ip"`
|
||||
Sniff map[string]RawSniffingConfig `yaml:"sniff" json:"sniff"`
|
||||
}
|
||||
|
||||
type RawSniffingConfig struct {
|
||||
Ports []string `yaml:"ports" json:"ports"`
|
||||
OverrideDest *bool `yaml:"override-destination" json:"override-destination"`
|
||||
}
|
||||
|
||||
// EBpf config
|
||||
@ -331,7 +342,6 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
Proxy: []map[string]any{},
|
||||
ProxyGroup: []map[string]any{},
|
||||
TCPConcurrent: false,
|
||||
EnableProcess: false,
|
||||
FindProcessMode: P.FindProcessStrict,
|
||||
Tun: RawTun{
|
||||
Enable: false,
|
||||
@ -399,6 +409,7 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
||||
Ports: []string{},
|
||||
ForceDnsMapping: true,
|
||||
ParsePureIp: true,
|
||||
OverrideDest: true,
|
||||
},
|
||||
Profile: Profile{
|
||||
StoreSelected: true,
|
||||
@ -507,6 +518,11 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||
elapsedTime := time.Since(startTime) / time.Millisecond // duration in ms
|
||||
log.Infoln("Initial configuration complete, total time: %dms", elapsedTime) //Segment finished in xxm
|
||||
|
||||
if len(config.General.GlobalClientFingerprint) != 0 {
|
||||
log.Debugln("GlobalClientFingerprint:%s", config.General.GlobalClientFingerprint)
|
||||
tlsC.SetGlobalUtlsClient(config.General.GlobalClientFingerprint)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@ -540,18 +556,18 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||
Secret: cfg.Secret,
|
||||
ExternalControllerTLS: cfg.ExternalControllerTLS,
|
||||
},
|
||||
UnifiedDelay: cfg.UnifiedDelay,
|
||||
Mode: cfg.Mode,
|
||||
LogLevel: cfg.LogLevel,
|
||||
IPv6: cfg.IPv6,
|
||||
Interface: cfg.Interface,
|
||||
RoutingMark: cfg.RoutingMark,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
EnableProcess: cfg.EnableProcess,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
EBpf: cfg.EBpf,
|
||||
UnifiedDelay: cfg.UnifiedDelay,
|
||||
Mode: cfg.Mode,
|
||||
LogLevel: cfg.LogLevel,
|
||||
IPv6: cfg.IPv6,
|
||||
Interface: cfg.Interface,
|
||||
RoutingMark: cfg.RoutingMark,
|
||||
GeodataMode: cfg.GeodataMode,
|
||||
GeodataLoader: cfg.GeodataLoader,
|
||||
TCPConcurrent: cfg.TCPConcurrent,
|
||||
FindProcessMode: cfg.FindProcessMode,
|
||||
EBpf: cfg.EBpf,
|
||||
GlobalClientFingerprint: cfg.GlobalClientFingerprint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -831,17 +847,15 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie[netip.Addr], error) {
|
||||
}
|
||||
|
||||
func hostWithDefaultPort(host string, defPort string) (string, error) {
|
||||
if !strings.Contains(host, ":") {
|
||||
host += ":"
|
||||
}
|
||||
|
||||
hostname, port, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if port == "" {
|
||||
port = defPort
|
||||
if !strings.Contains(err.Error(), "missing port in address") {
|
||||
return "", err
|
||||
}
|
||||
host = host + ":" + defPort
|
||||
if hostname, port, err = net.SplitHostPort(host); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return net.JoinHostPort(hostname, port), nil
|
||||
@ -851,10 +865,7 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
||||
var nameservers []dns.NameServer
|
||||
|
||||
for idx, server := range servers {
|
||||
// parse without scheme .e.g 8.8.8.8:53
|
||||
if !strings.Contains(server, "://") {
|
||||
server = "udp://" + server
|
||||
}
|
||||
server = parsePureDNSServer(server)
|
||||
u, err := url.Parse(server)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||
@ -875,29 +886,24 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
||||
addr, err = hostWithDefaultPort(u.Host, "853")
|
||||
dnsNetType = "tcp-tls" // DNS over TLS
|
||||
case "https":
|
||||
host := u.Host
|
||||
proxyAdapter = ""
|
||||
if _, _, err := net.SplitHostPort(host); err != nil && strings.Contains(err.Error(), "missing port in address") {
|
||||
host = net.JoinHostPort(host, "443")
|
||||
} else {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
clearURL := url.URL{Scheme: "https", Host: host, Path: u.Path}
|
||||
addr = clearURL.String()
|
||||
dnsNetType = "https" // DNS over HTTPS
|
||||
if len(u.Fragment) != 0 {
|
||||
for _, s := range strings.Split(u.Fragment, "&") {
|
||||
arr := strings.Split(s, "=")
|
||||
if len(arr) == 0 {
|
||||
continue
|
||||
} else if len(arr) == 1 {
|
||||
proxyAdapter = arr[0]
|
||||
} else if len(arr) == 2 {
|
||||
params[arr[0]] = arr[1]
|
||||
} else {
|
||||
params[arr[0]] = strings.Join(arr[1:], "=")
|
||||
addr, err = hostWithDefaultPort(u.Host, "443")
|
||||
if err == nil {
|
||||
proxyAdapter = ""
|
||||
clearURL := url.URL{Scheme: "https", Host: addr, Path: u.Path}
|
||||
addr = clearURL.String()
|
||||
dnsNetType = "https" // DNS over HTTPS
|
||||
if len(u.Fragment) != 0 {
|
||||
for _, s := range strings.Split(u.Fragment, "&") {
|
||||
arr := strings.Split(s, "=")
|
||||
if len(arr) == 0 {
|
||||
continue
|
||||
} else if len(arr) == 1 {
|
||||
proxyAdapter = arr[0]
|
||||
} else if len(arr) == 2 {
|
||||
params[arr[0]] = arr[1]
|
||||
} else {
|
||||
params[arr[0]] = strings.Join(arr[1:], "=")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -930,18 +936,53 @@ func parseNameServer(servers []string, preferH3 bool) ([]dns.NameServer, error)
|
||||
return nameservers, nil
|
||||
}
|
||||
|
||||
func parseNameServerPolicy(nsPolicy map[string]string, preferH3 bool) (map[string]dns.NameServer, error) {
|
||||
policy := map[string]dns.NameServer{}
|
||||
func parsePureDNSServer(server string) string {
|
||||
addPre := func(server string) string {
|
||||
return "udp://" + server
|
||||
}
|
||||
|
||||
if ip, err := netip.ParseAddr(server); err != nil {
|
||||
if strings.Contains(server, "://") {
|
||||
return server
|
||||
}
|
||||
return addPre(server)
|
||||
} else {
|
||||
if ip.Is4() {
|
||||
return addPre(server)
|
||||
} else {
|
||||
return addPre("[" + server + "]")
|
||||
}
|
||||
}
|
||||
}
|
||||
func parseNameServerPolicy(nsPolicy map[string]any, preferH3 bool) (map[string][]dns.NameServer, error) {
|
||||
policy := map[string][]dns.NameServer{}
|
||||
|
||||
for domain, server := range nsPolicy {
|
||||
nameservers, err := parseNameServer([]string{server}, preferH3)
|
||||
var (
|
||||
nameservers []dns.NameServer
|
||||
err error
|
||||
)
|
||||
|
||||
switch reflect.TypeOf(server).Kind() {
|
||||
case reflect.Slice, reflect.Array:
|
||||
origin := reflect.ValueOf(server)
|
||||
servers := make([]string, 0)
|
||||
for i := 0; i < origin.Len(); i++ {
|
||||
servers = append(servers, fmt.Sprintf("%v", origin.Index(i)))
|
||||
}
|
||||
nameservers, err = parseNameServer(servers, preferH3)
|
||||
case reflect.String:
|
||||
nameservers, err = parseNameServer([]string{fmt.Sprintf("%v", server)}, preferH3)
|
||||
default:
|
||||
return nil, errors.New("server format error, must be string or array")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, valid := trie.ValidAndSplitDomain(domain); !valid {
|
||||
return nil, fmt.Errorf("DNS ResoverRule invalid domain: %s", domain)
|
||||
}
|
||||
policy[domain] = nameservers[0]
|
||||
policy[domain] = nameservers
|
||||
}
|
||||
|
||||
return policy, nil
|
||||
@ -967,6 +1008,7 @@ func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainM
|
||||
if err := geodata.InitGeoSite(); err != nil {
|
||||
return nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
||||
}
|
||||
log.Warnln("replace fallback-filter.geosite with nameserver-policy, it will be removed in the future")
|
||||
}
|
||||
|
||||
for _, country := range countries {
|
||||
@ -1185,55 +1227,60 @@ func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||
ForceDnsMapping: snifferRaw.ForceDnsMapping,
|
||||
ParsePureIp: snifferRaw.ParsePureIp,
|
||||
}
|
||||
loadSniffer := make(map[snifferTypes.Type]SNIFF.SnifferConfig)
|
||||
|
||||
var ports []utils.Range[uint16]
|
||||
if len(snifferRaw.Ports) == 0 {
|
||||
ports = append(ports, *utils.NewRange[uint16](80, 80))
|
||||
ports = append(ports, *utils.NewRange[uint16](443, 443))
|
||||
} else {
|
||||
for _, portRange := range snifferRaw.Ports {
|
||||
portRaws := strings.Split(portRange, "-")
|
||||
p, err := strconv.ParseUint(portRaws[0], 10, 16)
|
||||
if len(snifferRaw.Sniff) != 0 {
|
||||
for sniffType, sniffConfig := range snifferRaw.Sniff {
|
||||
find := false
|
||||
ports, err := parsePortRange(sniffConfig.Ports)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
start := uint16(p)
|
||||
if len(portRaws) > 1 {
|
||||
p, err = strconv.ParseUint(portRaws[1], 10, 16)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
overrideDest := snifferRaw.OverrideDest
|
||||
if sniffConfig.OverrideDest != nil {
|
||||
overrideDest = *sniffConfig.OverrideDest
|
||||
}
|
||||
for _, snifferType := range snifferTypes.List {
|
||||
if snifferType.String() == strings.ToUpper(sniffType) {
|
||||
find = true
|
||||
loadSniffer[snifferType] = SNIFF.SnifferConfig{
|
||||
Ports: ports,
|
||||
OverrideDest: overrideDest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
end := uint16(p)
|
||||
ports = append(ports, *utils.NewRange(start, end))
|
||||
} else {
|
||||
ports = append(ports, *utils.NewRange(start, start))
|
||||
if !find {
|
||||
return nil, fmt.Errorf("not find the sniffer[%s]", sniffType)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Deprecated: Use Sniff instead
|
||||
log.Warnln("Deprecated: Use Sniff instead")
|
||||
globalPorts, err := parsePortRange(snifferRaw.Ports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, snifferName := range snifferRaw.Sniffing {
|
||||
find := false
|
||||
for _, snifferType := range snifferTypes.List {
|
||||
if snifferType.String() == strings.ToUpper(snifferName) {
|
||||
find = true
|
||||
loadSniffer[snifferType] = SNIFF.SnifferConfig{
|
||||
Ports: globalPorts,
|
||||
OverrideDest: snifferRaw.OverrideDest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !find {
|
||||
return nil, fmt.Errorf("not find the sniffer[%s]", snifferName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sniffer.Ports = &ports
|
||||
|
||||
loadSniffer := make(map[snifferTypes.Type]struct{})
|
||||
|
||||
for _, snifferName := range snifferRaw.Sniffing {
|
||||
find := false
|
||||
for _, snifferType := range snifferTypes.List {
|
||||
if snifferType.String() == strings.ToUpper(snifferName) {
|
||||
find = true
|
||||
loadSniffer[snifferType] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if !find {
|
||||
return nil, fmt.Errorf("not find the sniffer[%s]", snifferName)
|
||||
}
|
||||
}
|
||||
|
||||
for st := range loadSniffer {
|
||||
sniffer.Sniffers = append(sniffer.Sniffers, st)
|
||||
}
|
||||
sniffer.Sniffers = loadSniffer
|
||||
sniffer.ForceDomain = trie.New[struct{}]()
|
||||
for _, domain := range snifferRaw.ForceDomain {
|
||||
err := sniffer.ForceDomain.Insert(domain, struct{}{})
|
||||
@ -1254,3 +1301,28 @@ func parseSniffer(snifferRaw RawSniffer) (*Sniffer, error) {
|
||||
|
||||
return sniffer, nil
|
||||
}
|
||||
|
||||
func parsePortRange(portRanges []string) ([]utils.Range[uint16], error) {
|
||||
ports := make([]utils.Range[uint16], 0)
|
||||
for _, portRange := range portRanges {
|
||||
portRaws := strings.Split(portRange, "-")
|
||||
p, err := strconv.ParseUint(portRaws[0], 10, 16)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
}
|
||||
|
||||
start := uint16(p)
|
||||
if len(portRaws) > 1 {
|
||||
p, err = strconv.ParseUint(portRaws[1], 10, 16)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s format error", portRange)
|
||||
}
|
||||
|
||||
end := uint16(p)
|
||||
ports = append(ports, *utils.NewRange(start, end))
|
||||
} else {
|
||||
ports = append(ports, *utils.NewRange(start, start))
|
||||
}
|
||||
}
|
||||
return ports, nil
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
@ -92,6 +93,7 @@ type ProxyAdapter interface {
|
||||
Type() AdapterType
|
||||
Addr() string
|
||||
SupportUDP() bool
|
||||
SupportXUDP() bool
|
||||
SupportTFO() bool
|
||||
MarshalJSON() ([]byte, error)
|
||||
|
||||
@ -226,3 +228,23 @@ type PacketAdapter interface {
|
||||
UDPPacket
|
||||
Metadata() *Metadata
|
||||
}
|
||||
|
||||
type NatTable interface {
|
||||
Set(key string, e PacketConn)
|
||||
|
||||
Get(key string) PacketConn
|
||||
|
||||
GetOrCreateLock(key string) (*sync.Cond, bool)
|
||||
|
||||
Delete(key string)
|
||||
|
||||
GetLocalConn(lAddr, rAddr string) *net.UDPConn
|
||||
|
||||
AddLocalConn(lAddr, rAddr string, conn *net.UDPConn) bool
|
||||
|
||||
RangeLocalConn(lAddr string, f func(key, value any) bool)
|
||||
|
||||
GetOrCreateLockForLocalConn(lAddr, key string) (*sync.Cond, bool)
|
||||
|
||||
DeleteLocalConnMap(lAddr, key string)
|
||||
}
|
||||
|
@ -3,6 +3,8 @@ package constant
|
||||
import (
|
||||
"net"
|
||||
|
||||
N "github.com/Dreamacro/clash/common/net"
|
||||
|
||||
"github.com/gofrs/uuid"
|
||||
)
|
||||
|
||||
@ -13,7 +15,7 @@ type PlainContext interface {
|
||||
type ConnContext interface {
|
||||
PlainContext
|
||||
Metadata() *Metadata
|
||||
Conn() net.Conn
|
||||
Conn() *N.BufferedConn
|
||||
}
|
||||
|
||||
type PacketConnContext interface {
|
||||
|
@ -124,4 +124,4 @@ const (
|
||||
HTTPVersion2 HTTPVersion = "h2"
|
||||
// HTTPVersion3 is HTTP/3.
|
||||
HTTPVersion3 HTTPVersion = "h3"
|
||||
)
|
||||
)
|
||||
|
@ -16,7 +16,7 @@ type MultiAddrListener interface {
|
||||
|
||||
type InboundListener interface {
|
||||
Name() string
|
||||
Listen(tcpIn chan<- ConnContext, udpIn chan<- PacketAdapter) error
|
||||
Listen(tcpIn chan<- ConnContext, udpIn chan<- PacketAdapter, natTable NatTable) error
|
||||
Close() error
|
||||
Address() string
|
||||
RawAddress() string
|
||||
|
@ -128,12 +128,14 @@ type Metadata struct {
|
||||
InName string `json:"inboundName"`
|
||||
Host string `json:"host"`
|
||||
DNSMode DNSMode `json:"dnsMode"`
|
||||
Uid *uint32 `json:"uid"`
|
||||
Uid uint32 `json:"uid"`
|
||||
Process string `json:"process"`
|
||||
ProcessPath string `json:"processPath"`
|
||||
SpecialProxy string `json:"specialProxy"`
|
||||
SpecialRules string `json:"specialRules"`
|
||||
RemoteDst string `json:"remoteDestination"`
|
||||
// Only domain rule
|
||||
SniffHost string `json:"sniffHost"`
|
||||
}
|
||||
|
||||
func (m *Metadata) RemoteAddress() string {
|
||||
@ -146,16 +148,17 @@ func (m *Metadata) SourceAddress() string {
|
||||
|
||||
func (m *Metadata) SourceDetail() string {
|
||||
if m.Type == INNER {
|
||||
return fmt.Sprintf("[%s]", ClashName)
|
||||
return fmt.Sprintf("%s", ClashName)
|
||||
}
|
||||
|
||||
if m.Process != "" && m.Uid != nil {
|
||||
return fmt.Sprintf("%s(%s, uid=%d)", m.SourceAddress(), m.Process, *m.Uid)
|
||||
} else if m.Uid != nil {
|
||||
return fmt.Sprintf("%s(uid=%d)", m.SourceAddress(), *m.Uid)
|
||||
} else if m.Process != "" {
|
||||
switch {
|
||||
case m.Process != "" && m.Uid != 0:
|
||||
return fmt.Sprintf("%s(%s, uid=%d)", m.SourceAddress(), m.Process, m.Uid)
|
||||
case m.Uid != 0:
|
||||
return fmt.Sprintf("%s(uid=%d)", m.SourceAddress(), m.Uid)
|
||||
case m.Process != "":
|
||||
return fmt.Sprintf("%s(%s)", m.SourceAddress(), m.Process)
|
||||
} else {
|
||||
default:
|
||||
return fmt.Sprintf("%s", m.SourceAddress())
|
||||
}
|
||||
}
|
||||
@ -175,6 +178,14 @@ func (m *Metadata) Resolved() bool {
|
||||
return m.DstIP.IsValid()
|
||||
}
|
||||
|
||||
func (m *Metadata) RuleHost() string {
|
||||
if len(m.SniffHost) == 0 {
|
||||
return m.Host
|
||||
} else {
|
||||
return m.SniffHost
|
||||
}
|
||||
}
|
||||
|
||||
// Pure is used to solve unexpected behavior
|
||||
// when dialing proxy connection in DNSMapping mode.
|
||||
func (m *Metadata) Pure() *Metadata {
|
||||
|
@ -102,5 +102,6 @@ type RuleProvider interface {
|
||||
Behavior() RuleType
|
||||
Match(*constant.Metadata) bool
|
||||
ShouldResolveIP() bool
|
||||
ShouldFindProcess() bool
|
||||
AsRule(adaptor string) constant.Rule
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ type Sniffer interface {
|
||||
SupportNetwork() constant.NetWork
|
||||
SniffTCP(bytes []byte) (string, error)
|
||||
Protocol() string
|
||||
SupportPort(port uint16) bool
|
||||
}
|
||||
|
||||
const (
|
||||
|
@ -4,5 +4,5 @@ var (
|
||||
Meta = true
|
||||
Version = "1.10.0"
|
||||
BuildTime = "unknown time"
|
||||
ClashName = "Clash.Meta"
|
||||
ClashName = "clash.meta"
|
||||
)
|
||||
|
@ -12,7 +12,7 @@ import (
|
||||
type ConnContext struct {
|
||||
id uuid.UUID
|
||||
metadata *C.Metadata
|
||||
conn net.Conn
|
||||
conn *N.BufferedConn
|
||||
}
|
||||
|
||||
func NewConnContext(conn net.Conn, metadata *C.Metadata) *ConnContext {
|
||||
@ -36,6 +36,6 @@ func (c *ConnContext) Metadata() *C.Metadata {
|
||||
}
|
||||
|
||||
// Conn implement C.ConnContext Conn
|
||||
func (c *ConnContext) Conn() net.Conn {
|
||||
func (c *ConnContext) Conn() *N.BufferedConn {
|
||||
return c.conn
|
||||
}
|
||||
|
@ -4,13 +4,14 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
"go.uber.org/atomic"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||
"go.uber.org/atomic"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dialer"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
|
||||
@ -24,6 +25,26 @@ type client struct {
|
||||
host string
|
||||
iface *atomic.String
|
||||
proxyAdapter string
|
||||
addr string
|
||||
}
|
||||
|
||||
var _ dnsClient = (*client)(nil)
|
||||
|
||||
// Address implements dnsClient
|
||||
func (c *client) Address() string {
|
||||
if len(c.addr) != 0 {
|
||||
return c.addr
|
||||
}
|
||||
schema := "udp"
|
||||
if strings.HasPrefix(c.Client.Net, "tcp") {
|
||||
schema = "tcp"
|
||||
if strings.HasSuffix(c.Client.Net, "tls") {
|
||||
schema = "tls"
|
||||
}
|
||||
}
|
||||
|
||||
c.addr = fmt.Sprintf("%s://%s", schema, net.JoinHostPort(c.host, c.port))
|
||||
return c.addr
|
||||
}
|
||||
|
||||
func (c *client) Exchange(m *D.Msg) (*D.Msg, error) {
|
||||
@ -77,7 +98,7 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
|
||||
ch := make(chan result, 1)
|
||||
go func() {
|
||||
if strings.HasSuffix(c.Client.Net, "tls") {
|
||||
conn = tls.Client(conn, tlsC.GetGlobalFingerprintTLCConfig(c.Client.TLSConfig))
|
||||
conn = tls.Client(conn, tlsC.GetGlobalTLSConfig(c.Client.TLSConfig))
|
||||
}
|
||||
|
||||
msg, _, err := c.Client.ExchangeWithConn(m, &D.Conn{
|
||||
|
15
dns/dhcp.go
15
dns/dhcp.go
@ -2,12 +2,14 @@ package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.uber.org/atomic"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
|
||||
"github.com/Dreamacro/clash/component/dhcp"
|
||||
"github.com/Dreamacro/clash/component/iface"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
@ -34,6 +36,17 @@ type dhcpClient struct {
|
||||
err error
|
||||
}
|
||||
|
||||
var _ dnsClient = (*dhcpClient)(nil)
|
||||
|
||||
// Address implements dnsClient
|
||||
func (d *dhcpClient) Address() string {
|
||||
addrs := make([]string, 0)
|
||||
for _, c := range d.clients {
|
||||
addrs = append(addrs, c.Address())
|
||||
}
|
||||
return strings.Join(addrs, ",")
|
||||
}
|
||||
|
||||
func (d *dhcpClient) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), resolver.DefaultDNSTimeout)
|
||||
defer cancel()
|
||||
|
@ -64,6 +64,7 @@ type dnsOverHTTPS struct {
|
||||
r *Resolver
|
||||
httpVersions []C.HTTPVersion
|
||||
proxyAdapter string
|
||||
addr string
|
||||
}
|
||||
|
||||
// type check
|
||||
@ -83,6 +84,7 @@ func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[strin
|
||||
|
||||
doh := &dnsOverHTTPS{
|
||||
url: u,
|
||||
addr: u.String(),
|
||||
r: r,
|
||||
proxyAdapter: proxyAdapter,
|
||||
quicConfig: &quic.Config{
|
||||
@ -98,13 +100,16 @@ func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[strin
|
||||
}
|
||||
|
||||
// Address implements the Upstream interface for *dnsOverHTTPS.
|
||||
func (doh *dnsOverHTTPS) Address() string { return doh.url.String() }
|
||||
func (doh *dnsOverHTTPS) Address() string {
|
||||
return doh.addr
|
||||
}
|
||||
func (doh *dnsOverHTTPS) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||
// Quote from https://www.rfc-editor.org/rfc/rfc8484.html:
|
||||
// In order to maximize HTTP cache friendliness, DoH clients using media
|
||||
// formats that include the ID field from the DNS message header, such
|
||||
// as "application/dns-message", SHOULD use a DNS ID of 0 in every DNS
|
||||
// request.
|
||||
m = m.Copy()
|
||||
id := m.Id
|
||||
m.Id = 0
|
||||
defer func() {
|
||||
@ -374,7 +379,7 @@ func (doh *dnsOverHTTPS) createClient(ctx context.Context) (*http.Client, error)
|
||||
// HTTP3 is enabled in the upstream options). If this attempt is successful,
|
||||
// it returns an HTTP3 transport, otherwise it returns the H1/H2 transport.
|
||||
func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripper, err error) {
|
||||
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(
|
||||
tlsConfig := tlsC.GetGlobalTLSConfig(
|
||||
&tls.Config{
|
||||
InsecureSkipVerify: false,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
|
@ -89,6 +89,7 @@ func (doq *dnsOverQUIC) Address() string { return doq.addr }
|
||||
func (doq *dnsOverQUIC) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
||||
// When sending queries over a QUIC connection, the DNS Message ID MUST be
|
||||
// set to zero.
|
||||
m = m.Copy()
|
||||
id := m.Id
|
||||
m.Id = 0
|
||||
defer func() {
|
||||
@ -298,7 +299,7 @@ func (doq *dnsOverQUIC) openStream(ctx context.Context, conn quic.Connection) (q
|
||||
|
||||
// openConnection opens a new QUIC connection.
|
||||
func (doq *dnsOverQUIC) openConnection(ctx context.Context) (conn quic.Connection, err error) {
|
||||
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(
|
||||
tlsConfig := tlsC.GetGlobalTLSConfig(
|
||||
&tls.Config{
|
||||
InsecureSkipVerify: false,
|
||||
NextProtos: []string{
|
||||
|
@ -109,7 +109,7 @@ func NewEnhancer(cfg Config) *ResolverEnhancer {
|
||||
|
||||
if cfg.EnhancedMode != C.DNSNormal {
|
||||
fakePool = cfg.Pool
|
||||
mapping = cache.New[netip.Addr, string](cache.WithSize[netip.Addr, string](4096), cache.WithStale[netip.Addr, string](true))
|
||||
mapping = cache.New(cache.WithSize[netip.Addr, string](4096), cache.WithStale[netip.Addr, string](true))
|
||||
}
|
||||
|
||||
return &ResolverEnhancer{
|
||||
|
@ -91,6 +91,17 @@ type geoSiteFilter struct {
|
||||
matchers []*router.DomainMatcher
|
||||
}
|
||||
|
||||
func NewGeoSite(group string) (fallbackDomainFilter, error) {
|
||||
matcher, _, err := geodata.LoadGeoSiteMatcher(group)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter := &geoSiteFilter{
|
||||
matchers: []*router.DomainMatcher{matcher},
|
||||
}
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
func (gsf *geoSiteFilter) Match(domain string) bool {
|
||||
for _, matcher := range gsf.matchers {
|
||||
if matcher.ApplyDomain(domain) {
|
||||
|
@ -164,7 +164,6 @@ func withResolver(resolver *Resolver) handler {
|
||||
msg.SetRcode(r, msg.Rcode)
|
||||
msg.Authoritative = true
|
||||
|
||||
log.Debugln("[DNS] %s --> %s", msgToDomain(r), msgToIP(msg))
|
||||
return msg, nil
|
||||
}
|
||||
}
|
||||
|
@ -4,17 +4,20 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go.uber.org/atomic"
|
||||
"math/rand"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
|
||||
"github.com/Dreamacro/clash/common/cache"
|
||||
"github.com/Dreamacro/clash/component/fakeip"
|
||||
"github.com/Dreamacro/clash/component/geodata/router"
|
||||
"github.com/Dreamacro/clash/component/resolver"
|
||||
"github.com/Dreamacro/clash/component/trie"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
"golang.org/x/sync/singleflight"
|
||||
@ -23,6 +26,7 @@ import (
|
||||
type dnsClient interface {
|
||||
Exchange(m *D.Msg) (msg *D.Msg, err error)
|
||||
ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error)
|
||||
Address() string
|
||||
}
|
||||
|
||||
type result struct {
|
||||
@ -30,6 +34,12 @@ type result struct {
|
||||
Error error
|
||||
}
|
||||
|
||||
type geositePolicyRecord struct {
|
||||
matcher fallbackDomainFilter
|
||||
policy *Policy
|
||||
inversedMatching bool
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
ipv6 bool
|
||||
hosts *trie.DomainTrie[netip.Addr]
|
||||
@ -40,6 +50,7 @@ type Resolver struct {
|
||||
group singleflight.Group
|
||||
lruCache *cache.LruCache[string, *D.Msg]
|
||||
policy *trie.DomainTrie[*Policy]
|
||||
geositePolicy []geositePolicyRecord
|
||||
proxyServer []dnsClient
|
||||
}
|
||||
|
||||
@ -272,12 +283,18 @@ func (r *Resolver) matchPolicy(m *D.Msg) []dnsClient {
|
||||
}
|
||||
|
||||
record := r.policy.Search(domain)
|
||||
if record == nil {
|
||||
return nil
|
||||
if record != nil {
|
||||
p := record.Data()
|
||||
return p.GetData()
|
||||
}
|
||||
|
||||
p := record.Data()
|
||||
return p.GetData()
|
||||
for _, geositeRecord := range r.geositePolicy {
|
||||
matched := geositeRecord.matcher.Match(domain)
|
||||
if matched != geositeRecord.inversedMatching {
|
||||
return geositeRecord.policy.GetData()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Resolver) shouldOnlyQueryFallback(m *D.Msg) bool {
|
||||
@ -406,19 +423,19 @@ type Config struct {
|
||||
FallbackFilter FallbackFilter
|
||||
Pool *fakeip.Pool
|
||||
Hosts *trie.DomainTrie[netip.Addr]
|
||||
Policy map[string]NameServer
|
||||
Policy map[string][]NameServer
|
||||
}
|
||||
|
||||
func NewResolver(config Config) *Resolver {
|
||||
defaultResolver := &Resolver{
|
||||
main: transform(config.Default, nil),
|
||||
lruCache: cache.New[string, *D.Msg](cache.WithSize[string, *D.Msg](4096), cache.WithStale[string, *D.Msg](true)),
|
||||
lruCache: cache.New(cache.WithSize[string, *D.Msg](4096), cache.WithStale[string, *D.Msg](true)),
|
||||
}
|
||||
|
||||
r := &Resolver{
|
||||
ipv6: config.IPv6,
|
||||
main: transform(config.Main, defaultResolver),
|
||||
lruCache: cache.New[string, *D.Msg](cache.WithSize[string, *D.Msg](4096), cache.WithStale[string, *D.Msg](true)),
|
||||
lruCache: cache.New(cache.WithSize[string, *D.Msg](4096), cache.WithStale[string, *D.Msg](true)),
|
||||
hosts: config.Hosts,
|
||||
}
|
||||
|
||||
@ -433,7 +450,26 @@ func NewResolver(config Config) *Resolver {
|
||||
if len(config.Policy) != 0 {
|
||||
r.policy = trie.New[*Policy]()
|
||||
for domain, nameserver := range config.Policy {
|
||||
_ = r.policy.Insert(domain, NewPolicy(transform([]NameServer{nameserver}, defaultResolver)))
|
||||
if strings.HasPrefix(strings.ToLower(domain), "geosite:") {
|
||||
groupname := domain[8:]
|
||||
inverse := false
|
||||
if strings.HasPrefix(groupname, "!") {
|
||||
inverse = true
|
||||
groupname = groupname[1:]
|
||||
}
|
||||
log.Debugln("adding geosite policy: %s inversed %t", groupname, inverse)
|
||||
matcher, err := NewGeoSite(groupname)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.geositePolicy = append(r.geositePolicy, geositePolicyRecord{
|
||||
matcher: matcher,
|
||||
policy: NewPolicy(transform(nameserver, defaultResolver)),
|
||||
inversedMatching: inverse,
|
||||
})
|
||||
} else {
|
||||
_ = r.policy.Insert(domain, NewPolicy(transform(nameserver, defaultResolver)))
|
||||
}
|
||||
}
|
||||
r.policy.Optimize()
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user