Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
5987f8e3b5 | |||
3a8eb72de2 | |||
33abbdfd24 | |||
0703d6cbff | |||
10d2d14938 | |||
691cf1d8d6 | |||
d1decb8e58 | |||
7d04904109 | |||
a5acd3aa97 | |||
eea9a12560 | |||
0a4570b55c |
26
.github/release.sh
vendored
26
.github/release.sh
vendored
@ -1,26 +0,0 @@
|
|||||||
#!/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
26
.github/rename-cgo.sh
vendored
@ -1,26 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
FILENAMES=$(ls)
|
|
||||||
for FILENAME in $FILENAMES
|
|
||||||
do
|
|
||||||
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
|
||||||
echo "rename darwin-10.16-arm64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-darwin-arm64-cgo
|
|
||||||
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
|
||||||
echo "rename darwin-10.16-amd64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-darwin-amd64-cgo
|
|
||||||
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
|
||||||
echo "rename windows 386 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-windows-386-cgo.exe
|
|
||||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
|
||||||
echo "rename windows amd64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
|
||||||
elif [[ $FILENAME =~ "linux" ]];then
|
|
||||||
echo "rename linux $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
elif [[ $FILENAME =~ "android" ]];then
|
|
||||||
echo "rename android $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
else echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
20
.github/workflows/build.yaml
vendored
Normal file
20
.github/workflows/build.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
name: Build All
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v1
|
||||||
|
with:
|
||||||
|
go-version: 1.18
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v1
|
||||||
|
- name: Build
|
||||||
|
run: make all
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
357
.github/workflows/build.yml
vendored
357
.github/workflows/build.yml
vendored
@ -1,357 +0,0 @@
|
|||||||
name: Build
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
paths-ignore:
|
|
||||||
- "docs/**"
|
|
||||||
- "README.md"
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
- Meta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
- Meta
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.ref }}-${{ github.workflow }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
permissions: write-all
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
job:
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-amd64 linux-amd64-compatible",
|
|
||||||
id: "1",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
|
||||||
id: "2",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
|
||||||
id: "3",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
|
||||||
id: "4",
|
|
||||||
}
|
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
|
||||||
id: "6",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
|
||||||
id: "7",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-arm64 windows-arm32v7",
|
|
||||||
id: "8",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
|
||||||
id: "9",
|
|
||||||
}
|
|
||||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
|
||||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
|
||||||
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
|
||||||
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
|
||||||
- { type: "WithCGO", target: "android", id: "11" }
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Meta'}}
|
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
|
||||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
|
||||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
|
||||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
|
||||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
|
||||||
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: "1.20"
|
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{ matrix.job.id=='1' && matrix.job.type=='WithoutCGO' }}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build WithoutCGO
|
|
||||||
if: ${{ matrix.job.type=='WithoutCGO' }}
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
|
||||||
|
|
||||||
- uses: nttld/setup-ndk@v1
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
|
||||||
id: setup-ndk
|
|
||||||
with:
|
|
||||||
ndk-version: r25b
|
|
||||||
add-to-path: false
|
|
||||||
local-cache: true
|
|
||||||
|
|
||||||
- name: Build Android
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
|
||||||
env:
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
run: |
|
|
||||||
mkdir bin
|
|
||||||
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
|
||||||
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
|
||||||
|
|
||||||
- name: Set up xgo
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
|
||||||
run: |
|
|
||||||
docker pull techknowlogick/xgo:latest
|
|
||||||
go install src.techknowlogick.com/xgo@latest
|
|
||||||
|
|
||||||
- name: Build by xgo
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
|
||||||
env:
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
run: |
|
|
||||||
mkdir bin
|
|
||||||
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
|
||||||
|
|
||||||
- name: Rename
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' }}
|
|
||||||
run: |
|
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
cp ../.github/rename-cgo.sh ./
|
|
||||||
bash ./rename-cgo.sh
|
|
||||||
rm ./rename-cgo.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Zip
|
|
||||||
if: ${{ success() }}
|
|
||||||
run: |
|
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
chmod +x *
|
|
||||||
cp ../.github/release.sh ./
|
|
||||||
bash ./release.sh
|
|
||||||
rm ./release.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Save version
|
|
||||||
run: echo ${VERSION} > bin/version.txt
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
Upload-Prerelease:
|
|
||||||
permissions: write-all
|
|
||||||
if: ${{ github.ref_type=='branch' }}
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Set Env
|
|
||||||
run: |
|
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- run: |
|
|
||||||
cat > release.txt << 'EOF'
|
|
||||||
Release created at ${{ env.BUILDTIME }}
|
|
||||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
|
||||||
<br>
|
|
||||||
### release version
|
|
||||||
`default(not specified in file name)`: compiled with GOAMD64=v3
|
|
||||||
`cgo`: support lwip tun stack, compiled with GOAMD64=v1
|
|
||||||
`compatible`: compiled with GOAMD64=v1
|
|
||||||
Check details between different architectural levels [here](https://github.com/golang/go/wiki/MinimumRequirements#amd64).
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref_name }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
|
||||||
bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
Upload-Release:
|
|
||||||
permissions: write-all
|
|
||||||
if: ${{ github.ref_type=='tag' }}
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref_name }}
|
|
||||||
tag_name: ${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
Docker:
|
|
||||||
permissions: write-all
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
- name: Show files
|
|
||||||
run: |
|
|
||||||
ls .
|
|
||||||
ls bin/
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
linux/arm/v7
|
|
||||||
# linux/riscv64
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
61
.github/workflows/docker.yaml
vendored
Normal file
61
.github/workflows/docker.yaml
vendored
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
name: Docker
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Beta
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v1
|
||||||
|
|
||||||
|
- name: Setup Docker buildx
|
||||||
|
uses: docker/setup-buildx-action@v1
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v3
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||||
|
|
||||||
|
- name: Log into registry
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@v1
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
|
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: docker/build-push-action@v2
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64/v8
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
70
.github/workflows/prerelease.yml
vendored
Normal file
70
.github/workflows/prerelease.yml
vendored
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
name: Prerelease
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
if: ${{github.ref_name=='Beta'}}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload Alpha
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref_name }}
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
44
.github/workflows/release.yaml
vendored
Normal file
44
.github/workflows/release.yaml
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
name: Release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref }}
|
||||||
|
files: bin/*
|
||||||
|
generate_release_notes: true
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -24,5 +24,4 @@ vendor
|
|||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
/output
|
||||||
.vscode/
|
/.vscode
|
||||||
.fleet/
|
|
@ -8,10 +8,9 @@ linters:
|
|||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
gci:
|
gci:
|
||||||
custom-order: true
|
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/Dreamacro/clash)
|
- prefix(github.com/Dreamacro/clash)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.19'
|
go: '1.18'
|
||||||
|
25
Dockerfile
25
Dockerfile
@ -1,27 +1,26 @@
|
|||||||
FROM alpine:latest as builder
|
FROM golang:alpine as builder
|
||||||
ARG TARGETPLATFORM
|
|
||||||
RUN echo "I'm building for $TARGETPLATFORM"
|
|
||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache make git && \
|
||||||
mkdir /clash-config && \
|
mkdir /clash-config && \
|
||||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
|
|
||||||
COPY docker/file-name.sh /clash/file-name.sh
|
|
||||||
WORKDIR /clash
|
COPY . /clash-src
|
||||||
COPY bin/ bin/
|
WORKDIR /clash-src
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
RUN go mod download &&\
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
make docker &&\
|
||||||
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
mv ./bin/Clash.Meta-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata iptables
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
|
|
||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
COPY --from=builder /clash/clash /clash
|
COPY --from=builder /clash /clash
|
||||||
RUN chmod +x /clash
|
RUN chmod +x /clash
|
||||||
ENTRYPOINT [ "/clash" ]
|
ENTRYPOINT [ "/clash" ]
|
20
Makefile
20
Makefile
@ -1,4 +1,4 @@
|
|||||||
NAME=clash.meta
|
NAME=Clash.Meta
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
@ -12,7 +12,7 @@ VERSION=$(shell git rev-parse --short HEAD)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
@ -47,17 +47,14 @@ all:linux-amd64 linux-arm64\
|
|||||||
darwin-amd64 darwin-arm64\
|
darwin-amd64 darwin-arm64\
|
||||||
windows-amd64 windows-arm64\
|
windows-amd64 windows-arm64\
|
||||||
|
|
||||||
|
|
||||||
darwin-all: darwin-amd64 darwin-arm64
|
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64-compatible:
|
darwin-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -69,7 +66,7 @@ linux-amd64:
|
|||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64-compatible:
|
linux-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -101,9 +98,6 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-riscv64:
|
|
||||||
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
android-arm64:
|
android-arm64:
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -123,7 +117,7 @@ windows-amd64:
|
|||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64-compatible:
|
windows-amd64-compatible:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
@ -160,4 +154,4 @@ CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
|||||||
ebpf: export BPF_CLANG := $(CLANG)
|
ebpf: export BPF_CLANG := $(CLANG)
|
||||||
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||||
ebpf:
|
ebpf:
|
||||||
cd component/ebpf/ && go generate ./...
|
cd component/ebpf/ && go generate ./...
|
152
README.md
152
README.md
@ -29,42 +29,12 @@
|
|||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Wiki
|
## Getting Started
|
||||||
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
Documentation and configuring examples are available on [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki) and [Clash.Meta Wiki](https://docs.metacubex.one/).
|
## Advanced usage for this branch
|
||||||
|
|
||||||
## Build
|
### DNS configuration
|
||||||
|
|
||||||
You should install [golang](https://go.dev) first.
|
|
||||||
|
|
||||||
Then get the source code of Clash.Meta:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
|
||||||
cd Clash.Meta && go mod download
|
|
||||||
```
|
|
||||||
|
|
||||||
If you can't visit github,you should set proxy first:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
|
||||||
```
|
|
||||||
|
|
||||||
Now you can build it:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
go build
|
|
||||||
```
|
|
||||||
|
|
||||||
If you need gvisor for tun stack, build with:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
go build -tags with_gvisor
|
|
||||||
```
|
|
||||||
|
|
||||||
<!-- ## Advanced usage of this fork -->
|
|
||||||
|
|
||||||
<!-- ### DNS configuration
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
@ -74,6 +44,7 @@ Support resolve ip with a `Proxy Tunnel`.
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: DNS
|
- name: DNS
|
||||||
type: url-test
|
type: url-test
|
||||||
use:
|
use:
|
||||||
@ -82,7 +53,6 @@ proxy-groups:
|
|||||||
interval: 180
|
interval: 180
|
||||||
lazy: true
|
lazy: true
|
||||||
```
|
```
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
@ -98,12 +68,12 @@ dns:
|
|||||||
- https://doh.pub/dns-query
|
- https://doh.pub/dns-query
|
||||||
- tls://223.5.5.5:853
|
- tls://223.5.5.5:853
|
||||||
fallback:
|
fallback:
|
||||||
- "https://1.0.0.1/dns-query#DNS" # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
||||||
- "tls://8.8.4.4:853#DNS"
|
- 'tls://8.8.4.4:853#DNS'
|
||||||
fallback-filter:
|
fallback-filter:
|
||||||
geoip: false
|
geoip: false
|
||||||
geosite:
|
geosite:
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
||||||
domain:
|
domain:
|
||||||
- +.example.com
|
- +.example.com
|
||||||
ipcidr:
|
ipcidr:
|
||||||
@ -120,30 +90,28 @@ Built-in [Wintun](https://www.wintun.net) driver.
|
|||||||
# Enable the TUN listener
|
# Enable the TUN listener
|
||||||
tun:
|
tun:
|
||||||
enable: true
|
enable: true
|
||||||
stack: system # system/gvisor
|
stack: gvisor # only gvisor
|
||||||
dns-hijack:
|
dns-hijack:
|
||||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||||
auto-route: true # auto set global route
|
auto-route: true # auto set global route
|
||||||
```
|
```
|
||||||
|
|
||||||
### Rules configuration
|
### Rules configuration
|
||||||
|
|
||||||
- Support rule `GEOSITE`.
|
- Support rule `GEOSITE`.
|
||||||
- Support rule-providers `RULE-SET`.
|
- Support rule-providers `RULE-SET`.
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
- Support `network` condition for all rules.
|
- Support `network` condition for all rules.
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
rules:
|
rules:
|
||||||
|
|
||||||
# network(tcp/udp) condition for all rules
|
# network(tcp/udp) condition for all rules
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
# rule GEOSITE
|
# rule GEOSITE
|
||||||
- GEOSITE,category-ads-all,REJECT
|
- GEOSITE,category-ads-all,REJECT
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
@ -154,17 +122,18 @@ rules:
|
|||||||
- GEOSITE,youtube,PROXY
|
- GEOSITE,youtube,PROXY
|
||||||
- GEOSITE,geolocation-cn,DIRECT
|
- GEOSITE,geolocation-cn,DIRECT
|
||||||
- GEOSITE,geolocation-!cn,PROXY
|
- GEOSITE,geolocation-!cn,PROXY
|
||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
- GEOIP,private,DIRECT,no-resolve
|
- GEOIP,private,DIRECT,no-resolve
|
||||||
- GEOIP,cn,DIRECT
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Proxies configuration
|
### Proxies configuration
|
||||||
|
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||||
@ -173,17 +142,18 @@ Support `Policy Group Filter`
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
|
|
||||||
- name: 🚀 HK Group
|
- name: 🚀 HK Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: "HK"
|
filter: 'HK'
|
||||||
|
|
||||||
- name: 🚀 US Group
|
- name: 🚀 US Group
|
||||||
type: select
|
type: select
|
||||||
use:
|
use:
|
||||||
- ALL
|
- ALL
|
||||||
filter: "US"
|
filter: 'US'
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
ALL:
|
ALL:
|
||||||
@ -195,12 +165,14 @@ proxy-providers:
|
|||||||
enable: true
|
enable: true
|
||||||
interval: 600
|
interval: 600
|
||||||
url: http://www.gstatic.com/generate_204
|
url: http://www.gstatic.com/generate_204
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
Support outbound transport protocol `VLESS`.
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "vless"
|
- name: "vless"
|
||||||
@ -211,7 +183,7 @@ proxies:
|
|||||||
servername: example.com # AKA SNI
|
servername: example.com # AKA SNI
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
|
|
||||||
- name: "vless-ws"
|
- name: "vless-ws"
|
||||||
type: vless
|
type: vless
|
||||||
server: server
|
server: server
|
||||||
@ -236,50 +208,12 @@ proxies:
|
|||||||
network: grpc
|
network: grpc
|
||||||
servername: example.com # priority over wss host
|
servername: example.com # priority over wss host
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
grpc-opts:
|
grpc-opts:
|
||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `Wireguard`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "wg"
|
|
||||||
type: wireguard
|
|
||||||
server: 162.159.192.1
|
|
||||||
port: 2480
|
|
||||||
ip: 172.16.0.2
|
|
||||||
ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
|
||||||
private-key: eCtXsJZ27+4PbhDkHnB923tkUn2Gj59wZw5wFA75MnU=
|
|
||||||
public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
|
||||||
udp: true
|
|
||||||
```
|
|
||||||
|
|
||||||
Support outbound transport protocol `Tuic`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "tuic"
|
|
||||||
server: www.example.com
|
|
||||||
port: 10443
|
|
||||||
type: tuic
|
|
||||||
token: TOKEN
|
|
||||||
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
|
||||||
# heartbeat-interval: 10000
|
|
||||||
# alpn: [h3]
|
|
||||||
# disable-sni: true
|
|
||||||
reduce-rtt: true
|
|
||||||
# request-timeout: 8000
|
|
||||||
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
|
||||||
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
|
||||||
# max-udp-relay-packet-size: 1500
|
|
||||||
# fast-open: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
``` -->
|
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
|
Work on Linux OS who's supported `iptables`
|
||||||
Work on Linux OS which supported `iptables`
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@ -290,15 +224,17 @@ iptables:
|
|||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
|
||||||
### General installation guide for Linux
|
|
||||||
|
|
||||||
- Create user given name `clash-meta`
|
### General installation guide for Linux
|
||||||
|
+ Create user given name `clash-meta`
|
||||||
|
|
||||||
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
|
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||||
|
|
||||||
|
+ Create folder `/etc/Clash-Meta/` as working directory
|
||||||
|
|
||||||
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
|
||||||
|
|
||||||
- Create folder `/etc/Clash-Meta/` as working directory
|
|
||||||
|
|
||||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||||
|
|
||||||
@ -324,13 +260,10 @@ ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ systemctl enable Clash-Meta
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
@ -341,29 +274,22 @@ $ systemctl start Clash-Meta
|
|||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
|
|
||||||
To display process name in GUI please use [Razord-meta](https://github.com/MetaCubeX/Razord-meta).
|
To display process name in GUI please use [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
||||||
|
|
||||||
### Dashboard
|

|
||||||
|
|
||||||
We also made a custom fork of yacd provide better support for this project, check it out at [Yacd-meta](https://github.com/MetaCubeX/Yacd-meta)
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
If you want to build an application that uses clash as a library, check out the
|
If you want to build an application that uses clash as a library, check out the
|
||||||
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
|
|
||||||
## Debugging
|
|
||||||
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
|
||||||
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -92,8 +92,6 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["xudp"] = p.SupportXUDP()
|
|
||||||
mapping["tfo"] = p.SupportTFO()
|
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -200,9 +198,10 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
Host: u.Hostname(),
|
AddrType: C.AtypDomainName,
|
||||||
DstIP: netip.Addr{},
|
Host: u.Hostname(),
|
||||||
DstPort: port,
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -1,29 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Addition func(metadata *C.Metadata)
|
|
||||||
|
|
||||||
func (a Addition) Apply(metadata *C.Metadata) {
|
|
||||||
a(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithInName(name string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.InName = name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSpecialRules(specialRules string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.SpecialRules = specialRules
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSpecialProxy(specialProxy string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.SpecialProxy = specialProxy
|
|
||||||
}
|
|
||||||
}
|
|
@ -9,20 +9,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Addition) *context.ConnContext {
|
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(source); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -9,19 +9,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *context.ConnContext {
|
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPS
|
metadata.Type = C.HTTPS
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -1,26 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
lc = tfo.ListenConfig{
|
|
||||||
DisableTFO: true,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetTfo(open bool) {
|
|
||||||
lc.DisableTFO = !open
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
|
||||||
return lc.Listen(ctx, network, address)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Listen(network, address string) (net.Listener, error) {
|
|
||||||
return ListenContext(context.Background(), network, address)
|
|
||||||
}
|
|
@ -17,26 +17,17 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) C.PacketAdapter {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
|
||||||
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &PacketAdapter{
|
return &PacketAdapter{
|
||||||
packet,
|
UDPPacket: packet,
|
||||||
metadata,
|
metadata: metadata,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,21 +10,17 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) *context.ConnContext {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
for _, addition := range additions {
|
remoteAddr := conn.RemoteAddr()
|
||||||
addition.Apply(metadata)
|
// Filter when net.Addr interface is nil
|
||||||
}
|
if remoteAddr != nil {
|
||||||
|
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
metadata.SrcIP = ip
|
||||||
metadata.SrcIP = ip
|
metadata.SrcPort = port
|
||||||
metadata.SrcPort = port
|
}
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
@ -34,14 +30,19 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|||||||
metadata := &C.Metadata{}
|
metadata := &C.Metadata{}
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.INNER
|
metadata.Type = C.INNER
|
||||||
metadata.DNSMode = C.DNSNormal
|
metadata.DNSMode = C.DNSMapping
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
|
metadata.AddrType = C.AtypDomainName
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
metadata.DstPort = port
|
metadata.DstPort = port
|
||||||
if host == "" {
|
if host == "" {
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
if ip.Is6() {
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{}
|
metadata := &C.Metadata{
|
||||||
|
AddrType: int(target[0]),
|
||||||
|
}
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -44,33 +45,29 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
host = strings.TrimRight(host, ".")
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Host: host,
|
AddrType: C.AtypDomainName,
|
||||||
DstIP: netip.Addr{},
|
Host: host,
|
||||||
DstPort: port,
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
switch {
|
||||||
|
case ip.Is6():
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
default:
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
func parseAddr(addr string) (netip.Addr, string, error) {
|
||||||
// Filter when net.Addr interface is nil
|
host, port, err := net.SplitHostPort(addr)
|
||||||
if addr == nil {
|
|
||||||
return netip.Addr{}, "", errors.New("nil addr")
|
|
||||||
}
|
|
||||||
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
|
||||||
ip, port, err := parseAddr(rawAddr.RawAddr())
|
|
||||||
if err == nil {
|
|
||||||
return ip, port, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addrStr := addr.String()
|
|
||||||
host, port, err := net.SplitHostPort(addrStr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return netip.Addr{}, "", err
|
return netip.Addr{}, "", err
|
||||||
}
|
}
|
||||||
|
@ -4,11 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -19,8 +18,6 @@ type Base struct {
|
|||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
xudp bool
|
|
||||||
tfo bool
|
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
prefer C.DNSPrefer
|
prefer C.DNSPrefer
|
||||||
@ -34,7 +31,7 @@ func (b *Base) Name() string {
|
|||||||
// Id implements C.ProxyAdapter
|
// Id implements C.ProxyAdapter
|
||||||
func (b *Base) Id() string {
|
func (b *Base) Id() string {
|
||||||
if b.id == "" {
|
if b.id == "" {
|
||||||
id, err := utils.UnsafeUUIDGenerator.NewV6()
|
id, err := uuid.NewV6()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.id = b.name
|
b.id = b.name
|
||||||
} else {
|
} else {
|
||||||
@ -59,26 +56,16 @@ func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (b *Base) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportWithDialer() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
func (b *Base) SupportUOT() bool {
|
func (b *Base) SupportUOT() bool {
|
||||||
return false
|
return false
|
||||||
@ -89,16 +76,6 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportXUDP implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportXUDP() bool {
|
|
||||||
return b.xudp
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportTFO implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportTFO() bool {
|
|
||||||
return b.tfo
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
@ -113,7 +90,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -139,15 +116,10 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.tfo {
|
|
||||||
opts = append(opts, dialer.WithTFO(true))
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||||
@ -158,8 +130,6 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
XUDP bool
|
|
||||||
TFO bool
|
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
Prefer C.DNSPrefer
|
Prefer C.DNSPrefer
|
||||||
@ -171,8 +141,6 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
xudp: opt.XUDP,
|
|
||||||
tfo: opt.TFO,
|
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
prefer: opt.Prefer,
|
prefer: opt.Prefer,
|
||||||
@ -180,7 +148,7 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
N.ExtendedConn
|
net.Conn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
@ -199,12 +167,8 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *conn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
|
@ -5,7 +5,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -15,7 +14,7 @@ type Direct struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithDirect())
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -26,8 +25,8 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithDirect())
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -14,7 +15,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -44,9 +44,7 @@ type HttpOption struct {
|
|||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
err := cc.Handshake()
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
@ -61,20 +59,13 @@ func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return h.DialContextWithDialer(ctx, dialer.NewDialer(h.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -84,11 +75,6 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
return NewConn(c, h), nil
|
return NewConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (h *Http) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
req := &http.Request{
|
req := &http.Request{
|
||||||
@ -150,7 +136,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
})
|
})
|
||||||
@ -170,7 +156,6 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -4,41 +4,39 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/core"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
|
"github.com/lucas-clemente/quic-go"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/metacubex/quic-go"
|
|
||||||
"github.com/metacubex/quic-go/congestion"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/core"
|
"github.com/lucas-clemente/quic-go/congestion"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
mbpsToBps = 125000
|
mbpsToBps = 125000
|
||||||
|
minSpeedBPS = 16384
|
||||||
|
|
||||||
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||||
|
DefaultMaxIncomingStreams = 1024
|
||||||
|
|
||||||
DefaultALPN = "hysteria"
|
DefaultALPN = "hysteria"
|
||||||
DefaultProtocol = "udp"
|
DefaultProtocol = "udp"
|
||||||
DefaultHopInterval = 10
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
@ -52,11 +50,11 @@ type Hysteria struct {
|
|||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
hdc := hyDialerWithContext{
|
hdc := hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func(network string) (net.PacketConn, error) {
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,11 +69,11 @@ func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
hdc := hyDialerWithContext{
|
hdc := hyDialerWithContext{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func(network string) (net.PacketConn, error) {
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
udpConn, err := h.client.DialUDP(&hdc)
|
udpConn, err := h.client.DialUDP(&hdc)
|
||||||
@ -87,30 +85,23 @@ func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
|
|
||||||
type HysteriaOption struct {
|
type HysteriaOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port,omitempty"`
|
Port int `proxy:"port"`
|
||||||
Ports string `proxy:"ports,omitempty"`
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
Up string `proxy:"up"`
|
||||||
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
Down string `proxy:"down"`
|
||||||
Up string `proxy:"up"`
|
AuthString string `proxy:"auth_str,omitempty"`
|
||||||
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
Down string `proxy:"down"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Auth string `proxy:"auth,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
AuthString string `proxy:"auth-str,omitempty"`
|
ALPN string `proxy:"alpn,omitempty"`
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
CustomCAString string `proxy:"ca_str,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
ReceiveWindow int `proxy:"recv_window,omitempty"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable_mtu_discovery,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
|
||||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
@ -134,9 +125,8 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
Timeout: 8 * time.Second,
|
Timeout: 8 * time.Second,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
ports := option.Ports
|
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
serverName = option.SNI
|
serverName = option.SNI
|
||||||
@ -178,14 +168,15 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = []string{option.ALPN}
|
||||||
} else {
|
} else {
|
||||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
}
|
}
|
||||||
|
|
||||||
quicConfig := &quic.Config{
|
quicConfig := &quic.Config{
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
@ -195,17 +186,10 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
if option.ObfsProtocol != "" {
|
|
||||||
option.Protocol = option.ObfsProtocol
|
|
||||||
}
|
|
||||||
if option.Protocol == "" {
|
if option.Protocol == "" {
|
||||||
option.Protocol = DefaultProtocol
|
option.Protocol = DefaultProtocol
|
||||||
}
|
}
|
||||||
if option.HopInterval == 0 {
|
if option.ReceiveWindowConn == 0 {
|
||||||
option.HopInterval = DefaultHopInterval
|
|
||||||
}
|
|
||||||
hopInterval := time.Duration(int64(option.HopInterval)) * time.Second
|
|
||||||
if option.ReceiveWindow == 0 {
|
|
||||||
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
||||||
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||||
}
|
}
|
||||||
@ -218,12 +202,6 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var auth = []byte(option.AuthString)
|
var auth = []byte(option.AuthString)
|
||||||
if option.Auth != "" {
|
|
||||||
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var obfuscator obfs.Obfuscator
|
var obfuscator obfs.Obfuscator
|
||||||
if len(option.Obfs) > 0 {
|
if len(option.Obfs) > 0 {
|
||||||
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||||
@ -233,16 +211,11 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if option.UpSpeed != 0 {
|
|
||||||
up = uint64(option.UpSpeed * mbpsToBps)
|
|
||||||
}
|
|
||||||
if option.DownSpeed != 0 {
|
|
||||||
down = uint64(option.DownSpeed * mbpsToBps)
|
|
||||||
}
|
|
||||||
client, err := core.NewClient(
|
client, err := core.NewClient(
|
||||||
addr, ports, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
}, obfuscator, hopInterval, option.FastOpen,
|
}, obfuscator,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
@ -253,7 +226,6 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Hysteria,
|
tp: C.Hysteria,
|
||||||
udp: true,
|
udp: true,
|
||||||
tfo: option.FastOpen,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -322,17 +294,13 @@ func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type hyDialerWithContext struct {
|
type hyDialerWithContext struct {
|
||||||
hyDialer func(network string) (net.PacketConn, error)
|
hyDialer func() (net.PacketConn, error)
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
remoteAddr func(host string) (net.Addr, error)
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, error) {
|
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
|
||||||
network := "udp"
|
return h.hyDialer()
|
||||||
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
|
||||||
network = dialer.ParseNetwork(network, addrPort.Addr())
|
|
||||||
}
|
|
||||||
return h.hyDialer(network)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hyDialerWithContext) Context() context.Context {
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
@ -1,35 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
|
|
||||||
"golang.org/x/crypto/curve25519"
|
|
||||||
)
|
|
||||||
|
|
||||||
type RealityOptions struct {
|
|
||||||
PublicKey string `proxy:"public-key"`
|
|
||||||
ShortID string `proxy:"short-id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
|
||||||
if o.PublicKey != "" {
|
|
||||||
config := new(tlsC.RealityConfig)
|
|
||||||
|
|
||||||
n, err := base64.RawURLEncoding.Decode(config.PublicKey[:], []byte(o.PublicKey))
|
|
||||||
if err != nil || n != curve25519.ScalarSize {
|
|
||||||
return nil, errors.New("invalid REALITY public key")
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
|
||||||
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
|
||||||
return nil, errors.New("invalid REALITY short ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
return config, nil
|
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
@ -6,7 +6,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -17,12 +16,12 @@ type Reject struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
return NewConn(nopConn{}, r), nil
|
return NewConn(&nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return newPacketConn(nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
@ -49,37 +48,27 @@ func NewPass() *Reject {
|
|||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw nopConn) Read(b []byte) (int, error) {
|
func (rw *nopConn) Read(b []byte) (int, error) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
func (rw *nopConn) Write(b []byte) (int, error) {
|
||||||
return io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw nopConn) Write(b []byte) (int, error) {
|
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
func (rw *nopConn) Close() error { return nil }
|
||||||
return io.EOF
|
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
||||||
}
|
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) Close() error { return nil }
|
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||||
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
func (npc nopPacketConn) Close() error { return nil }
|
func (npc *nopPacketConn) Close() error { return nil }
|
||||||
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
||||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
@ -6,34 +6,35 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
"github.com/sagernet/sing-shadowsocks"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/sagernet/sing/common/buf"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/common/uot"
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
buf.DefaultAllocator = pool.DefaultAllocator
|
||||||
|
}
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
method shadowsocks.Method
|
method shadowsocks.Method
|
||||||
|
|
||||||
option *ShadowSocksOption
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
@ -65,32 +66,8 @@ type v2rayObfsOption struct {
|
|||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type shadowTLSOption struct {
|
|
||||||
Password string `obfs:"password"`
|
|
||||||
Host string `obfs:"host"`
|
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
|
||||||
ClientFingerprint string `obfs:"client-fingerprint,omitempty"`
|
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
|
||||||
Version int `obfs:"version,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
switch ss.obfsMode {
|
|
||||||
case shadowtls.Mode:
|
|
||||||
// fix tls handshake not timeout
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
var err error
|
|
||||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ss.streamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) streamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -105,80 +82,49 @@ func (ss *ShadowSocks) streamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
if N.NeedHandshake(c) {
|
metadata.Host = uot.UOTMagicAddress
|
||||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443")), nil
|
metadata.DstPort = "443"
|
||||||
} else {
|
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
switch ss.obfsMode {
|
c, err = ss.StreamConn(c, metadata)
|
||||||
case shadowtls.Mode:
|
|
||||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = ss.streamConn(c, metadata)
|
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return ss.ListenPacketWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
tcpConn, err := ss.DialContext(ctx, metadata, opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
||||||
}
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
addr, err := resolveUDPAddrWithPrefer("udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
||||||
return newPacketConn(pc, ss), nil
|
return newPacketConn(pc, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
@ -194,14 +140,13 @@ func (ss *ShadowSocks) SupportUOT() bool {
|
|||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password, time.Now)
|
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -237,23 +182,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
|
||||||
obfsMode = shadowtls.Mode
|
|
||||||
opt := &shadowTLSOption{
|
|
||||||
Version: 2,
|
|
||||||
}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, opt); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
|
||||||
Password: opt.Password,
|
|
||||||
Host: opt.Host,
|
|
||||||
Fingerprint: opt.Fingerprint,
|
|
||||||
ClientFingerprint: opt.ClientFingerprint,
|
|
||||||
SkipCertVerify: opt.SkipCertVerify,
|
|
||||||
Version: opt.Version,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -262,18 +190,16 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
method: method,
|
method: method,
|
||||||
|
|
||||||
option: &option,
|
option: &option,
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
shadowTLSOption: shadowTLSOpt,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -60,20 +60,13 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return ssr.DialContextWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
@ -81,18 +74,14 @@ func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dia
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return ssr.ListenPacketWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
addr, err := resolveUDPAddrWithPrefer("udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,11 +90,6 @@ func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Di
|
|||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
// SSR protocol compatibility
|
// SSR protocol compatibility
|
||||||
// https://github.com/Dreamacro/clash/pull/2056
|
// https://github.com/Dreamacro/clash/pull/2056
|
||||||
@ -163,7 +147,6 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -78,20 +78,13 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.DialContextWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConn(c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
@ -99,12 +92,7 @@ func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return s.ListenPacketWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -120,9 +108,10 @@ func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
return newPacketConn(pc, s), nil
|
return newPacketConn(pc, s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (s *Snell) SupportWithDialer() bool {
|
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
return true
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -167,7 +156,6 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -5,12 +5,12 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -41,9 +41,7 @@ type Socks5Option struct {
|
|||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
err := cc.Handshake()
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -65,20 +63,13 @@ func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -88,11 +79,6 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
return NewConn(c, ss), nil
|
return NewConn(c, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *Socks5) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
@ -103,15 +89,11 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
err = cc.Handshake()
|
||||||
defer cancel()
|
|
||||||
err = cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
@ -128,21 +110,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
err = errors.New("invalid UDP bind address")
|
|
||||||
return
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr(ctx, "udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", bindUDPAddr.AddrPort().Addr()), "", ss.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -155,6 +123,20 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc.Close()
|
pc.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// Support unspecified UDP bind address.
|
||||||
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -167,7 +149,7 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
var err error
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
@ -182,7 +164,6 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -4,13 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
@ -26,28 +25,24 @@ type Trojan struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
@ -80,13 +75,8 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
|
||||||
t.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
if t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig, t.realityConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
} else {
|
} else {
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(c)
|
||||||
}
|
}
|
||||||
@ -105,7 +95,7 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
return N.NewExtendedConn(c), err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -130,20 +120,14 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
return NewConn(c, t), nil
|
return NewConn(c, t), nil
|
||||||
}
|
}
|
||||||
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
c, err = t.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -163,33 +147,18 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
} else {
|
||||||
}(c)
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
c, err = t.plainStream(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
return newPacketConn(pc, t), err
|
|
||||||
}
|
|
||||||
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = t.plainStream(c)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
@ -201,11 +170,6 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
return newPacketConn(pc, t), err
|
return newPacketConn(pc, t), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
pc := t.instance.PacketConn(c)
|
pc := t.instance.PacketConn(c)
|
||||||
@ -221,25 +185,21 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
tOption := &trojan.Option{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
Fingerprint: option.Fingerprint,
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
case "", "tcp":
|
option.Flow = option.Flow[:16]
|
||||||
if len(option.Flow) >= 16 {
|
switch option.Flow {
|
||||||
option.Flow = option.Flow[:16]
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
switch option.Flow {
|
tOption.Flow = option.Flow
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
default:
|
||||||
tOption.Flow = option.Flow
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -253,7 +213,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -262,13 +221,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
|
||||||
t.realityConfig, err = option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
tOption.Reality = t.realityConfig
|
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
||||||
@ -287,7 +239,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
var err error
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
@ -295,7 +247,11 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
if t.option.Flow != "" {
|
||||||
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
|
} else {
|
||||||
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
|
@ -1,251 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/quic-go"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Tuic struct {
|
|
||||||
*Base
|
|
||||||
client *tuic.PoolClient
|
|
||||||
}
|
|
||||||
|
|
||||||
type TuicOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Token string `proxy:"token"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
|
||||||
ReduceRtt bool `proxy:"reduce-rtt,omitempty"`
|
|
||||||
RequestTimeout int `proxy:"request-timeout,omitempty"`
|
|
||||||
UdpRelayMode string `proxy:"udp-relay-mode,omitempty"`
|
|
||||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
|
||||||
DisableSni bool `proxy:"disable-sni,omitempty"`
|
|
||||||
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
|
||||||
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
|
||||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
|
||||||
SNI string `proxy:"sni,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
conn, err := t.client.DialContextWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return NewConn(conn, t), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
pc, err := t.client.ListenPacketWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(pc, t), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
|
||||||
return t.dialWithDialer(ctx, dialer.NewDialer(opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
addr = udpAddr
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
serverName := option.Server
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
if option.SNI != "" {
|
|
||||||
tlsConfig.ServerName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
var bs []byte
|
|
||||||
var err error
|
|
||||||
if len(option.CustomCA) > 0 {
|
|
||||||
bs, err = os.ReadFile(option.CustomCA)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("tuic %s load ca error: %w", addr, err)
|
|
||||||
}
|
|
||||||
} else if option.CustomCAString != "" {
|
|
||||||
bs = []byte(option.CustomCAString)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(bs) > 0 {
|
|
||||||
block, _ := pem.Decode(bs)
|
|
||||||
if block == nil {
|
|
||||||
return nil, fmt.Errorf("CA cert is not PEM")
|
|
||||||
}
|
|
||||||
|
|
||||||
fpBytes := sha256.Sum256(block.Bytes)
|
|
||||||
if len(option.Fingerprint) == 0 {
|
|
||||||
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.Fingerprint) != 0 {
|
|
||||||
var err error
|
|
||||||
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
tlsConfig.NextProtos = option.ALPN
|
|
||||||
} else {
|
|
||||||
tlsConfig.NextProtos = []string{"h3"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.RequestTimeout == 0 {
|
|
||||||
option.RequestTimeout = 8000
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.HeartbeatInterval <= 0 {
|
|
||||||
option.HeartbeatInterval = 10000
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.UdpRelayMode != "quic" {
|
|
||||||
option.UdpRelayMode = "native"
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
|
||||||
option.MaxUdpRelayPacketSize = 1252
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxOpenStreams == 0 {
|
|
||||||
option.MaxOpenStreams = 100
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
|
||||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
|
||||||
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
|
||||||
quicConfig := &quic.Config{
|
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
MaxIncomingStreams: quicMaxOpenStreams,
|
|
||||||
MaxIncomingUniStreams: quicMaxOpenStreams,
|
|
||||||
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
|
||||||
EnableDatagrams: true,
|
|
||||||
}
|
|
||||||
if option.ReceiveWindowConn == 0 {
|
|
||||||
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
|
|
||||||
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
|
|
||||||
}
|
|
||||||
if option.ReceiveWindow == 0 {
|
|
||||||
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
|
|
||||||
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.Ip) > 0 {
|
|
||||||
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
|
||||||
}
|
|
||||||
host := option.Server
|
|
||||||
if option.DisableSni {
|
|
||||||
host = ""
|
|
||||||
tlsConfig.ServerName = ""
|
|
||||||
}
|
|
||||||
tkn := tuic.GenTKN(option.Token)
|
|
||||||
|
|
||||||
t := &Tuic{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Tuic,
|
|
||||||
udp: true,
|
|
||||||
tfo: option.FastOpen,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
|
||||||
|
|
||||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
|
||||||
if clientMaxOpenStreams == 100 {
|
|
||||||
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
if clientMaxOpenStreams < 1 {
|
|
||||||
clientMaxOpenStreams = 1
|
|
||||||
}
|
|
||||||
clientOption := &tuic.ClientOption{
|
|
||||||
TlsConfig: tlsConfig,
|
|
||||||
QuicConfig: quicConfig,
|
|
||||||
Host: host,
|
|
||||||
Token: tkn,
|
|
||||||
UdpRelayMode: option.UdpRelayMode,
|
|
||||||
CongestionController: option.CongestionController,
|
|
||||||
ReduceRtt: option.ReduceRtt,
|
|
||||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
|
||||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
|
||||||
FastOpen: option.FastOpen,
|
|
||||||
MaxOpenStreams: clientMaxOpenStreams,
|
|
||||||
}
|
|
||||||
|
|
||||||
t.client = tuic.NewPoolClient(clientOption)
|
|
||||||
|
|
||||||
return t, nil
|
|
||||||
}
|
|
@ -2,7 +2,6 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
xtls "github.com/xtls/go"
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
@ -45,11 +44,10 @@ func getClientXSessionCache() xtls.ClientSessionCache {
|
|||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
addrType := metadata.AddrType()
|
aType := uint8(metadata.AddrType)
|
||||||
aType := uint8(addrType)
|
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch addrType {
|
switch metadata.AddrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
lenM := uint8(len(metadata.Host))
|
lenM := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
@ -64,34 +62,34 @@ func serializesSocksAddr(metadata *C.Metadata) []byte {
|
|||||||
return bytes.Join(buf, nil)
|
return bytes.Join(buf, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddr(ctx context.Context, network, address string) (*net.UDPAddr, error) {
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveProxyServerHost(ctx, host)
|
ip, err := resolver.ResolveProxyServerHost(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var ip netip.Addr
|
var ip netip.Addr
|
||||||
var fallback netip.Addr
|
|
||||||
switch prefer {
|
switch prefer {
|
||||||
case C.IPv4Only:
|
case C.IPv4Only:
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
case C.IPv6Only:
|
case C.IPv6Only:
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
case C.IPv6Prefer:
|
case C.IPv6Prefer:
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is6() {
|
if addr.Is6() {
|
||||||
@ -103,11 +101,13 @@ func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, pref
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ip = fallback
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
// C.IPv4Prefer, C.DualStack and other
|
// C.IPv4Prefer, C.DualStack and other
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for _, addr := range ips {
|
for _, addr := range ips {
|
||||||
if addr.Is4() {
|
if addr.Is4() {
|
||||||
@ -120,13 +120,12 @@ func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, pref
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !ip.IsValid() && fallback.IsValid() {
|
||||||
|
ip = fallback
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ip.IsValid() && fallback.IsValid() {
|
|
||||||
ip = fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -134,7 +133,7 @@ func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, pref
|
|||||||
}
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil && c != nil {
|
if err != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,26 +6,20 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmessSing "github.com/sagernet/sing-vmess"
|
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -42,46 +36,35 @@ type Vless struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
|
||||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -89,7 +72,6 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,12 +90,9 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -157,7 +136,11 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
if v.isXTLSEnabled() {
|
||||||
|
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS And XTLS
|
// handle TLS And XTLS
|
||||||
@ -168,17 +151,21 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
if v.isLegacyXTLSEnabled() && !isH2 {
|
if v.isXTLSEnabled() {
|
||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
Fingerprint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
}
|
||||||
|
|
||||||
|
if isH2 {
|
||||||
|
xtlsOpts.NextProtos = []string{"h2"}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -189,11 +176,9 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
} else if v.option.TLS {
|
} else if v.option.TLS {
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
FingerPrint: v.option.Fingerprint,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -210,8 +195,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
return conn, nil
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isLegacyXTLSEnabled() bool {
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
return v.client.Addons != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -222,43 +207,32 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
@ -272,55 +246,17 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
packetAddrMetadata := *metadata // make a copy
|
|
||||||
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
|
||||||
packetAddrMetadata.DstPort = "443"
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(&packetAddrMetadata, false))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
packetAddrMetadata := *metadata // make a copy
|
|
||||||
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
|
||||||
packetAddrMetadata.DstPort = "443"
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, &packetAddrMetadata)
|
|
||||||
} else {
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -331,24 +267,8 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (v *Vless) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if v.option.XUDP {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: vmessSing.NewXUDPConn(c, M.ParseSocksaddr(metadata.RemoteAddress())),
|
|
||||||
}, v), nil
|
|
||||||
} else if v.option.PacketAddr {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
|
||||||
Conn: c, rAddr: metadata.UDPAddr(),
|
|
||||||
}, M.ParseSocksaddr(metadata.RemoteAddress())),
|
|
||||||
}, v), nil
|
|
||||||
}
|
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -357,19 +277,19 @@ func (v *Vless) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType() {
|
switch metadata.AddrType {
|
||||||
case socks5.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = vless.AtypIPv4
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case socks5.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
addrType = vless.AtypIPv6
|
addrType = vless.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case socks5.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
addrType = vless.AtypDomainName
|
addrType = vless.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
@ -381,8 +301,7 @@ func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
|||||||
UDP: metadata.NetWork == C.UDP,
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: uint16(port),
|
Port: uint(port),
|
||||||
Mux: metadata.NetWork == C.UDP && xudp,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -483,9 +402,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
switch option.Flow {
|
||||||
case vless.XRV:
|
|
||||||
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
|
||||||
fallthrough
|
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
@ -495,16 +411,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
|
||||||
case "packetaddr", "packet":
|
|
||||||
option.PacketAddr = true
|
|
||||||
option.XUDP = false
|
|
||||||
default: // https://github.com/XTLS/Xray-core/pull/1567#issuecomment-1407305458
|
|
||||||
if !option.PacketAddr {
|
|
||||||
option.XUDP = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -516,21 +422,13 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2":
|
case "h2":
|
||||||
if len(option.HTTP2Opts.Host) == 0 {
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
@ -547,11 +445,10 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
})
|
||||||
@ -564,8 +461,11 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
if v.isXTLSEnabled() {
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
|
} else {
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -5,27 +5,23 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
|
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
*Base
|
*Base
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
@ -35,35 +31,28 @@ type Vmess struct {
|
|||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *gun.TransportWrap
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
|
||||||
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 {
|
type HTTPOptions struct {
|
||||||
@ -91,13 +80,9 @@ type WSOptions struct {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
|
||||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &clashVMess.WebsocketConfig{
|
wsOpts := &clashVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -105,7 +90,6 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,8 +108,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
|
var err error
|
||||||
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -143,15 +128,14 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -170,11 +154,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := clashVMess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -193,16 +175,14 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
c, err = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -217,25 +197,9 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
if v.option.XUDP {
|
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
if N.NeedHandshake(c) {
|
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
return v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -247,9 +211,7 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -258,19 +220,13 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
@ -278,9 +234,9 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
@ -288,8 +244,6 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
if v.option.PacketAddr {
|
||||||
_metadata := *metadata // make a copy
|
|
||||||
metadata = &_metadata
|
|
||||||
metadata.Host = packetaddr.SeqPacketMagicAddress
|
metadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
metadata.DstPort = "443"
|
metadata.DstPort = "443"
|
||||||
}
|
}
|
||||||
@ -301,68 +255,36 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if v.option.XUDP {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
tcpKeepAlive(c)
|
||||||
}
|
defer safeConnClose(c, err)
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
c, err = v.StreamConn(c, metadata)
|
||||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
if v.option.PacketAddr {
|
||||||
func (v *Vmess) SupportWithDialer() bool {
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
||||||
return true
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if v.option.PacketAddr {
|
if v.option.PacketAddr {
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
||||||
} else if pc, ok := c.(net.PacketConn); ok {
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
}
|
}
|
||||||
@ -377,9 +299,6 @@ func (v *Vmess) SupportUOT() bool {
|
|||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
var options []vmess.ClientOption
|
var options []vmess.ClientOption
|
||||||
if option.GlobalPadding {
|
|
||||||
options = append(options, vmess.ClientWithGlobalPadding())
|
|
||||||
}
|
|
||||||
if option.AuthenticatedLength {
|
if option.AuthenticatedLength {
|
||||||
options = append(options, vmess.ClientWithAuthenticatedLength())
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
}
|
}
|
||||||
@ -388,20 +307,10 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
|
||||||
case "packetaddr", "packet":
|
|
||||||
option.PacketAddr = true
|
|
||||||
case "xudp":
|
|
||||||
option.XUDP = true
|
|
||||||
}
|
|
||||||
if option.XUDP {
|
|
||||||
option.PacketAddr = false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2", "grpc":
|
case "h2", "grpc":
|
||||||
if !option.TLS {
|
if !option.TLS {
|
||||||
option.TLS = true
|
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -411,8 +320,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -437,9 +344,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
@ -454,15 +360,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -483,14 +382,7 @@ type vmessPacketConn struct {
|
|||||||
access sync.Mutex
|
access sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteTo implments C.PacketConn.WriteTo
|
|
||||||
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
allowedAddr := uc.rAddr.(*net.UDPAddr)
|
|
||||||
destAddr := addr.(*net.UDPAddr)
|
|
||||||
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
|
||||||
return 0, ErrUDPRemoteAddrMismatch
|
|
||||||
}
|
|
||||||
uc.access.Lock()
|
uc.access.Lock()
|
||||||
defer uc.access.Unlock()
|
defer uc.access.Unlock()
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
|
@ -1,269 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/debug"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
"github.com/sagernet/wireguard-go/device"
|
|
||||||
)
|
|
||||||
|
|
||||||
type WireGuard struct {
|
|
||||||
*Base
|
|
||||||
bind *wireguard.ClientBind
|
|
||||||
device *device.Device
|
|
||||||
tunDevice wireguard.Device
|
|
||||||
dialer *wgSingDialer
|
|
||||||
startOnce sync.Once
|
|
||||||
startErr error
|
|
||||||
}
|
|
||||||
|
|
||||||
type WireGuardOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PrivateKey string `proxy:"private-key"`
|
|
||||||
PublicKey string `proxy:"public-key"`
|
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
|
||||||
Workers int `proxy:"workers,omitempty"`
|
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgSingDialer struct {
|
|
||||||
dialer dialer.Dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.Dialer = &wgSingDialer{}
|
|
||||||
|
|
||||||
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
|
||||||
return d.dialer.DialContext(ctx, network, destination.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
|
||||||
return d.dialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgNetDialer struct {
|
|
||||||
tunDevice wireguard.Device
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ dialer.NetDialer = &wgNetDialer{}
|
|
||||||
|
|
||||||
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|
||||||
outbound := &WireGuard{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
tp: C.WireGuard,
|
|
||||||
udp: option.UDP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
dialer: &wgSingDialer{dialer: dialer.NewDialer()},
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
|
||||||
if len(option.Reserved) > 0 {
|
|
||||||
if len(option.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
|
||||||
}
|
|
||||||
reserved[0] = uint8(option.Reserved[0])
|
|
||||||
reserved[1] = uint8(option.Reserved[1])
|
|
||||||
reserved[2] = uint8(option.Reserved[2])
|
|
||||||
}
|
|
||||||
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
|
||||||
if len(option.Ip) > 0 {
|
|
||||||
if !strings.Contains(option.Ip, "/") {
|
|
||||||
option.Ip = option.Ip + "/32"
|
|
||||||
}
|
|
||||||
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
|
||||||
localPrefixes = append(localPrefixes, prefix)
|
|
||||||
} else {
|
|
||||||
return nil, E.Cause(err, "ip address parse error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(option.Ipv6) > 0 {
|
|
||||||
if !strings.Contains(option.Ipv6, "/") {
|
|
||||||
option.Ipv6 = option.Ipv6 + "/128"
|
|
||||||
}
|
|
||||||
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
|
||||||
localPrefixes = append(localPrefixes, prefix)
|
|
||||||
} else {
|
|
||||||
return nil, E.Cause(err, "ipv6 address parse error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(localPrefixes) == 0 {
|
|
||||||
return nil, E.New("missing local address")
|
|
||||||
}
|
|
||||||
var privateKey, peerPublicKey, preSharedKey string
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode private key")
|
|
||||||
}
|
|
||||||
privateKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
if option.PreSharedKey != "" {
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
|
||||||
}
|
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
ipcConf := "private_key=" + privateKey
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + peerAddr.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
|
||||||
if option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
mtu := option.MTU
|
|
||||||
if mtu == 0 {
|
|
||||||
mtu = 1408
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
|
||||||
}
|
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
|
||||||
log.SingLogger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
|
||||||
},
|
|
||||||
Errorf: func(format string, args ...interface{}) {
|
|
||||||
log.SingLogger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
|
||||||
},
|
|
||||||
}, option.Workers)
|
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace("created wireguard ipc conf: \n", ipcConf)
|
|
||||||
}
|
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
|
||||||
}
|
|
||||||
//err = outbound.tunDevice.Start()
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeWireGuard(w *WireGuard) {
|
|
||||||
if w.device != nil {
|
|
||||||
w.device.Close()
|
|
||||||
}
|
|
||||||
_ = common.Close(w.tunDevice)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
options := w.Base.DialOptions(opts...)
|
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var conn net.Conn
|
|
||||||
w.startOnce.Do(func() {
|
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
options = append(options, dialer.WithResolver(resolver.DefaultResolver))
|
|
||||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
|
||||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
|
||||||
} else {
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if conn == nil {
|
|
||||||
return nil, E.New("conn is nil")
|
|
||||||
}
|
|
||||||
return NewConn(CN.NewRefConn(conn, w), w), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
options := w.Base.DialOptions(opts...)
|
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var pc net.PacketConn
|
|
||||||
w.startOnce.Do(func() {
|
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if pc == nil {
|
|
||||||
return nil, E.New("packetConn is nil")
|
|
||||||
}
|
|
||||||
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
|
||||||
}
|
|
@ -4,14 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
@ -32,21 +29,9 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
|
f.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed()
|
||||||
}
|
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
f.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
@ -87,8 +72,8 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (f *Fallback) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
proxy := f.findAliveProxy(touch)
|
proxy := f.findAliveProxy(true)
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,8 +131,6 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
@ -3,68 +3,47 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filterRegs []*regexp2.Regexp
|
filter *regexp2.Regexp
|
||||||
excludeFilterReg *regexp2.Regexp
|
providers []provider.ProxyProvider
|
||||||
excludeTypeArray []string
|
failedTestMux sync.Mutex
|
||||||
providers []provider.ProxyProvider
|
failedTimes int
|
||||||
failedTestMux sync.Mutex
|
failedTime time.Time
|
||||||
failedTimes int
|
failedTesting *atomic.Bool
|
||||||
failedTime time.Time
|
proxies [][]C.Proxy
|
||||||
failedTesting *atomic.Bool
|
versions []atomic.Uint32
|
||||||
proxies [][]C.Proxy
|
|
||||||
versions []atomic.Uint32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
providers []provider.ProxyProvider
|
||||||
excludeType string
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var excludeFilterReg *regexp2.Regexp
|
var filter *regexp2.Regexp = nil
|
||||||
if opt.excludeFilter != "" {
|
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
|
||||||
}
|
|
||||||
var excludeTypeArray []string
|
|
||||||
if opt.excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(opt.excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
for _, filter := range strings.Split(opt.filter, "`") {
|
filter = regexp2.MustCompile(opt.filter, 0)
|
||||||
filterReg := regexp2.MustCompile(filter, 0)
|
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gb := &GroupBase{
|
gb := &GroupBase{
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
filterRegs: filterRegs,
|
filter: filter,
|
||||||
excludeFilterReg: excludeFilterReg,
|
providers: opt.providers,
|
||||||
excludeTypeArray: excludeTypeArray,
|
failedTesting: atomic.NewBool(false),
|
||||||
providers: opt.providers,
|
|
||||||
failedTesting: atomic.NewBool(false),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
@ -73,122 +52,59 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
return gb
|
return gb
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) Touch() {
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
pd.Touch()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
var proxies []C.Proxy
|
if gb.filter == nil {
|
||||||
if len(gb.filterRegs) == 0 {
|
var proxies []C.Proxy
|
||||||
for _, pd := range gb.providers {
|
for _, pd := range gb.providers {
|
||||||
if touch {
|
if touch {
|
||||||
pd.Touch()
|
pd.Touch()
|
||||||
}
|
}
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
}
|
}
|
||||||
} else {
|
if len(proxies) == 0 {
|
||||||
for i, pd := range gb.providers {
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
if touch {
|
}
|
||||||
pd.Touch()
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
if pd.VehicleType() == types.Compatible {
|
for i, pd := range gb.providers {
|
||||||
gb.versions[i].Store(pd.Version())
|
if touch {
|
||||||
gb.proxies[i] = pd.Proxies()
|
pd.Touch()
|
||||||
continue
|
}
|
||||||
}
|
|
||||||
|
|
||||||
version := gb.versions[i].Load()
|
if pd.VehicleType() == types.Compatible {
|
||||||
if version != pd.Version() && gb.versions[i].CompareAndSwap(version, pd.Version()) {
|
gb.versions[i].Store(pd.Version())
|
||||||
var (
|
gb.proxies[i] = pd.Proxies()
|
||||||
proxies []C.Proxy
|
continue
|
||||||
newProxies []C.Proxy
|
}
|
||||||
)
|
|
||||||
|
|
||||||
proxies = pd.Proxies()
|
version := gb.versions[i].Load()
|
||||||
proxiesSet := map[string]struct{}{}
|
if version != pd.Version() && gb.versions[i].CAS(version, pd.Version()) {
|
||||||
for _, filterReg := range gb.filterRegs {
|
var (
|
||||||
for _, p := range proxies {
|
proxies []C.Proxy
|
||||||
name := p.Name()
|
newProxies []C.Proxy
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
)
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
proxies = pd.Proxies()
|
||||||
newProxies = append(newProxies, p)
|
for _, p := range proxies {
|
||||||
}
|
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
||||||
}
|
newProxies = append(newProxies, p)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gb.proxies[i] = newProxies
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range gb.proxies {
|
gb.proxies[i] = newProxies
|
||||||
proxies = append(proxies, p...)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, p := range gb.proxies {
|
||||||
|
proxies = append(proxies, p...)
|
||||||
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
proxiesSet := map[string]struct{}{}
|
|
||||||
for _, filterReg := range gb.filterRegs {
|
|
||||||
for _, p := range proxies {
|
|
||||||
name := p.Name()
|
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, p := range proxies { // add not matched proxies at the end
|
|
||||||
name := p.Name()
|
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
if gb.excludeTypeArray != nil {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
for _, p := range proxies {
|
|
||||||
mType := p.Type().String()
|
|
||||||
flag := false
|
|
||||||
for i := range gb.excludeTypeArray {
|
|
||||||
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
if gb.excludeFilterReg != nil {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
for _, p := range proxies {
|
|
||||||
name := p.Name()
|
|
||||||
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -220,13 +136,8 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
func (gb *GroupBase) onDialFailed() {
|
||||||
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
if gb.failedTesting.Load() {
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.Contains(err.Error(), "connection refused") {
|
|
||||||
go gb.healthCheck()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -246,34 +157,26 @@ func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
|||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
|
gb.failedTesting.Store(true)
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
gb.healthCheck()
|
wg := sync.WaitGroup{}
|
||||||
|
for _, proxyProvider := range gb.providers {
|
||||||
|
wg.Add(1)
|
||||||
|
proxyProvider := proxyProvider
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
proxyProvider.HealthCheck()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
gb.failedTesting.Store(false)
|
||||||
|
gb.failedTimes = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) healthCheck() {
|
|
||||||
if gb.failedTesting.Load() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.failedTesting.Store(true)
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
for _, proxyProvider := range gb.providers {
|
|
||||||
wg.Add(1)
|
|
||||||
proxyProvider := proxyProvider
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
proxyProvider.HealthCheck()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
gb.failedTesting.Store(false)
|
|
||||||
gb.failedTimes = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
func (gb *GroupBase) failedIntervalTime() int64 {
|
||||||
return 5 * time.Second.Milliseconds()
|
return 5 * time.Second.Milliseconds()
|
||||||
}
|
}
|
||||||
|
@ -5,15 +5,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -21,7 +18,7 @@ import (
|
|||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
@ -85,28 +82,18 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := lb.Unwrap(metadata, true)
|
defer func() {
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
if err == nil {
|
lb.onDialSuccess()
|
||||||
c.AppendToChains(lb)
|
} else {
|
||||||
} else {
|
lb.onDialFailed()
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,7 +105,7 @@ func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata, true)
|
proxy := lb.Unwrap(metadata)
|
||||||
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,25 +116,12 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
idxMutex := sync.Mutex{}
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
|
||||||
idxMutex.Lock()
|
|
||||||
defer idxMutex.Unlock()
|
|
||||||
|
|
||||||
i := 0
|
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
if touch {
|
idx = (idx + 1) % length
|
||||||
defer func() {
|
proxy := proxies[idx]
|
||||||
idx = (idx + i) % length
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
for ; i < length; i++ {
|
|
||||||
id := (idx + i) % length
|
|
||||||
proxy := proxies[id]
|
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
i++
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -158,7 +132,7 @@ func strategyRoundRobin() strategyFn {
|
|||||||
|
|
||||||
func strategyConsistentHashing() strategyFn {
|
func strategyConsistentHashing() strategyFn {
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(proxies))
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
@ -183,10 +157,10 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
func strategyStickySessions() strategyFn {
|
func strategyStickySessions() strategyFn {
|
||||||
ttl := time.Minute * 10
|
ttl := time.Minute * 10
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
lruCache := cache.New[uint64, int](
|
lruCache := cache.NewLRUCache[uint64, int](
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
cache.WithSize[uint64, int](1000))
|
cache.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
idx, has := lruCache.Get(key)
|
idx, has := lruCache.Get(key)
|
||||||
@ -216,9 +190,9 @@ func strategyStickySessions() strategyFn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
proxies := lb.GetProxies(touch)
|
proxies := lb.GetProxies(true)
|
||||||
return lb.strategyFn(proxies, metadata, touch)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -254,8 +228,6 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
@ -21,17 +21,15 @@ var (
|
|||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
outbound.BasicOption
|
outbound.BasicOption
|
||||||
Name string `group:"name"`
|
Name string `group:"name"`
|
||||||
Type string `group:"type"`
|
Type string `group:"type"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
Use []string `group:"use,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
|
||||||
ExcludeType string `group:"exclude-type,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
@ -78,7 +76,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" {
|
if groupOption.URL == "" {
|
||||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
groupOption.URL = "http://www.gstatic.com/generate_204"
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
if groupOption.Interval == 0 {
|
||||||
|
@ -3,12 +3,9 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net"
|
"fmt"
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -18,36 +15,6 @@ type Relay struct {
|
|||||||
*GroupBase
|
*GroupBase
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyDialer struct {
|
|
||||||
proxy C.Proxy
|
|
||||||
dialer C.Dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p proxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
currentMeta, err := addrToMetadata(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if strings.Contains(network, "udp") { // should not support this operation
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
pc, err := p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return N.NewBindPacketConn(pc, currentMeta.UDPAddr()), nil
|
|
||||||
}
|
|
||||||
return p.proxy.DialContextWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
|
||||||
currentMeta, err := addrToMetadata(rAddrPort.String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
return p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
@ -58,19 +25,37 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
case 1:
|
case 1:
|
||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
var d C.Dialer
|
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
first := proxies[0]
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
|
||||||
d = proxyDialer{
|
|
||||||
proxy: proxy,
|
|
||||||
dialer: d,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn := outbound.NewConn(c, last)
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
conn.AppendToChains(chainProxies[i])
|
conn.AppendToChains(chainProxies[i])
|
||||||
@ -92,18 +77,39 @@ func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
var d C.Dialer
|
first := proxies[0]
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
|
||||||
d = proxyDialer{
|
|
||||||
proxy: proxy,
|
|
||||||
dialer: d,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var pc C.PacketConn
|
||||||
|
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
for i := len(chainProxies) - 2; i >= 0; i-- {
|
||||||
@ -121,19 +127,8 @@ func (r *Relay) SupportUDP() bool {
|
|||||||
if len(proxies) == 0 { // C.Direct
|
if len(proxies) == 0 { // C.Direct
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
for i := len(proxies) - 1; i >= 0; i-- {
|
last := proxies[len(proxies)-1]
|
||||||
proxy := proxies[i]
|
return last.SupportUDP() && last.SupportUOT()
|
||||||
if !proxy.SupportUDP() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if proxy.SupportUOT() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if !proxy.SupportWithDialer() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -158,11 +153,11 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
for n, proxy := range rawProxies {
|
for n, proxy := range rawProxies {
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
chainProxies = append(chainProxies, proxy)
|
chainProxies = append(chainProxies, proxy)
|
||||||
subproxy := proxy.Unwrap(metadata, touch)
|
subproxy := proxy.Unwrap(metadata)
|
||||||
for subproxy != nil {
|
for subproxy != nil {
|
||||||
chainProxies = append(chainProxies, subproxy)
|
chainProxies = append(chainProxies, subproxy)
|
||||||
proxies[n] = subproxy
|
proxies[n] = subproxy
|
||||||
subproxy = subproxy.Unwrap(metadata, touch)
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -176,7 +171,7 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Addr() string {
|
func (r *Relay) Addr() string {
|
||||||
proxies, _ := r.proxies(nil, false)
|
proxies, _ := r.proxies(nil, true)
|
||||||
return proxies[len(proxies)-1].Addr()
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -190,8 +185,6 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
"",
|
"",
|
||||||
"",
|
|
||||||
"",
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
@ -74,8 +74,8 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return s.selectedProxy(touch)
|
return s.selectedProxy(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
@ -99,8 +99,6 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
@ -6,8 +6,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -36,27 +34,13 @@ func (u *URLTest) Now() string {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := u.fast(true)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
|
u.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed()
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
u.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,12 +55,12 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return u.fast(touch)
|
return u.fast(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
@ -105,9 +89,6 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
|
||||||
u.Touch()
|
|
||||||
}
|
|
||||||
|
|
||||||
return elm
|
return elm
|
||||||
}
|
}
|
||||||
@ -158,8 +139,6 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
},
|
},
|
||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
@ -16,19 +16,32 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip, err := netip.ParseAddr(host); err != nil {
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err != nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
Host: host,
|
AddrType: C.AtypDomainName,
|
||||||
DstPort: port,
|
Host: host,
|
||||||
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
} else {
|
err = nil
|
||||||
|
return
|
||||||
|
} else if ip.Is4() {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
Host: "",
|
AddrType: C.AtypIPv4,
|
||||||
DstIP: ip.Unmap(),
|
Host: "",
|
||||||
DstPort: port,
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv6,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,15 +3,13 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true, KeyReplacer: structure.DefaultKeyReplacer})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
return nil, fmt.Errorf("missing type")
|
return nil, fmt.Errorf("missing type")
|
||||||
@ -57,11 +55,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
|
||||||
vmessOption.ClientFingerprint = GlobalUtlsClient
|
|
||||||
}
|
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -69,11 +62,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{}
|
||||||
|
|
||||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
|
||||||
vlessOption.ClientFingerprint = GlobalUtlsClient
|
|
||||||
}
|
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -88,11 +76,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{}
|
trojanOption := &outbound.TrojanOption{}
|
||||||
|
|
||||||
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
|
||||||
trojanOption.ClientFingerprint = GlobalUtlsClient
|
|
||||||
}
|
|
||||||
|
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -105,20 +88,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
case "wireguard":
|
|
||||||
wgOption := &outbound.WireGuardOption{}
|
|
||||||
err = decoder.Decode(mapping, wgOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewWireGuard(*wgOption)
|
|
||||||
case "tuic":
|
|
||||||
tuicOption := &outbound.TuicOption{}
|
|
||||||
err = decoder.Decode(mapping, tuicOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewTuic(*tuicOption)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -2,13 +2,11 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
@ -37,13 +35,16 @@ func (hc *HealthCheck) process() {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
hc.lazyCheck()
|
hc.check()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
hc.lazyCheck()
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -51,17 +52,6 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) lazyCheck() bool {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -76,26 +66,18 @@ func (hc *HealthCheck) touch() {
|
|||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
id := ""
|
|
||||||
if uid, err := utils.UnsafeUUIDGenerator.NewV4(); err == nil {
|
|
||||||
id = uid.String()
|
|
||||||
}
|
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Wait()
|
b.Wait()
|
||||||
log.Debugln("Finish A Health Checking {%s}", id)
|
|
||||||
return struct{}{}, nil
|
return struct{}{}, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -3,10 +3,10 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -21,14 +21,12 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
@ -63,8 +61,5 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
|
|
||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
excludeFilter := schema.ExcludeFilter
|
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
||||||
excludeType := schema.ExcludeType
|
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, vehicle, hc)
|
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,19 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -37,20 +32,18 @@ type ProxySetProvider struct {
|
|||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*resource.Fetcher[[]C.Proxy]
|
*resource.Fetcher[[]C.Proxy]
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
version uint32
|
version uint32
|
||||||
subscriptionInfo *SubscriptionInfo
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,66 +92,19 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
defer func() { go pp.healthCheck.lazyCheck() }()
|
defer func() { go pp.healthCheck.check() }()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) getSubscriptionInfo() {
|
|
||||||
if pp.VehicleType() != types.HTTP {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
|
||||||
defer cancel()
|
|
||||||
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
|
||||||
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
|
||||||
if userInfoStr == "" {
|
|
||||||
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
|
||||||
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp2.Body.Close()
|
|
||||||
userInfoStr = strings.TrimSpace(resp2.Header.Get("subscription-userinfo"))
|
|
||||||
if userInfoStr == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pp.subscriptionInfo, err = NewSubscriptionInfo(userInfoStr)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.Fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
|
||||||
var excludeTypeArray []string
|
|
||||||
if excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
|
||||||
}
|
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
if hc.auto() {
|
||||||
@ -170,10 +116,9 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
pd.getSubscriptionInfo()
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -264,11 +209,10 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
pd.version += 1
|
pd.version += 1
|
||||||
pd.getSubscriptionInfo()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@ -285,59 +229,17 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
proxiesSet := map[string]struct{}{}
|
for idx, mapping := range schema.Proxies {
|
||||||
for _, filterReg := range filterRegs {
|
name, ok := mapping["name"]
|
||||||
for idx, mapping := range schema.Proxies {
|
mat, _ := filterReg.FindStringMatch(name.(string))
|
||||||
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
if ok && len(filter) > 0 && mat == nil {
|
||||||
mType, ok := mapping["type"]
|
continue
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
pType, ok := mType.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
flag := false
|
|
||||||
for i := range excludeTypeArray {
|
|
||||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
mName, ok := mapping["name"]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
name, ok := mName.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if len(excludeFilter) > 0 {
|
|
||||||
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(filter) > 0 {
|
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, ok := proxiesSet[name]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
}
|
||||||
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
|
@ -1,57 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SubscriptionInfo struct {
|
|
||||||
Upload int64
|
|
||||||
Download int64
|
|
||||||
Total int64
|
|
||||||
Expire int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) {
|
|
||||||
si = &SubscriptionInfo{}
|
|
||||||
str = strings.ToLower(str)
|
|
||||||
reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0)
|
|
||||||
reExpire := regexp2.MustCompile("expire=(\\d+)", 0)
|
|
||||||
|
|
||||||
match, err := reTraffic.FindStringMatch(str)
|
|
||||||
if err != nil || match == nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
group := match.Groups()
|
|
||||||
si.Upload, err = str2uint64(group[1].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
si.Download, err = str2uint64(group[2].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
si.Total, err = str2uint64(group[3].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
match, _ = reExpire.FindStringMatch(str)
|
|
||||||
if match != nil {
|
|
||||||
group = match.Groups()
|
|
||||||
si.Expire, err = str2uint64(group[1].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func str2uint64(str string) (int64, error) {
|
|
||||||
i, err := strconv.ParseInt(str, 10, 64)
|
|
||||||
return i, err
|
|
||||||
}
|
|
@ -1,25 +0,0 @@
|
|||||||
package buf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
)
|
|
||||||
|
|
||||||
const BufferSize = buf.BufferSize
|
|
||||||
|
|
||||||
type Buffer = buf.Buffer
|
|
||||||
|
|
||||||
var New = buf.New
|
|
||||||
var StackNew = buf.StackNew
|
|
||||||
var StackNewSize = buf.StackNewSize
|
|
||||||
var With = buf.With
|
|
||||||
|
|
||||||
var KeepAlive = common.KeepAlive
|
|
||||||
|
|
||||||
//go:norace
|
|
||||||
func Dup[T any](obj T) T {
|
|
||||||
return common.Dup(obj)
|
|
||||||
}
|
|
||||||
|
|
||||||
var Must = common.Must
|
|
||||||
var Error = common.Error
|
|
106
common/cache/cache.go
vendored
Normal file
106
common/cache/cache.go
vendored
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cache store element with a expired time
|
||||||
|
type Cache[K comparable, V any] struct {
|
||||||
|
*cache[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
type cache[K comparable, V any] struct {
|
||||||
|
mapping sync.Map
|
||||||
|
janitor *janitor[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
type element[V any] struct {
|
||||||
|
Expired time.Time
|
||||||
|
Payload V
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put element in Cache with its ttl
|
||||||
|
func (c *cache[K, V]) Put(key K, payload V, ttl time.Duration) {
|
||||||
|
c.mapping.Store(key, &element[V]{
|
||||||
|
Payload: payload,
|
||||||
|
Expired: time.Now().Add(ttl),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get element in Cache, and drop when it expired
|
||||||
|
func (c *cache[K, V]) Get(key K) V {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return getZero[V]()
|
||||||
|
}
|
||||||
|
elm := item.(*element[V])
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return getZero[V]()
|
||||||
|
}
|
||||||
|
return elm.Payload
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire element in Cache with Expire Time
|
||||||
|
func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
elm := item.(*element[V])
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return elm.Payload, elm.Expired
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cache[K, V]) cleanup() {
|
||||||
|
c.mapping.Range(func(k, v any) bool {
|
||||||
|
key := k.(string)
|
||||||
|
elm := v.(*element[V])
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type janitor[K comparable, V any] struct {
|
||||||
|
interval time.Duration
|
||||||
|
stop chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor[K, V]) process(c *cache[K, V]) {
|
||||||
|
ticker := time.NewTicker(j.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
c.cleanup()
|
||||||
|
case <-j.stop:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopJanitor[K comparable, V any](c *Cache[K, V]) {
|
||||||
|
c.janitor.stop <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return *Cache
|
||||||
|
func New[K comparable, V any](interval time.Duration) *Cache[K, V] {
|
||||||
|
j := &janitor[K, V]{
|
||||||
|
interval: interval,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
}
|
||||||
|
c := &cache[K, V]{janitor: j}
|
||||||
|
go j.process(c)
|
||||||
|
C := &Cache[K, V]{c}
|
||||||
|
runtime.SetFinalizer(C, stopJanitor[K, V])
|
||||||
|
return C
|
||||||
|
}
|
72
common/cache/cache_test.go
vendored
Normal file
72
common/cache/cache_test.go
vendored
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCache_Basic(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
d := New[string, string](interval)
|
||||||
|
d.Put("string", "a", ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
|
|
||||||
|
s := d.Get("string")
|
||||||
|
assert.Equal(t, s, "a", "should recv 'a'")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_TTL(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
now := time.Now()
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("int2", 2, ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
_, expired := c.GetWithExpire("int2")
|
||||||
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
|
assert.True(t, now.Before(expired))
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i = c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int2")
|
||||||
|
assert.True(t, i == 0, "should recv 0")
|
||||||
|
assert.True(t, j == 0, "should recv 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i := c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int")
|
||||||
|
assert.True(t, i == 0, "should recv 0")
|
||||||
|
assert.True(t, j == 0, "should recv 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
|
sign := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
sign <- struct{}{}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-sign
|
||||||
|
runtime.GC()
|
||||||
|
}
|
4
common/cache/lrucache.go
vendored
4
common/cache/lrucache.go
vendored
@ -65,8 +65,8 @@ type LruCache[K comparable, V any] struct {
|
|||||||
onEvict EvictCallback[K, V]
|
onEvict EvictCallback[K, V]
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates an LruCache
|
// NewLRUCache creates an LruCache
|
||||||
func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
func NewLRUCache[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||||
lc := &LruCache[K, V]{
|
lc := &LruCache[K, V]{
|
||||||
lru: list.New[*entry[K, V]](),
|
lru: list.New[*entry[K, V]](),
|
||||||
cache: make(map[K]*list.Element[*entry[K, V]]),
|
cache: make(map[K]*list.Element[*entry[K, V]]),
|
||||||
|
20
common/cache/lrucache_test.go
vendored
20
common/cache/lrucache_test.go
vendored
@ -19,7 +19,7 @@ var entries = []struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUCache(t *testing.T) {
|
func TestLRUCache(t *testing.T) {
|
||||||
c := New[string, string]()
|
c := NewLRUCache[string, string]()
|
||||||
|
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
c.Set(e.key, e.value)
|
c.Set(e.key, e.value)
|
||||||
@ -45,7 +45,7 @@ func TestLRUCache(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUMaxAge(t *testing.T) {
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
c := New[string, string](WithAge[string, string](86400))
|
c := NewLRUCache[string, string](WithAge[string, string](86400))
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expected := now + 86400
|
expected := now + 86400
|
||||||
@ -88,7 +88,7 @@ func TestLRUMaxAge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUpdateOnGet(t *testing.T) {
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
c := New[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
c := NewLRUCache[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expires := now + 86400/2
|
expires := now + 86400/2
|
||||||
@ -103,7 +103,7 @@ func TestLRUpdateOnGet(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestMaxSize(t *testing.T) {
|
func TestMaxSize(t *testing.T) {
|
||||||
c := New[string, string](WithSize[string, string](2))
|
c := NewLRUCache[string, string](WithSize[string, string](2))
|
||||||
// Add one expired entry
|
// Add one expired entry
|
||||||
c.Set("foo", "bar")
|
c.Set("foo", "bar")
|
||||||
_, ok := c.Get("foo")
|
_, ok := c.Get("foo")
|
||||||
@ -117,7 +117,7 @@ func TestMaxSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExist(t *testing.T) {
|
func TestExist(t *testing.T) {
|
||||||
c := New[int, int](WithSize[int, int](1))
|
c := NewLRUCache[int, int](WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
assert.True(t, c.Exist(1))
|
assert.True(t, c.Exist(1))
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
@ -130,7 +130,7 @@ func TestEvict(t *testing.T) {
|
|||||||
temp = key + value
|
temp = key + value
|
||||||
}
|
}
|
||||||
|
|
||||||
c := New[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
c := NewLRUCache[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
|
|
||||||
@ -138,7 +138,7 @@ func TestEvict(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSetWithExpire(t *testing.T) {
|
func TestSetWithExpire(t *testing.T) {
|
||||||
c := New[int, *struct{}](WithAge[int, *struct{}](1))
|
c := NewLRUCache[int, *struct{}](WithAge[int, *struct{}](1))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -153,7 +153,7 @@ func TestSetWithExpire(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStale(t *testing.T) {
|
func TestStale(t *testing.T) {
|
||||||
c := New[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
c := NewLRUCache[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -166,11 +166,11 @@ func TestStale(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCloneTo(t *testing.T) {
|
func TestCloneTo(t *testing.T) {
|
||||||
o := New[string, int](WithSize[string, int](10))
|
o := NewLRUCache[string, int](WithSize[string, int](10))
|
||||||
o.Set("1", 1)
|
o.Set("1", 1)
|
||||||
o.Set("2", 2)
|
o.Set("2", 2)
|
||||||
|
|
||||||
n := New[string, int](WithSize[string, int](2))
|
n := NewLRUCache[string, int](WithSize[string, int](2))
|
||||||
n.Set("3", 3)
|
n.Set("3", 3)
|
||||||
n.Set("4", 4)
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
@ -1,25 +0,0 @@
|
|||||||
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,10 +2,8 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@ -49,7 +47,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["port"] = urlHysteria.Port()
|
hysteria["port"] = urlHysteria.Port()
|
||||||
hysteria["sni"] = query.Get("peer")
|
hysteria["sni"] = query.Get("peer")
|
||||||
hysteria["obfs"] = query.Get("obfs")
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
hysteria["alpn"] = []string{query.Get("alpn")}
|
hysteria["alpn"] = query.Get("alpn")
|
||||||
hysteria["auth_str"] = query.Get("auth")
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
hysteria["protocol"] = query.Get("protocol")
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
up := query.Get("up")
|
up := query.Get("up")
|
||||||
@ -83,7 +81,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["port"] = urlTrojan.Port()
|
trojan["port"] = urlTrojan.Port()
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
trojan["password"] = urlTrojan.User.Username()
|
||||||
trojan["udp"] = true
|
trojan["udp"] = true
|
||||||
trojan["skip-cert-verify"], _ = strconv.ParseBool(query.Get("allowInsecure"))
|
trojan["skip-cert-verify"] = false
|
||||||
|
|
||||||
sni := query.Get("sni")
|
sni := query.Get("sni")
|
||||||
if sni != "" {
|
if sni != "" {
|
||||||
@ -113,12 +111,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["grpc-opts"] = grpcOpts
|
trojan["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
|
||||||
trojan["client-fingerprint"] = "chrome"
|
|
||||||
} else {
|
|
||||||
trojan["client-fingerprint"] = fingerprint
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
proxies = append(proxies, trojan)
|
||||||
|
|
||||||
case "vless":
|
case "vless":
|
||||||
@ -128,11 +120,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
query := urlVLess.Query()
|
query := urlVLess.Query()
|
||||||
vless := make(map[string]any, 20)
|
vless := make(map[string]any, 20)
|
||||||
err = handleVShareLink(names, urlVLess, scheme, vless)
|
handleVShareLink(names, urlVLess, scheme, vless)
|
||||||
if err != nil {
|
|
||||||
log.Warnln("error:%s line:%s", err.Error(), line)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if flow := query.Get("flow"); flow != "" {
|
if flow := query.Get("flow"); flow != "" {
|
||||||
vless["flow"] = strings.ToLower(flow)
|
vless["flow"] = strings.ToLower(flow)
|
||||||
}
|
}
|
||||||
@ -150,11 +138,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
query := urlVMess.Query()
|
query := urlVMess.Query()
|
||||||
vmess := make(map[string]any, 20)
|
vmess := make(map[string]any, 20)
|
||||||
err = handleVShareLink(names, urlVMess, scheme, vmess)
|
handleVShareLink(names, urlVMess, scheme, vmess)
|
||||||
if err != nil {
|
|
||||||
log.Warnln("error:%s line:%s", err.Error(), line)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
vmess["alterId"] = 0
|
vmess["alterId"] = 0
|
||||||
vmess["cipher"] = "auto"
|
vmess["cipher"] = "auto"
|
||||||
if encryption := query.Get("encryption"); encryption != "" {
|
if encryption := query.Get("encryption"); encryption != "" {
|
||||||
@ -170,11 +154,8 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if jsonDc.Decode(&values) != nil {
|
if jsonDc.Decode(&values) != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
tempName, ok := values["ps"].(string)
|
|
||||||
if !ok {
|
name := uniqueName(names, values["ps"].(string))
|
||||||
continue
|
|
||||||
}
|
|
||||||
name := uniqueName(names, tempName)
|
|
||||||
vmess := make(map[string]any, 20)
|
vmess := make(map[string]any, 20)
|
||||||
|
|
||||||
vmess["name"] = name
|
vmess["name"] = name
|
||||||
@ -188,7 +169,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["alterId"] = 0
|
vmess["alterId"] = 0
|
||||||
}
|
}
|
||||||
vmess["udp"] = true
|
vmess["udp"] = true
|
||||||
vmess["xudp"] = true
|
|
||||||
vmess["tls"] = false
|
vmess["tls"] = false
|
||||||
vmess["skip-cert-verify"] = false
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
@ -284,28 +264,22 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
cipherRaw = urlSS.User.Username()
|
cipher = urlSS.User.Username()
|
||||||
cipher string
|
password string
|
||||||
password string
|
|
||||||
)
|
)
|
||||||
cipher = cipherRaw
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
if password, found = urlSS.User.Password(); !found {
|
||||||
dcBuf, err := base64.RawURLEncoding.DecodeString(cipherRaw)
|
dcBuf, _ := enc.DecodeString(cipher)
|
||||||
if err != nil {
|
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
||||||
dcBuf, _ = enc.DecodeString(cipherRaw)
|
dcBuf, _ = encRaw.DecodeString(cipher)
|
||||||
}
|
}
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
if !found {
|
if !found {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err = VerifyMethod(cipher, password)
|
|
||||||
if err != nil {
|
|
||||||
dcBuf, _ = encRaw.DecodeString(cipherRaw)
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ss := make(map[string]any, 10)
|
ss := make(map[string]any, 20)
|
||||||
|
|
||||||
ss["name"] = name
|
ss["name"] = name
|
||||||
ss["type"] = scheme
|
ss["type"] = scheme
|
||||||
@ -315,9 +289,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
ss["password"] = password
|
ss["password"] = password
|
||||||
query := urlSS.Query()
|
query := urlSS.Query()
|
||||||
ss["udp"] = true
|
ss["udp"] = true
|
||||||
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
|
||||||
ss["udp-over-tcp"] = true
|
|
||||||
}
|
|
||||||
if strings.Contains(query.Get("plugin"), "obfs") {
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
obfsParams := strings.Split(query.Get("plugin"), ";")
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
ss["plugin"] = "obfs"
|
ss["plugin"] = "obfs"
|
||||||
|
@ -2,14 +2,11 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/gofrs/uuid"
|
||||||
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@ -294,7 +291,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func RandHost() string {
|
func RandHost() string {
|
||||||
id, _ := utils.UnsafeUUIDGenerator.NewV4()
|
id, _ := uuid.NewV4()
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
base = strings.ReplaceAll(base, "-", "")
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
base = strings.ReplaceAll(base, "_", "")
|
||||||
@ -303,11 +300,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[fastrand.Intn(uaLen)]
|
return userAgents[rand.Intn(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
@ -317,8 +314,3 @@ func SetUserAgent(header http.Header) {
|
|||||||
userAgent := RandUserAgent()
|
userAgent := RandUserAgent()
|
||||||
header.Set("User-Agent", userAgent)
|
header.Set("User-Agent", userAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func VerifyMethod(cipher, password string) (err error) {
|
|
||||||
_, err = shadowimpl.FetchMethod(cipher, password, time.Now)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
@ -1,24 +1,15 @@
|
|||||||
package convert
|
package convert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) error {
|
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
||||||
// Xray VMessAEAD / VLESS share link standard
|
// Xray VMessAEAD / VLESS share link standard
|
||||||
// https://github.com/XTLS/Xray-core/discussions/716
|
// https://github.com/XTLS/Xray-core/discussions/716
|
||||||
query := url.Query()
|
query := url.Query()
|
||||||
proxy["name"] = uniqueName(names, url.Fragment)
|
proxy["name"] = uniqueName(names, url.Fragment)
|
||||||
if url.Hostname() == "" {
|
|
||||||
return errors.New("url.Hostname() is empty")
|
|
||||||
}
|
|
||||||
if url.Port() == "" {
|
|
||||||
return errors.New("url.Port() is empty")
|
|
||||||
}
|
|
||||||
proxy["type"] = scheme
|
proxy["type"] = scheme
|
||||||
proxy["server"] = url.Hostname()
|
proxy["server"] = url.Hostname()
|
||||||
proxy["port"] = url.Port()
|
proxy["port"] = url.Port()
|
||||||
@ -29,24 +20,11 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
tls := strings.ToLower(query.Get("security"))
|
tls := strings.ToLower(query.Get("security"))
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
proxy["tls"] = true
|
proxy["tls"] = true
|
||||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
|
||||||
proxy["client-fingerprint"] = "chrome"
|
|
||||||
} else {
|
|
||||||
proxy["client-fingerprint"] = fingerprint
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if sni := query.Get("sni"); sni != "" {
|
if sni := query.Get("sni"); sni != "" {
|
||||||
proxy["servername"] = sni
|
proxy["servername"] = sni
|
||||||
}
|
}
|
||||||
|
|
||||||
switch query.Get("packetEncoding") {
|
|
||||||
case "none":
|
|
||||||
case "packet":
|
|
||||||
proxy["packet-addr"] = true
|
|
||||||
default:
|
|
||||||
proxy["xudp"] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
network := strings.ToLower(query.Get("type"))
|
||||||
if network == "" {
|
if network == "" {
|
||||||
network = "tcp"
|
network = "tcp"
|
||||||
@ -101,17 +79,6 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
if earlyData := query.Get("ed"); earlyData != "" {
|
|
||||||
med, err := strconv.Atoi(earlyData)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
|
||||||
}
|
|
||||||
wsOpts["max-early-data"] = med
|
|
||||||
}
|
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy["ws-opts"] = wsOpts
|
proxy["ws-opts"] = wsOpts
|
||||||
|
|
||||||
case "grpc":
|
case "grpc":
|
||||||
@ -119,5 +86,4 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
proxy["grpc-opts"] = grpcOpts
|
proxy["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
@ -5,10 +5,10 @@
|
|||||||
// Package list implements a doubly linked list.
|
// Package list implements a doubly linked list.
|
||||||
//
|
//
|
||||||
// To iterate over a list (where l is a *List):
|
// To iterate over a list (where l is a *List):
|
||||||
//
|
|
||||||
// for e := l.Front(); e != nil; e = e.Next() {
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
// // do something with e.Value
|
// // do something with e.Value
|
||||||
// }
|
// }
|
||||||
|
//
|
||||||
package list
|
package list
|
||||||
|
|
||||||
// Element is an element of a linked list.
|
// Element is an element of a linked list.
|
||||||
|
@ -1,36 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import "net"
|
|
||||||
|
|
||||||
type bindPacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
|
||||||
n, _, err = wpc.PacketConn.ReadFrom(b)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
|
||||||
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
|
||||||
return wpc.rAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
|
||||||
if wpc.PacketConn.LocalAddr() == nil {
|
|
||||||
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
|
||||||
} else {
|
|
||||||
return wpc.PacketConn.LocalAddr()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
|
||||||
return &bindPacketConn{
|
|
||||||
PacketConn: pc,
|
|
||||||
rAddr: rAddr,
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,23 +3,18 @@ package net
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ ExtendedConn = (*BufferedConn)(nil)
|
|
||||||
|
|
||||||
type BufferedConn struct {
|
type BufferedConn struct {
|
||||||
r *bufio.Reader
|
r *bufio.Reader
|
||||||
ExtendedConn
|
net.Conn
|
||||||
peeked bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBufferedConn(c net.Conn) *BufferedConn {
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||||
if bc, ok := c.(*BufferedConn); ok {
|
if bc, ok := c.(*BufferedConn); ok {
|
||||||
return bc
|
return bc
|
||||||
}
|
}
|
||||||
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
return &BufferedConn{bufio.NewReader(c), c}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reader returns the internal bufio.Reader.
|
// Reader returns the internal bufio.Reader.
|
||||||
@ -27,24 +22,11 @@ func (c *BufferedConn) Reader() *bufio.Reader {
|
|||||||
return c.r
|
return c.r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ResetPeeked() {
|
|
||||||
c.peeked = false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Peeked() bool {
|
|
||||||
return c.peeked
|
|
||||||
}
|
|
||||||
|
|
||||||
// Peek returns the next n bytes without advancing the reader.
|
// Peek returns the next n bytes without advancing the reader.
|
||||||
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||||
c.peeked = true
|
|
||||||
return c.r.Peek(n)
|
return c.r.Peek(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) Discard(n int) (discarded int, err error) {
|
|
||||||
return c.r.Discard(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Read(p []byte) (int, error) {
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
||||||
return c.r.Read(p)
|
return c.r.Read(p)
|
||||||
}
|
}
|
||||||
@ -60,22 +42,3 @@ func (c *BufferedConn) UnreadByte() error {
|
|||||||
func (c *BufferedConn) Buffered() int {
|
func (c *BufferedConn) Buffered() int {
|
||||||
return c.r.Buffered()
|
return c.r.Buffered()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
_, err = buffer.ReadOnceFrom(c.r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return c.ExtendedConn.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) ReaderReplaceable() bool {
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
@ -1,104 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type refConn struct {
|
|
||||||
conn net.Conn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Read(b []byte) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Read(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Write(b []byte) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) RemoteAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.RemoteAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Upstream() any {
|
|
||||||
return c.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
|
||||||
return &refConn{conn: conn, ref: ref}
|
|
||||||
}
|
|
||||||
|
|
||||||
type refPacketConn struct {
|
|
||||||
pc net.PacketConn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.ReadFrom(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.WriteTo(p, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefPacketConn(pc net.PacketConn, ref any) net.PacketConn {
|
|
||||||
return &refPacketConn{pc: pc, ref: ref}
|
|
||||||
}
|
|
@ -1,24 +1,30 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
//import (
|
import (
|
||||||
// "io"
|
"io"
|
||||||
// "net"
|
"net"
|
||||||
// "time"
|
"time"
|
||||||
//)
|
|
||||||
//
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
//// Relay copies between left and right bidirectionally.
|
)
|
||||||
//func Relay(leftConn, rightConn net.Conn) {
|
|
||||||
// ch := make(chan error)
|
// Relay copies between left and right bidirectionally.
|
||||||
//
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
// go func() {
|
ch := make(chan error)
|
||||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
|
||||||
// // See also https://github.com/Dreamacro/clash/pull/1209
|
go func() {
|
||||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
// leftConn.SetReadDeadline(time.Now())
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// ch <- err
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
// }()
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
//
|
pool.Put(buf)
|
||||||
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
leftConn.SetReadDeadline(time.Now())
|
||||||
// rightConn.SetReadDeadline(time.Now())
|
ch <- err
|
||||||
// <-ch
|
}()
|
||||||
//}
|
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
|
pool.Put(buf)
|
||||||
|
rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
var NewExtendedConn = bufio.NewExtendedConn
|
|
||||||
var NewExtendedWriter = bufio.NewExtendedWriter
|
|
||||||
var NewExtendedReader = bufio.NewExtendedReader
|
|
||||||
|
|
||||||
type ExtendedConn = network.ExtendedConn
|
|
||||||
type ExtendedWriter = network.ExtendedWriter
|
|
||||||
type ExtendedReader = network.ExtendedReader
|
|
||||||
|
|
||||||
func NeedHandshake(conn any) bool {
|
|
||||||
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
|
||||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"math/big"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
|
||||||
if certificate == "" || privateKey == "" {
|
|
||||||
return newRandomTLSKeyPair()
|
|
||||||
}
|
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
|
||||||
if painTextErr == nil {
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
|
|
||||||
if loadErr != nil {
|
|
||||||
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
|
||||||
}
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
|
||||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
|
||||||
certDER, err := x509.CreateCertificate(
|
|
||||||
rand.Reader,
|
|
||||||
&template,
|
|
||||||
&template,
|
|
||||||
&key.PublicKey,
|
|
||||||
key)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
|
||||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
|
||||||
|
|
||||||
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
return tlsCert, nil
|
|
||||||
}
|
|
@ -1,131 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"math/bits"
|
|
||||||
)
|
|
||||||
|
|
||||||
// kanged from https://github.com/nhooyr/websocket/blob/master/frame.go
|
|
||||||
// License: MIT
|
|
||||||
|
|
||||||
// MaskWebSocket applies the WebSocket masking algorithm to p
|
|
||||||
// with the given key.
|
|
||||||
// See https://tools.ietf.org/html/rfc6455#section-5.3
|
|
||||||
//
|
|
||||||
// The returned value is the correctly rotated key to
|
|
||||||
// to continue to mask/unmask the message.
|
|
||||||
//
|
|
||||||
// It is optimized for LittleEndian and expects the key
|
|
||||||
// to be in little endian.
|
|
||||||
//
|
|
||||||
// See https://github.com/golang/go/issues/31586
|
|
||||||
func MaskWebSocket(key uint32, b []byte) uint32 {
|
|
||||||
if len(b) >= 8 {
|
|
||||||
key64 := uint64(key)<<32 | uint64(key)
|
|
||||||
|
|
||||||
// At some point in the future we can clean these unrolled loops up.
|
|
||||||
// See https://github.com/golang/go/issues/31586#issuecomment-487436401
|
|
||||||
|
|
||||||
// Then we xor until b is less than 128 bytes.
|
|
||||||
for len(b) >= 128 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[32:40])
|
|
||||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[40:48])
|
|
||||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[48:56])
|
|
||||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[56:64])
|
|
||||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[64:72])
|
|
||||||
binary.LittleEndian.PutUint64(b[64:72], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[72:80])
|
|
||||||
binary.LittleEndian.PutUint64(b[72:80], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[80:88])
|
|
||||||
binary.LittleEndian.PutUint64(b[80:88], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[88:96])
|
|
||||||
binary.LittleEndian.PutUint64(b[88:96], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[96:104])
|
|
||||||
binary.LittleEndian.PutUint64(b[96:104], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[104:112])
|
|
||||||
binary.LittleEndian.PutUint64(b[104:112], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[112:120])
|
|
||||||
binary.LittleEndian.PutUint64(b[112:120], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[120:128])
|
|
||||||
binary.LittleEndian.PutUint64(b[120:128], v^key64)
|
|
||||||
b = b[128:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 64 bytes.
|
|
||||||
for len(b) >= 64 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[32:40])
|
|
||||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[40:48])
|
|
||||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[48:56])
|
|
||||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[56:64])
|
|
||||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
|
||||||
b = b[64:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 32 bytes.
|
|
||||||
for len(b) >= 32 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
b = b[32:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 16 bytes.
|
|
||||||
for len(b) >= 16 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
b = b[16:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 8 bytes.
|
|
||||||
for len(b) >= 8 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
b = b[8:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 4 bytes.
|
|
||||||
for len(b) >= 4 {
|
|
||||||
v := binary.LittleEndian.Uint32(b)
|
|
||||||
binary.LittleEndian.PutUint32(b, v^key)
|
|
||||||
b = b[4:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// xor remaining bytes.
|
|
||||||
for i := range b {
|
|
||||||
b[i] ^= byte(key)
|
|
||||||
key = bits.RotateLeft32(key, -8)
|
|
||||||
}
|
|
||||||
|
|
||||||
return key
|
|
||||||
}
|
|
@ -8,7 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultAllocator = NewAllocator()
|
var DefaultAllocator = NewAllocator()
|
||||||
|
|
||||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
type Allocator struct {
|
type Allocator struct {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math/rand"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(fastrand.Int())
|
msb(rand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,9 +13,9 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return defaultAllocator.Get(size)
|
return DefaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Put(buf []byte) error {
|
func Put(buf []byte) error {
|
||||||
return defaultAllocator.Put(buf)
|
return DefaultAllocator.Put(buf)
|
||||||
}
|
}
|
||||||
|
@ -1,7 +0,0 @@
|
|||||||
package pool
|
|
||||||
|
|
||||||
import "github.com/sagernet/sing/common/buf"
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
buf.DefaultAllocator = defaultAllocator
|
|
||||||
}
|
|
@ -3,7 +3,6 @@ package structure
|
|||||||
// references: https://github.com/mitchellh/mapstructure
|
// references: https://github.com/mitchellh/mapstructure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -14,11 +13,8 @@ import (
|
|||||||
type Option struct {
|
type Option struct {
|
||||||
TagName string
|
TagName string
|
||||||
WeaklyTypedInput bool
|
WeaklyTypedInput bool
|
||||||
KeyReplacer *strings.Replacer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var DefaultKeyReplacer = strings.NewReplacer("_", "-")
|
|
||||||
|
|
||||||
// Decoder is the core of structure
|
// Decoder is the core of structure
|
||||||
type Decoder struct {
|
type Decoder struct {
|
||||||
option *Option
|
option *Option
|
||||||
@ -53,23 +49,6 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
omitempty := found && omitKey == "omitempty"
|
omitempty := found && omitKey == "omitempty"
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok {
|
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
key = d.option.KeyReplacer.Replace(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _strKey := range src {
|
|
||||||
strKey := _strKey
|
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
strKey = d.option.KeyReplacer.Replace(strKey)
|
|
||||||
}
|
|
||||||
if strings.EqualFold(key, strKey) {
|
|
||||||
value = src[_strKey]
|
|
||||||
ok = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
if omitempty {
|
if omitempty {
|
||||||
continue
|
continue
|
||||||
@ -86,16 +65,9 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
kind := val.Kind()
|
switch val.Kind() {
|
||||||
switch {
|
case reflect.Int:
|
||||||
case isInt(kind):
|
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
case isUint(kind):
|
|
||||||
return d.decodeUint(name, data, val)
|
|
||||||
case isFloat(kind):
|
|
||||||
return d.decodeFloat(name, data, val)
|
|
||||||
}
|
|
||||||
switch kind {
|
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
return d.decodeString(name, data, val)
|
return d.decodeString(name, data, val)
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
@ -113,42 +85,13 @@ func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isInt(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isUint(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isFloat(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case isInt(kind):
|
case kind == reflect.Int:
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
||||||
val.SetInt(int64(dataVal.Uint()))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetInt(int64(dataVal.Float()))
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
@ -167,72 +110,14 @@ func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeUint(name string, data any, val reflect.Value) (err error) {
|
|
||||||
dataVal := reflect.ValueOf(data)
|
|
||||||
kind := dataVal.Kind()
|
|
||||||
switch {
|
|
||||||
case isUint(kind):
|
|
||||||
val.SetUint(dataVal.Uint())
|
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetUint(uint64(dataVal.Int()))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetUint(uint64(dataVal.Float()))
|
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
|
||||||
var i uint64
|
|
||||||
i, err = strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
|
|
||||||
if err == nil {
|
|
||||||
val.SetUint(i)
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf(
|
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
|
||||||
name, val.Type(), dataVal.Type(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeFloat(name string, data any, val reflect.Value) (err error) {
|
|
||||||
dataVal := reflect.ValueOf(data)
|
|
||||||
kind := dataVal.Kind()
|
|
||||||
switch {
|
|
||||||
case isFloat(kind):
|
|
||||||
val.SetFloat(dataVal.Float())
|
|
||||||
case isUint(kind):
|
|
||||||
val.SetFloat(float64(dataVal.Uint()))
|
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetFloat(float64(dataVal.Int()))
|
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
|
||||||
var i float64
|
|
||||||
i, err = strconv.ParseFloat(dataVal.String(), val.Type().Bits())
|
|
||||||
if err == nil {
|
|
||||||
val.SetFloat(i)
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf(
|
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
|
||||||
name, val.Type(), dataVal.Type(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.String:
|
case kind == reflect.String:
|
||||||
val.SetString(dataVal.String())
|
val.SetString(dataVal.String())
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatFloat(dataVal.Float(), 'E', -1, dataVal.Type().Bits()))
|
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -248,10 +133,8 @@ func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err erro
|
|||||||
switch {
|
switch {
|
||||||
case kind == reflect.Bool:
|
case kind == reflect.Bool:
|
||||||
val.SetBool(dataVal.Bool())
|
val.SetBool(dataVal.Bool())
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
val.SetBool(dataVal.Int() != 0)
|
val.SetBool(dataVal.Int() != 0)
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -266,17 +149,6 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
if dataVal.Kind() == reflect.String && valElemType.Kind() == reflect.Uint8 { // from encoding/json
|
|
||||||
s := []byte(dataVal.String())
|
|
||||||
b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
|
|
||||||
n, err := base64.StdEncoding.Decode(b, s)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("try decode '%s' by base64 error: %w", name, err)
|
|
||||||
}
|
|
||||||
val.SetBytes(b[:n])
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if dataVal.Kind() != reflect.Slice {
|
if dataVal.Kind() != reflect.Slice {
|
||||||
return fmt.Errorf("'%s' is not a slice", name)
|
return fmt.Errorf("'%s' is not a slice", name)
|
||||||
}
|
}
|
||||||
@ -481,18 +353,12 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
if !rawMapVal.IsValid() {
|
if !rawMapVal.IsValid() {
|
||||||
// Do a slower search by iterating over each key and
|
// Do a slower search by iterating over each key and
|
||||||
// doing case-insensitive search.
|
// doing case-insensitive search.
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
fieldName = d.option.KeyReplacer.Replace(fieldName)
|
|
||||||
}
|
|
||||||
for dataValKey := range dataValKeys {
|
for dataValKey := range dataValKeys {
|
||||||
mK, ok := dataValKey.Interface().(string)
|
mK, ok := dataValKey.Interface().(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
// Not a string key
|
// Not a string key
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
mK = d.option.KeyReplacer.Replace(mK)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.EqualFold(mK, fieldName) {
|
if strings.EqualFold(mK, fieldName) {
|
||||||
rawMapKey = dataValKey
|
rawMapKey = dataValKey
|
||||||
|
@ -137,45 +137,3 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceNilValue(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": 1,
|
|
||||||
"bar": []any{"bar", nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
goal := &BazSlice{
|
|
||||||
Foo: 1,
|
|
||||||
Bar: []string{"bar", ""},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &BazSlice{}
|
|
||||||
err := weakTypeDecoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, goal.Bar, s.Bar)
|
|
||||||
|
|
||||||
s = &BazSlice{}
|
|
||||||
err = decoder.Decode(rawMap, s)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Bar []map[string]any `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Nil(t, s.Bar[1])
|
|
||||||
|
|
||||||
ss := &struct {
|
|
||||||
Bar []Baz `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err = decoder.Decode(rawMap, ss)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
func MustOK[T any](result T, ok bool) T {
|
|
||||||
if ok {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
panic("operation failed")
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
|
|
||||||
result := make([]T, 0)
|
|
||||||
for _, t := range tSlice {
|
|
||||||
if filter(t) {
|
|
||||||
result = append(result, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func ToStringSlice(value any) ([]string, error) {
|
|
||||||
strArr := make([]string, 0)
|
|
||||||
switch reflect.TypeOf(value).Kind() {
|
|
||||||
case reflect.Slice, reflect.Array:
|
|
||||||
origin := reflect.ValueOf(value)
|
|
||||||
for i := 0; i < origin.Len(); i++ {
|
|
||||||
item := fmt.Sprintf("%v", origin.Index(i))
|
|
||||||
strArr = append(strArr, item)
|
|
||||||
}
|
|
||||||
case reflect.String:
|
|
||||||
strArr = append(strArr, fmt.Sprintf("%v", value))
|
|
||||||
default:
|
|
||||||
return nil, errors.New("value format error, must be string or array")
|
|
||||||
}
|
|
||||||
return strArr, nil
|
|
||||||
}
|
|
@ -2,22 +2,15 @@ package utils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type fastRandReader struct{}
|
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
||||||
|
|
||||||
func (r fastRandReader) Read(p []byte) (int, error) {
|
|
||||||
return fastrand.Read(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
var UnsafeUUIDGenerator = uuid.NewGenWithOptions(uuid.WithRandomReader(fastRandReader{}))
|
|
||||||
|
|
||||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
func UUIDMap(str string) (uuid.UUID, error) {
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
u, err := uuid.FromString(str)
|
u, err := uuid.FromString(str)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return UnsafeUUIDGenerator.NewV5(uuid.Nil, str), nil
|
return uuid.NewV5(uuidNamespace, str), nil
|
||||||
}
|
}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
@ -11,8 +10,16 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
func bindControl(ifaceIdx int) controlFn {
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
|
||||||
|
func bindControl(ifaceIdx int, chain controlFn) controlFn {
|
||||||
|
return func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
return
|
return
|
||||||
@ -42,7 +49,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.A
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,10 +59,6 @@ func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
lc.Control = bindControl(ifaceObj.Index, lc.Control)
|
||||||
return address, nil
|
return address, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
return network
|
|
||||||
}
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
@ -9,8 +8,16 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
func bindControl(ifaceName string) controlFn {
|
type controlFn = func(network, address string, c syscall.RawConn) error
|
||||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
|
||||||
|
func bindControl(ifaceName string, chain controlFn) controlFn {
|
||||||
|
return func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
return
|
return
|
||||||
@ -30,17 +37,13 @@ func bindControl(ifaceName string) controlFn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
||||||
addControlToDialer(dialer, bindControl(ifaceName))
|
dialer.Control = bindControl(ifaceName, dialer.Control)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
||||||
addControlToListenConfig(lc, bindControl(ifaceName))
|
lc.Control = bindControl(ifaceName, lc.Control)
|
||||||
|
|
||||||
return address, nil
|
return address, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
return network
|
|
||||||
}
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
//go:build !linux && !darwin && !windows
|
//go:build !linux && !darwin
|
||||||
|
|
||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
@ -91,13 +91,3 @@ func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, add
|
|||||||
|
|
||||||
return addr.String(), nil
|
return addr.String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
// fix bindIfaceToListenConfig() force bind to an ipv4 address
|
|
||||||
if !strings.HasSuffix(network, "4") &&
|
|
||||||
!strings.HasSuffix(network, "6") &&
|
|
||||||
addr.Unmap().Is6() {
|
|
||||||
network += "6"
|
|
||||||
}
|
|
||||||
return network
|
|
||||||
}
|
|
||||||
|
@ -1,92 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
//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)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
//go:build go1.20
|
|
||||||
|
|
||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
func addControlToDialer(d *net.Dialer, fn controlFn) {
|
|
||||||
ld := *d
|
|
||||||
d.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
|
||||||
switch {
|
|
||||||
case ld.ControlContext != nil:
|
|
||||||
if err = ld.ControlContext(ctx, network, address, c); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
case ld.Control != nil:
|
|
||||||
if err = ld.Control(network, address, c); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fn(ctx, network, address, c)
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,28 +2,27 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
"go.uber.org/atomic"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error)
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
dialMux sync.Mutex
|
dialMux sync.Mutex
|
||||||
actualSingleStackDialContext = serialSingleStackDialContext
|
actualSingleDialContext = singleDialContext
|
||||||
actualDualStackDialContext = serialDualStackDialContext
|
actualDualStackDialContext = dualStackDialContext
|
||||||
tcpConcurrent = false
|
tcpConcurrent = false
|
||||||
fallbackTimeout = 300 * time.Millisecond
|
DisableIPv6 = false
|
||||||
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
|
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
||||||
)
|
)
|
||||||
|
|
||||||
func applyOptions(options ...Option) *option {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
routingMark: int(DefaultRoutingMark.Load()),
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
@ -37,12 +36,6 @@ func applyOptions(options ...Option) *option {
|
|||||||
o(opt)
|
o(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
return opt
|
|
||||||
}
|
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
|
||||||
opt := applyOptions(options...)
|
|
||||||
|
|
||||||
if opt.network == 4 || opt.network == 6 {
|
if opt.network == 4 || opt.network == 6 {
|
||||||
if strings.Contains(network, "tcp") {
|
if strings.Contains(network, "tcp") {
|
||||||
network = "tcp"
|
network = "tcp"
|
||||||
@ -53,23 +46,29 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
network = fmt.Sprintf("%s%d", network, opt.network)
|
network = fmt.Sprintf("%s%d", network, opt.network)
|
||||||
}
|
}
|
||||||
|
|
||||||
ips, port, err := parseAddr(ctx, network, address, opt.resolver)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleStackDialContext(ctx, network, ips, port, opt)
|
return actualSingleDialContext(ctx, network, address, opt)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return actualDualStackDialContext(ctx, network, ips, port, opt)
|
return actualDualStackDialContext(ctx, network, address, opt)
|
||||||
default:
|
default:
|
||||||
return nil, ErrorInvalidedNetworkStack
|
return nil, ErrorInvalidedNetworkStack
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
|
||||||
cfg := applyOptions(options...)
|
cfg := &option{
|
||||||
|
interfaceName: DefaultInterface.Load(),
|
||||||
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range DefaultOptions {
|
||||||
|
o(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range options {
|
||||||
|
o(cfg)
|
||||||
|
}
|
||||||
|
|
||||||
lc := &net.ListenConfig{}
|
lc := &net.ListenConfig{}
|
||||||
if cfg.interfaceName != "" {
|
if cfg.interfaceName != "" {
|
||||||
@ -89,40 +88,26 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetTcpConcurrent(concurrent bool) {
|
func SetDial(concurrent bool) {
|
||||||
dialMux.Lock()
|
dialMux.Lock()
|
||||||
defer dialMux.Unlock()
|
|
||||||
tcpConcurrent = concurrent
|
tcpConcurrent = concurrent
|
||||||
if concurrent {
|
if concurrent {
|
||||||
actualSingleStackDialContext = concurrentSingleStackDialContext
|
actualSingleDialContext = concurrentSingleDialContext
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
} else {
|
} else {
|
||||||
actualSingleStackDialContext = serialSingleStackDialContext
|
actualSingleDialContext = singleDialContext
|
||||||
actualDualStackDialContext = serialDualStackDialContext
|
actualDualStackDialContext = dualStackDialContext
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dialMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetTcpConcurrent() bool {
|
func GetDial() bool {
|
||||||
dialMux.Lock()
|
|
||||||
defer dialMux.Unlock()
|
|
||||||
return tcpConcurrent
|
return tcpConcurrent
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
address := net.JoinHostPort(destination.String(), port)
|
dialer := &net.Dialer{}
|
||||||
|
|
||||||
netDialer := opt.netDialer
|
|
||||||
switch netDialer.(type) {
|
|
||||||
case nil:
|
|
||||||
netDialer = &net.Dialer{}
|
|
||||||
case *net.Dialer:
|
|
||||||
_netDialer := *netDialer.(*net.Dialer)
|
|
||||||
netDialer = &_netDialer // make a copy
|
|
||||||
default:
|
|
||||||
return netDialer.DialContext(ctx, network, address)
|
|
||||||
}
|
|
||||||
|
|
||||||
dialer := netDialer.(*net.Dialer)
|
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -131,213 +116,287 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
if opt.routingMark != 0 {
|
if opt.routingMark != 0 {
|
||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
if opt.tfo {
|
|
||||||
return dialTFO(ctx, *dialer, network, address)
|
if DisableIPv6 && destination.Is6() {
|
||||||
|
return nil, ErrorDisableIPv6
|
||||||
}
|
}
|
||||||
return dialer.DialContext(ctx, network, address)
|
|
||||||
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func serialSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
return serialDialContext(ctx, network, ips, port, opt)
|
host, port, err := net.SplitHostPort(address)
|
||||||
}
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
func serialDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
return dualStackDialContext(ctx, serialDialContext, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentSingleStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
return parallelDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDualStackDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
if opt.prefer != 4 && opt.prefer != 6 {
|
|
||||||
return parallelDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
}
|
||||||
return dualStackDialContext(ctx, parallelDialContext, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func dualStackDialContext(ctx context.Context, dialFn dialFunc, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
ipv4s, ipv6s := sortationAddr(ips)
|
|
||||||
preferIPVersion := opt.prefer
|
|
||||||
|
|
||||||
fallbackTicker := time.NewTicker(fallbackTimeout)
|
|
||||||
defer fallbackTicker.Stop()
|
|
||||||
results := make(chan dialResult)
|
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
racer := func(ips []netip.Addr, isPrimary bool) {
|
|
||||||
result := dialResult{isPrimary: isPrimary}
|
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, direct bool, ipv6 bool) {
|
||||||
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil && result.error == nil {
|
if result.Conn != nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
result.Conn, result.error = dialFn(ctx, network, ips, port, opt)
|
|
||||||
}
|
var ip netip.Addr
|
||||||
go racer(ipv4s, preferIPVersion != 6)
|
if ipv6 {
|
||||||
go racer(ipv6s, preferIPVersion != 4)
|
if !direct {
|
||||||
var fallback dialResult
|
ip, result.error = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
var errs []error
|
|
||||||
for i := 0; i < 2; {
|
|
||||||
select {
|
|
||||||
case <-fallbackTicker.C:
|
|
||||||
if fallback.error == nil && fallback.Conn != nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
case res := <-results:
|
|
||||||
i++
|
|
||||||
if res.error == nil {
|
|
||||||
if res.isPrimary {
|
|
||||||
return res.Conn, nil
|
|
||||||
}
|
|
||||||
fallback = res
|
|
||||||
} else {
|
} else {
|
||||||
if res.isPrimary {
|
ip, result.error = resolver.ResolveIPv6(host)
|
||||||
errs = append([]error{fmt.Errorf("connect failed: %w", res.error)}, errs...)
|
}
|
||||||
} else {
|
} else {
|
||||||
errs = append(errs, fmt.Errorf("connect failed: %w", res.error))
|
if !direct {
|
||||||
}
|
ip, result.error = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, result.error = resolver.ResolveIPv4(host)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if result.error != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.resolved = true
|
||||||
|
|
||||||
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
if fallback.error == nil && fallback.Conn != nil {
|
|
||||||
return fallback.Conn, nil
|
go startRacer(ctx, network+"4", host, opt.direct, false)
|
||||||
|
go startRacer(ctx, network+"6", host, opt.direct, 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():
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil, errorsJoin(errs...)
|
|
||||||
|
return nil, errors.New("dual stack tcp shake hands failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
func parallelDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
if len(ips) == 0 {
|
host, port, err := net.SplitHostPort(address)
|
||||||
return nil, ErrorNoIpAddress
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
results := make(chan dialResult)
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIP(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
racer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
result := dialResult{isPrimary: true, ip: ip}
|
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() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil && result.error == nil {
|
if result.Conn != nil {
|
||||||
_ = result.Conn.Close()
|
_ = result.Conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
if strings.Contains(network, "tcp") {
|
||||||
|
network = "tcp"
|
||||||
|
} else {
|
||||||
|
network = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.Is6() {
|
||||||
|
network += "6"
|
||||||
|
if opt.prefer != 4 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.Is4() {
|
||||||
|
network += "4"
|
||||||
|
if opt.prefer != 6 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if result.isPrimary {
|
||||||
|
preferCount.Add(1)
|
||||||
|
}
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
go racer(ctx, ip)
|
go tcpRacer(ctx, ip)
|
||||||
}
|
|
||||||
var errs []error
|
|
||||||
for i := 0; i < len(ips); i++ {
|
|
||||||
res := <-results
|
|
||||||
if res.error == nil {
|
|
||||||
return res.Conn, nil
|
|
||||||
}
|
|
||||||
errs = append(errs, res.error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(errs) > 0 {
|
connCount := len(ips)
|
||||||
return nil, errorsJoin(errs...)
|
var fallback dialResult
|
||||||
}
|
for i := 0; i < connCount; i++ {
|
||||||
return nil, os.ErrDeadlineExceeded
|
select {
|
||||||
}
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
if res.isPrimary {
|
||||||
if len(ips) == 0 {
|
return res.Conn, nil
|
||||||
return nil, ErrorNoIpAddress
|
} else {
|
||||||
}
|
if !fallback.done || fallback.error != nil {
|
||||||
var errs []error
|
fallback = res
|
||||||
for _, ip := range ips {
|
}
|
||||||
if conn, err := dialContext(ctx, network, ip, port, opt); err == nil {
|
}
|
||||||
return conn, nil
|
} else {
|
||||||
} else {
|
if res.isPrimary {
|
||||||
errs = append(errs, err)
|
preferCount.Add(-1)
|
||||||
|
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, errorsJoin(errs...)
|
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||||
}
|
}
|
||||||
|
|
||||||
type dialResult struct {
|
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
ip netip.Addr
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
isPrimary bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseAddr(ctx context.Context, network, address string, preferResolver resolver.Resolver) ([]netip.Addr, string, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "-1", err
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ip netip.Addr
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialContext(ctx, network, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
return concurrentIPv4DialContext(ctx, network, address, opt)
|
||||||
|
default:
|
||||||
|
return concurrentIPv6DialContext(ctx, network, address, opt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
switch network {
|
if !opt.direct {
|
||||||
case "tcp4", "udp4":
|
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||||
if preferResolver == nil {
|
} else {
|
||||||
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
ips, err = resolver.ResolveAllIPv4(host)
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPv4WithResolver(ctx, host, preferResolver)
|
|
||||||
}
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
if preferResolver == nil {
|
|
||||||
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPv6WithResolver(ctx, host, preferResolver)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if preferResolver == nil {
|
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.LookupIPWithResolver(ctx, host, preferResolver)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "-1", fmt.Errorf("dns resolve failed: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
for i, ip := range ips {
|
|
||||||
if ip.Is4In6() {
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
ips[i] = ip.Unmap()
|
}
|
||||||
}
|
|
||||||
|
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
return ips, port, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func sortationAddr(ips []netip.Addr) (ipv4s, ipv6s []netip.Addr) {
|
var ips []netip.Addr
|
||||||
for _, v := range ips {
|
if !opt.direct {
|
||||||
if v.Is4() { // 4in6 parse was in parseAddr
|
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||||
ipv4s = append(ipv4s, v)
|
} else {
|
||||||
} else {
|
ips, err = resolver.ResolveAllIPv6(host)
|
||||||
ipv6s = append(ipv6s, v)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type Dialer struct {
|
if err != nil {
|
||||||
opt option
|
return nil, err
|
||||||
}
|
|
||||||
|
|
||||||
func (d Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
return DialContext(ctx, network, address, WithOption(d.opt))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
|
||||||
opt := WithOption(d.opt)
|
|
||||||
if rAddrPort.Addr().Unmap().IsLoopback() {
|
|
||||||
// avoid "The requested address is not valid in its context."
|
|
||||||
opt = WithInterface("")
|
|
||||||
}
|
}
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDialer(options ...Option) Dialer {
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
opt := applyOptions(options...)
|
|
||||||
return Dialer{opt: *opt}
|
|
||||||
}
|
}
|
||||||
|
@ -1,18 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrorNoIpAddress = errors.New("no ip address")
|
|
||||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
|
||||||
)
|
|
||||||
|
|
||||||
func errorsJoin(errs ...error) error {
|
|
||||||
// compatibility with golang<1.20
|
|
||||||
// maybe use errors.Join(errs...) is better after we drop the old version's support
|
|
||||||
return E.Errors(errs...)
|
|
||||||
}
|
|
@ -3,35 +3,39 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ netip.Addr) {
|
||||||
addControlToDialer(dialer, bindMarkToControl(mark))
|
dialer.Control = bindMarkToControl(mark, dialer.Control)
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, _ string) {
|
||||||
addControlToListenConfig(lc, bindMarkToControl(mark))
|
lc.Control = bindMarkToControl(mark, lc.Control)
|
||||||
}
|
}
|
||||||
|
|
||||||
func bindMarkToControl(mark int) controlFn {
|
func bindMarkToControl(mark int, chain controlFn) controlFn {
|
||||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
return func(network, address string, c syscall.RawConn) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if err == nil && chain != nil {
|
||||||
|
err = chain(network, address, c)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
addrPort, err := netip.ParseAddrPort(address)
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var innerErr error
|
return c.Control(func(fd uintptr) {
|
||||||
err = c.Control(func(fd uintptr) {
|
switch network {
|
||||||
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
case "tcp4", "udp4":
|
||||||
|
_ = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
_ = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
if innerErr != nil {
|
|
||||||
err = innerErr
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -15,19 +10,13 @@ var (
|
|||||||
DefaultRoutingMark = atomic.NewInt32(0)
|
DefaultRoutingMark = atomic.NewInt32(0)
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetDialer interface {
|
|
||||||
DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type option struct {
|
type option struct {
|
||||||
interfaceName string
|
interfaceName string
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
|
direct bool
|
||||||
network int
|
network int
|
||||||
prefer int
|
prefer int
|
||||||
tfo bool
|
|
||||||
resolver resolver.Resolver
|
|
||||||
netDialer NetDialer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -50,9 +39,9 @@ func WithRoutingMark(mark int) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithResolver(r resolver.Resolver) Option {
|
func WithDirect() Option {
|
||||||
return func(opt *option) {
|
return func(opt *option) {
|
||||||
opt.resolver = r
|
opt.direct = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,21 +66,3 @@ func WithOnlySingleStack(isIPv4 bool) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithTFO(tfo bool) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.tfo = tfo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithNetDialer(netDialer NetDialer) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.netDialer = netDialer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithOption(o option) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
*opt = o
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
@ -11,10 +10,18 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
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)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
return c.Control(func(fd uintptr) {
|
||||||
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
|
||||||
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
@ -9,9 +8,17 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
func addrReuseToListenConfig(lc *net.ListenConfig) {
|
||||||
addControlToListenConfig(lc, func(ctx context.Context, network, address string, c syscall.RawConn) error {
|
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)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
return c.Control(func(fd uintptr) {
|
||||||
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
windows.SetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_REUSEADDR, 1)
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,123 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/sagernet/tfo-go"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type tfoConn struct {
|
|
||||||
net.Conn
|
|
||||||
closed bool
|
|
||||||
dialed chan bool
|
|
||||||
cancel context.CancelFunc
|
|
||||||
ctx context.Context
|
|
||||||
dialFn func(ctx context.Context, earlyData []byte) (net.Conn, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) Dial(earlyData []byte) (err error) {
|
|
||||||
c.Conn, err = c.dialFn(c.ctx, earlyData)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.dialed <- true
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) Read(b []byte) (n int, err error) {
|
|
||||||
if c.closed {
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
}
|
|
||||||
if c.Conn == nil {
|
|
||||||
select {
|
|
||||||
case <-c.ctx.Done():
|
|
||||||
return 0, io.ErrUnexpectedEOF
|
|
||||||
case <-c.dialed:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return c.Conn.Read(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) Write(b []byte) (n int, err error) {
|
|
||||||
if c.closed {
|
|
||||||
return 0, io.ErrClosedPipe
|
|
||||||
}
|
|
||||||
if c.Conn == nil {
|
|
||||||
if err := c.Dial(b); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return len(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) Close() error {
|
|
||||||
c.closed = true
|
|
||||||
c.cancel()
|
|
||||||
if c.Conn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) LocalAddr() net.Addr {
|
|
||||||
if c.Conn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) RemoteAddr() net.Addr {
|
|
||||||
if c.Conn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn.RemoteAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) SetDeadline(t time.Time) error {
|
|
||||||
if err := c.SetReadDeadline(t); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return c.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) SetReadDeadline(t time.Time) error {
|
|
||||||
if c.Conn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
if c.Conn == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) Upstream() any {
|
|
||||||
if c.Conn == nil { // ensure return a nil interface not an interface with nil value
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return c.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) NeedHandshake() bool {
|
|
||||||
return c.Conn == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
|
||||||
return &tfoConn{
|
|
||||||
dialed: make(chan bool, 1),
|
|
||||||
cancel: cancel,
|
|
||||||
ctx: ctx,
|
|
||||||
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
|
||||||
return dialer.DialContext(ctx, network, address, earlyData)
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
@ -6,38 +6,15 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cmd"
|
"github.com/Dreamacro/clash/common/cmd"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/ebpf/redir"
|
"github.com/Dreamacro/clash/component/ebpf/redir"
|
||||||
"github.com/Dreamacro/clash/component/ebpf/tc"
|
"github.com/Dreamacro/clash/component/ebpf/tc"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/sagernet/netlink"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetAutoDetectInterface() (string, error) {
|
|
||||||
routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, route := range routes {
|
|
||||||
if route.Dst == nil {
|
|
||||||
lk, err := netlink.LinkByIndex(route.LinkIndex)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if lk.Type() == "tuntap" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return lk.Attrs().Name, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", fmt.Errorf("interface not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTcEBpfProgram new redirect to tun ebpf program
|
// NewTcEBpfProgram new redirect to tun ebpf program
|
||||||
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
||||||
tunIface, err := netlink.LinkByName(tunName)
|
tunIface, err := netlink.LinkByName(tunName)
|
||||||
|
@ -15,7 +15,3 @@ func NewTcEBpfProgram(_ []string, _ string) (*TcEBpfProgram, error) {
|
|||||||
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
||||||
return nil, fmt.Errorf("system not supported")
|
return nil, fmt.Errorf("system not supported")
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetAutoDetectInterface() (string, error) {
|
|
||||||
return "", fmt.Errorf("system not supported")
|
|
||||||
}
|
|
||||||
|
@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
"github.com/cilium/ebpf"
|
"github.com/cilium/ebpf"
|
||||||
"github.com/cilium/ebpf/rlimit"
|
"github.com/cilium/ebpf/rlimit"
|
||||||
"github.com/sagernet/netlink"
|
"github.com/vishvananda/netlink"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
||||||
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -134,6 +134,5 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
//
|
|
||||||
//go:embed bpf_bpfeb.o
|
//go:embed bpf_bpfeb.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -134,6 +134,5 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
//
|
|
||||||
//go:embed bpf_bpfel.o
|
//go:embed bpf_bpfel.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -115,6 +115,5 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
//
|
|
||||||
//go:embed bpf_bpfeb.o
|
//go:embed bpf_bpfeb.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -28,9 +28,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -115,6 +115,5 @@ func _BpfClose(closers ...io.Closer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do not access this directly.
|
// Do not access this directly.
|
||||||
//
|
|
||||||
//go:embed bpf_bpfel.o
|
//go:embed bpf_bpfel.o
|
||||||
var _BpfBytes []byte
|
var _BpfBytes []byte
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
|
|
||||||
"github.com/cilium/ebpf"
|
"github.com/cilium/ebpf"
|
||||||
"github.com/cilium/ebpf/rlimit"
|
"github.com/cilium/ebpf/rlimit"
|
||||||
"github.com/sagernet/netlink"
|
"github.com/vishvananda/netlink"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
@ -73,7 +73,7 @@ func (m *memoryStore) FlushFakeIP() error {
|
|||||||
|
|
||||||
func newMemoryStore(size int) *memoryStore {
|
func newMemoryStore(size int) *memoryStore {
|
||||||
return &memoryStore{
|
return &memoryStore{
|
||||||
cacheIP: cache.New[string, netip.Addr](cache.WithSize[string, netip.Addr](size)),
|
cacheIP: cache.NewLRUCache[string, netip.Addr](cache.WithSize[string, netip.Addr](size)),
|
||||||
cacheHost: cache.New[netip.Addr, string](cache.WithSize[netip.Addr, string](size)),
|
cacheHost: cache.NewLRUCache[netip.Addr, string](cache.WithSize[netip.Addr, string](size)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,6 @@ package fakeip
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
@ -27,7 +26,7 @@ type store interface {
|
|||||||
FlushFakeIP() error
|
FlushFakeIP() error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pool is an implementation about fake ip generator without storage
|
// Pool is a implementation about fake ip generator without storage
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
gateway netip.Addr
|
gateway netip.Addr
|
||||||
first netip.Addr
|
first netip.Addr
|
||||||
@ -35,7 +34,7 @@ type Pool struct {
|
|||||||
offset netip.Addr
|
offset netip.Addr
|
||||||
cycle bool
|
cycle bool
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
host *trie.DomainTrie[struct{}]
|
host *trie.DomainTrie[bool]
|
||||||
ipnet *netip.Prefix
|
ipnet *netip.Prefix
|
||||||
store store
|
store store
|
||||||
}
|
}
|
||||||
@ -44,9 +43,6 @@ type Pool struct {
|
|||||||
func (p *Pool) Lookup(host string) netip.Addr {
|
func (p *Pool) Lookup(host string) netip.Addr {
|
||||||
p.mux.Lock()
|
p.mux.Lock()
|
||||||
defer p.mux.Unlock()
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
// RFC4343: DNS Case Insensitive, we SHOULD return result with all cases.
|
|
||||||
host = strings.ToLower(host)
|
|
||||||
if ip, exist := p.store.GetByHost(host); exist {
|
if ip, exist := p.store.GetByHost(host); exist {
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
@ -154,7 +150,7 @@ func (p *Pool) restoreState() {
|
|||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
IPNet *netip.Prefix
|
IPNet *netip.Prefix
|
||||||
Host *trie.DomainTrie[struct{}]
|
Host *trie.DomainTrie[bool]
|
||||||
|
|
||||||
// Size sets the maximum number of entries in memory
|
// Size sets the maximum number of entries in memory
|
||||||
// and does not work if Persistence is true
|
// and does not work if Persistence is true
|
||||||
@ -170,7 +166,7 @@ func New(options Options) (*Pool, error) {
|
|||||||
var (
|
var (
|
||||||
hostAddr = options.IPNet.Masked().Addr()
|
hostAddr = options.IPNet.Masked().Addr()
|
||||||
gateway = hostAddr.Next()
|
gateway = hostAddr.Next()
|
||||||
first = gateway.Next().Next().Next() // default start with 198.18.0.4
|
first = gateway.Next().Next()
|
||||||
last = nnip.UnMasked(*options.IPNet)
|
last = nnip.UnMasked(*options.IPNet)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -62,16 +62,16 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
||||||
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 4})))
|
||||||
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 6})))
|
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,41 +90,20 @@ func TestPool_BasicV6(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
||||||
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805"))
|
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
||||||
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8806")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_Case_Insensitive(t *testing.T) {
|
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
|
||||||
pools, tempfile, err := createPools(Options{
|
|
||||||
IPNet: &ipnet,
|
|
||||||
Size: 10,
|
|
||||||
})
|
|
||||||
assert.Nil(t, err)
|
|
||||||
defer os.Remove(tempfile)
|
|
||||||
|
|
||||||
for _, pool := range pools {
|
|
||||||
first := pool.Lookup("foo.com")
|
|
||||||
last := pool.Lookup("Foo.Com")
|
|
||||||
foo, exist := pool.LookBack(last)
|
|
||||||
|
|
||||||
assert.Equal(t, first, pool.Lookup("Foo.Com"))
|
|
||||||
assert.Equal(t, pool.Lookup("fOo.cOM"), first)
|
|
||||||
assert.True(t, exist)
|
|
||||||
assert.Equal(t, foo, "foo.com")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPool_CycleUsed(t *testing.T) {
|
func TestPool_CycleUsed(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.16/28")
|
ipnet := netip.MustParsePrefix("192.168.0.16/28")
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
@ -137,7 +116,7 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
for _, pool := range pools {
|
for _, pool := range pools {
|
||||||
foo := pool.Lookup("foo.com")
|
foo := pool.Lookup("foo.com")
|
||||||
bar := pool.Lookup("bar.com")
|
bar := pool.Lookup("bar.com")
|
||||||
for i := 0; i < 9; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
pool.Lookup(fmt.Sprintf("%d.com", i))
|
pool.Lookup(fmt.Sprintf("%d.com", i))
|
||||||
}
|
}
|
||||||
baz := pool.Lookup("baz.com")
|
baz := pool.Lookup("baz.com")
|
||||||
@ -149,8 +128,8 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_Skip(t *testing.T) {
|
func TestPool_Skip(t *testing.T) {
|
||||||
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
ipnet := netip.MustParsePrefix("192.168.0.1/29")
|
||||||
tree := trie.New[struct{}]()
|
tree := trie.New[bool]()
|
||||||
tree.Insert("example.com", struct{}{})
|
tree.Insert("example.com", true)
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
Size: 10,
|
Size: 10,
|
||||||
@ -219,8 +198,8 @@ func TestPool_Clone(t *testing.T) {
|
|||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
|
|
||||||
newPool, _ := New(Options{
|
newPool, _ := New(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user