Compare commits
3 Commits
v1.14.4
...
revert-324
Author | SHA1 | Date | |
---|---|---|---|
95564f1ae6 | |||
de6d32a9d5 | |||
5616d9dc40 |
82
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
82
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,82 +0,0 @@
|
|||||||
name: Bug report
|
|
||||||
description: Create a report to help us improve
|
|
||||||
title: "[Bug] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
确保你使用的是**本仓库**最新的的 clash 或 clash Alpha 版本
|
|
||||||
Ensure you are using the latest version of Clash or Clash Premium from **this repository**.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
|
||||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
"
|
|
||||||
required: false
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
I have searched on the [issue tracker](……/) for a related issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经使用 Alpha 分支版本测试过,问题依旧存在
|
|
||||||
I have tested using the dev branch, and the issue still exists.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
|
||||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Clash version
|
|
||||||
description: "use `clash -v`"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: os
|
|
||||||
attributes:
|
|
||||||
label: What OS are you seeing the problem on?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- macOS
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- OpenBSD/FreeBSD
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: yaml
|
|
||||||
label: "Clash config"
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash core 配置文件,请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等)
|
|
||||||
Paste the Clash core configuration file below, please make sure that there is no sensitive information in the configuration file (e.g., server address/url, password, port)
|
|
||||||
"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: shell
|
|
||||||
label: Clash log
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
"
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
validations:
|
|
||||||
required: true
|
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Feature request
|
|
||||||
description: Suggest an idea for this project
|
|
||||||
title: "[Feature] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
|
||||||
I have searched on the [issue tracker](……/) for a related feature request.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法找到这个功能
|
|
||||||
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什麽?
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Possible Solution
|
|
||||||
description: "
|
|
||||||
此项非必须,但是如果你有想法的话欢迎提出。
|
|
||||||
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
|
||||||
"
|
|
1
.github/genReleaseNote.sh
vendored
1
.github/genReleaseNote.sh
vendored
@ -1 +0,0 @@
|
|||||||
git log --pretty=format:"* %s by @%an" v1.14.x..v1.14.y | sort -f | uniq > release.md
|
|
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
|
|
35
.github/rename-cgo.sh
vendored
35
.github/rename-cgo.sh
vendored
@ -1,35 +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 =~ "clash.meta-linux-arm-5" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv5-cgo
|
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv6-cgo
|
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv7-cgo
|
|
||||||
elif [[ $FILENAME =~ "linux" ]];then
|
|
||||||
echo "rename linux $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
elif [[ $FILENAME =~ "android" ]];then
|
|
||||||
echo "rename android $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
else echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
22
.github/workflows/build.yaml
vendored
Normal file
22
.github/workflows/build.yaml
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
name: Build All
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '1.19'
|
||||||
|
check-latest: true
|
||||||
|
cache: true
|
||||||
|
- name: Build
|
||||||
|
run: make all
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
354
.github/workflows/build.yml
vendored
354
.github/workflows/build.yml
vendored
@ -1,354 +0,0 @@
|
|||||||
name: Build
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
paths-ignore:
|
|
||||||
- "docs/**"
|
|
||||||
- "README.md"
|
|
||||||
- ".github/ISSUE_TEMPLATE/**"
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.ref }}-${{ github.workflow }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
permissions: write-all
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
job:
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-amd64 linux-amd64-compatible",
|
|
||||||
id: "1",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
|
||||||
id: "2",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
|
||||||
id: "3",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
|
||||||
id: "4",
|
|
||||||
}
|
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
|
||||||
id: "6",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
|
||||||
id: "7",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-arm64 windows-arm32v7",
|
|
||||||
id: "8",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
|
||||||
id: "9",
|
|
||||||
}
|
|
||||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
|
||||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
|
||||||
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
|
||||||
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
|
||||||
- { type: "WithCGO", target: "android", id: "11" }
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Meta'}}
|
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
|
||||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
|
||||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
|
||||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
|
||||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
|
||||||
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@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 }}
|
|
15
.github/workflows/delete.yml
vendored
15
.github/workflows/delete.yml
vendored
@ -1,15 +0,0 @@
|
|||||||
name: Delete old workflow runs
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: "0 0 * * SUN"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
del_runs:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Delete workflow runs
|
|
||||||
uses: GitRML/delete-workflow-runs@main
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.AUTH_PAT }}
|
|
||||||
repository: ${{ github.repository }}
|
|
||||||
retain_days: 30
|
|
61
.github/workflows/docker.yaml
vendored
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 }}
|
61
.github/workflows/prerelease.yml
vendored
Normal file
61
.github/workflows/prerelease.yml
vendored
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
name: Prerelease
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '1.19'
|
||||||
|
check-latest: true
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
if: ${{github.ref_name=='Beta'}}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: mknejp/delete-release-assets@v1
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
assets: |
|
||||||
|
*.zip
|
||||||
|
*.gz
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload Alpha
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
36
.github/workflows/release.yaml
vendored
Normal file
36
.github/workflows/release.yaml
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
name: Release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
jobs:
|
||||||
|
Build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: '1.19'
|
||||||
|
check-latest: true
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref }}
|
||||||
|
files: bin/*
|
||||||
|
generate_release_notes: true
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -24,5 +24,4 @@ vendor
|
|||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
/output
|
||||||
.vscode/
|
/.vscode
|
||||||
.fleet/
|
|
21
Dockerfile
21
Dockerfile
@ -1,19 +1,18 @@
|
|||||||
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"
|
||||||
|
|
||||||
@ -22,6 +21,6 @@ RUN apk add --no-cache ca-certificates tzdata iptables
|
|||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/clash/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
COPY --from=builder /clash/clash /clash
|
COPY --from=builder /clash /clash
|
||||||
RUN chmod +x /clash
|
RUN chmod +x /clash
|
||||||
ENTRYPOINT [ "/clash" ]
|
ENTRYPOINT [ "/clash" ]
|
||||||
|
16
Makefile
16
Makefile
@ -1,4 +1,4 @@
|
|||||||
NAME=clash.meta
|
NAME=Clash.Meta
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
@ -47,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
|
||||||
|
89
README.md
89
README.md
@ -29,41 +29,32 @@
|
|||||||
- 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
|
||||||
Configuration examples can be found at [/docs/config.yaml](https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml), while documentation can be found [Clash.Meta Wiki](https://clash-meta.wiki).
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
|
## Advanced usage for this branch
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
You should install [golang](https://go.dev) first.
|
You should install [golang](https://go.dev) first.
|
||||||
|
|
||||||
Then get the source code of Clash.Meta:
|
Then get the source code of Clash.Meta:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
||||||
cd Clash.Meta && go mod download
|
cd Clash.Meta && go mod download
|
||||||
```
|
```
|
||||||
|
|
||||||
If you can't visit github,you should set proxy first:
|
If you can't visit github,you should set proxy first:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you can build it:
|
So now you can build it:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
go build
|
go build
|
||||||
```
|
```
|
||||||
|
|
||||||
If you need gvisor for tun stack, build with:
|
### DNS configuration
|
||||||
|
|
||||||
```shell
|
|
||||||
go build -tags with_gvisor
|
|
||||||
```
|
|
||||||
|
|
||||||
<!-- ## Advanced usage of this fork -->
|
|
||||||
|
|
||||||
<!-- ### DNS configuration
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
@ -73,6 +64,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:
|
||||||
@ -81,7 +73,6 @@ proxy-groups:
|
|||||||
interval: 180
|
interval: 180
|
||||||
lazy: true
|
lazy: true
|
||||||
```
|
```
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
@ -97,12 +88,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:
|
||||||
@ -119,23 +110,21 @@ 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
|
||||||
@ -164,6 +153,7 @@ rules:
|
|||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Proxies configuration
|
### Proxies configuration
|
||||||
|
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
||||||
@ -172,17 +162,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:
|
||||||
@ -194,12 +185,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"
|
||||||
@ -239,8 +232,8 @@ proxies:
|
|||||||
grpc-service-name: grpcname
|
grpc-service-name: grpcname
|
||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `Wireguard`
|
|
||||||
|
|
||||||
|
Support outbound transport protocol `Wireguard`
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "wg"
|
- name: "wg"
|
||||||
@ -255,7 +248,6 @@ proxies:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `Tuic`
|
Support outbound transport protocol `Tuic`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "tuic"
|
- name: "tuic"
|
||||||
@ -274,11 +266,11 @@ proxies:
|
|||||||
# max-udp-relay-packet-size: 1500
|
# max-udp-relay-packet-size: 1500
|
||||||
# fast-open: true
|
# fast-open: true
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
``` -->
|
|
||||||
|
```
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
|
Work on Linux OS who's supported `iptables`
|
||||||
Work on Linux OS which supported `iptables`
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@ -289,15 +281,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
|
### General installation guide for Linux
|
||||||
|
+ Create user given name `clash-meta`
|
||||||
|
|
||||||
- Create user given name `clash-meta`
|
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
||||||
|
|
||||||
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
||||||
|
|
||||||
|
+ Create folder `/etc/Clash-Meta/` as working directory
|
||||||
|
|
||||||
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
|
||||||
|
|
||||||
- Create folder `/etc/Clash-Meta/` as working directory
|
|
||||||
|
|
||||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
Run Meta Kernel by user `clash-meta` as a daemon.
|
||||||
|
|
||||||
@ -323,13 +317,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
|
||||||
@ -340,29 +331,23 @@ $ 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)
|
* [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -4,16 +4,16 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"go.uber.org/atomic"
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
@ -92,7 +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()
|
mapping["tfo"] = p.SupportTFO()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
@ -16,11 +16,11 @@ func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Ad
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(source); err == nil {
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -15,11 +15,11 @@ func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *cont
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
if ip, port, err := parseAddr(conn.LocalAddr().String()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
"github.com/database64128/tfo-go/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -24,12 +24,12 @@ func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions
|
|||||||
for _, addition := range additions {
|
for _, addition := range additions {
|
||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
if ip, port, err := parseAddr(p.InAddr().String()); err == nil {
|
||||||
metadata.InIP = ip
|
metadata.InIP = ip
|
||||||
metadata.InPort = port
|
metadata.InPort = port
|
||||||
}
|
}
|
||||||
|
@ -18,13 +18,22 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
|||||||
addition.Apply(metadata)
|
addition.Apply(metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
remoteAddr := conn.RemoteAddr()
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
// Filter when net.Addr interface is nil
|
||||||
|
if remoteAddr != nil {
|
||||||
|
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
localAddr := conn.LocalAddr()
|
||||||
metadata.InIP = ip
|
// Filter when net.Addr interface is nil
|
||||||
metadata.InPort = port
|
if localAddr != nil {
|
||||||
|
if ip, port, err := parseAddr(localAddr.String()); err == nil {
|
||||||
|
metadata.InIP = ip
|
||||||
|
metadata.InPort = port
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
@ -34,7 +43,7 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|||||||
metadata := &C.Metadata{}
|
metadata := &C.Metadata{}
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.INNER
|
metadata.Type = C.INNER
|
||||||
metadata.DNSMode = C.DNSNormal
|
metadata.DNSMode = C.DNSMapping
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
@ -42,8 +51,6 @@ func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|||||||
if host == "" {
|
if host == "" {
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
if ip, err := netip.ParseAddr(h); err == nil {
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
} else {
|
|
||||||
metadata.Host = h
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
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"
|
||||||
)
|
)
|
||||||
@ -58,19 +57,8 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
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
|
||||||
}
|
}
|
||||||
|
@ -3,12 +3,11 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
@ -19,7 +18,6 @@ type Base struct {
|
|||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
xudp bool
|
|
||||||
tfo bool
|
tfo bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
@ -34,7 +32,12 @@ 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 == "" {
|
||||||
b.id = utils.NewUUIDV6().String()
|
id, err := uuid.NewV6()
|
||||||
|
if err != nil {
|
||||||
|
b.id = b.name
|
||||||
|
} else {
|
||||||
|
b.id = id.String()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return b.id
|
return b.id
|
||||||
@ -47,31 +50,31 @@ func (b *Base) Type() C.AdapterType {
|
|||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return c, C.ErrNotSupport
|
return c, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
return nil, C.ErrNotSupport
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
return nil, C.ErrNotSupport
|
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, C.ErrNotSupport
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
return nil, C.ErrNotSupport
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (b *Base) SupportWithDialer() C.NetWork {
|
func (b *Base) SupportWithDialer() bool {
|
||||||
return C.InvalidNet
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -84,21 +87,11 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportXUDP implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportXUDP() bool {
|
|
||||||
return b.xudp
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportTFO implements C.ProxyAdapter
|
// SupportTFO implements C.ProxyAdapter
|
||||||
func (b *Base) SupportTFO() bool {
|
func (b *Base) SupportTFO() bool {
|
||||||
return b.tfo
|
return b.tfo
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
|
||||||
func (b *Base) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
@ -139,19 +132,13 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.tfo {
|
|
||||||
opts = append(opts, dialer.WithTFO(true))
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||||
DialerProxy string `proxy:"dialer-proxy,omitempty"` // don't apply this option into groups, but can set a group name in a proxy
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@ -159,7 +146,6 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
XUDP bool
|
|
||||||
TFO bool
|
TFO bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
@ -172,7 +158,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,
|
tfo: opt.TFO,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
@ -181,7 +166,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
|
||||||
}
|
}
|
||||||
@ -200,30 +185,13 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *conn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *conn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *conn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
|
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
|
||||||
}
|
|
||||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
adapterName string
|
|
||||||
connID string
|
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -241,16 +209,8 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *packetConn) LocalAddr() net.Addr {
|
|
||||||
lAddr := c.PacketConn.LocalAddr()
|
|
||||||
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
pc = N.NewDeadlinePacketConn(pc) // most conn from outbound can't handle readDeadline correctly
|
|
||||||
}
|
|
||||||
return &packetConn{pc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
|
@ -2,7 +2,6 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
@ -27,14 +26,7 @@ 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) {
|
||||||
// net.UDPConn.WriteTo only working with *net.UDPAddr, so we need a net.UDPAddr
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DefaultResolver)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -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,8 +15,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -67,12 +66,6 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(h.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(h.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
@ -92,8 +85,8 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (h *Http) SupportWithDialer() C.NetWork {
|
func (h *Http) SupportWithDialer() bool {
|
||||||
return C.TCP
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
@ -157,7 +150,7 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
if len(option.Fingerprint) == 0 {
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
})
|
})
|
||||||
@ -177,7 +170,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),
|
||||||
|
@ -20,7 +20,6 @@ import (
|
|||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
@ -29,7 +28,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -48,12 +46,21 @@ var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
|||||||
type Hysteria struct {
|
type Hysteria struct {
|
||||||
*Base
|
*Base
|
||||||
|
|
||||||
option *HysteriaOption
|
|
||||||
client *core.Client
|
client *core.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), h.genHdc(ctx, opts...))
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
||||||
|
},
|
||||||
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), &hdc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -62,32 +69,20 @@ 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) {
|
||||||
udpConn, err := h.client.DialUDP(h.genHdc(ctx, opts...))
|
hdc := hyDialerWithContext{
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria) genHdc(ctx context.Context, opts ...dialer.Option) utils.PacketDialer {
|
|
||||||
return &hyDialerWithContext{
|
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
hyDialer: func(network string) (net.PacketConn, error) {
|
hyDialer: func(network string) (net.PacketConn, error) {
|
||||||
var err error
|
return dialer.ListenPacket(ctx, network, "", h.Base.DialOptions(opts...)...)
|
||||||
var cDialer C.Dialer = dialer.NewDialer(h.Base.DialOptions(opts...)...)
|
|
||||||
if len(h.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(h.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rAddrPort, _ := netip.ParseAddrPort(h.Addr())
|
|
||||||
return cDialer.ListenPacket(ctx, network, "", rAddrPort)
|
|
||||||
},
|
},
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
return resolveUDPAddrWithPrefer(ctx, "udp", addr, h.prefer)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
udpConn, err := h.client.DialUDP(&hdc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type HysteriaOption struct {
|
type HysteriaOption struct {
|
||||||
@ -183,7 +178,7 @@ 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 {
|
||||||
@ -263,7 +258,6 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
client: client,
|
client: client,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
@ -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,22 +6,15 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/restls"
|
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
restlsC "github.com/3andne/restls-client-go"
|
"github.com/metacubex/sing-shadowsocks"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
@ -34,26 +27,22 @@ type ShadowSocks struct {
|
|||||||
|
|
||||||
option *ShadowSocksOption
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
|
||||||
restlsConfig *restlsC.Config
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
||||||
UDPOverTCPVersion int `proxy:"udp-over-tcp-version,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -72,31 +61,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"`
|
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
|
||||||
Version int `obfs:"version,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type restlsOption struct {
|
|
||||||
Password string `obfs:"password"`
|
|
||||||
Host string `obfs:"host"`
|
|
||||||
VersionHint string `obfs:"version-hint"`
|
|
||||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
// fix tls handshake not timeout
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return ss.StreamConnContext(ctx, c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
useEarly := false
|
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -109,35 +75,11 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
case shadowtls.Mode:
|
|
||||||
var err error
|
|
||||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
useEarly = true
|
|
||||||
case restls.Mode:
|
|
||||||
var err error
|
|
||||||
c, err = restls.NewRestls(ctx, c, ss.restlsConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
|
|
||||||
}
|
|
||||||
useEarly = true
|
|
||||||
}
|
}
|
||||||
useEarly = useEarly || N.NeedHandshake(c)
|
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
uotDestination := uot.RequestDestination(uint8(ss.option.UDPOverTCPVersion))
|
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
||||||
if useEarly {
|
|
||||||
return ss.method.DialEarlyConn(c, uotDestination), nil
|
|
||||||
} else {
|
|
||||||
return ss.method.DialConn(c, uotDestination)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if useEarly {
|
|
||||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -147,12 +89,6 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -163,7 +99,7 @@ func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Diale
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConnContext(ctx, c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,18 +110,12 @@ func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ss.option.UDPOverTCP {
|
if ss.option.UDPOverTCP {
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
||||||
}
|
}
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -196,35 +126,21 @@ func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dial
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, 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
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) SupportWithDialer() C.NetWork {
|
func (ss *ShadowSocks) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, 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 {
|
||||||
// ss uot use stream-oriented udp with a special address, so we need a net.UDPAddr
|
return newPacketConn(uot.NewClientConn(c), ss), nil
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
|
||||||
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
|
||||||
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
|
||||||
} else {
|
|
||||||
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil, C.ErrNotSupport
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -234,15 +150,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
|
|
||||||
var restlsConfig *restlsC.Config
|
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -278,43 +192,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: option.ClientFingerprint,
|
|
||||||
SkipCertVerify: opt.SkipCertVerify,
|
|
||||||
Version: opt.Version,
|
|
||||||
}
|
|
||||||
} else if option.Plugin == restls.Mode {
|
|
||||||
obfsMode = restls.Mode
|
|
||||||
restlsOpt := &restlsOption{}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, restlsOpt); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
restlsConfig, err = restlsC.NewRestlsConfig(restlsOpt.Host, restlsOpt.Password, restlsOpt.VersionHint, restlsOpt.RestlsScript, option.ClientFingerprint)
|
|
||||||
restlsConfig.SessionTicketsDisabled = true
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
switch option.UDPOverTCPVersion {
|
|
||||||
case uot.Version, uot.LegacyVersion:
|
|
||||||
case 0:
|
|
||||||
option.UDPOverTCPVersion = uot.Version
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -323,19 +200,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,
|
|
||||||
restlsConfig: restlsConfig,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
@ -18,7 +17,6 @@ import (
|
|||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
*Base
|
*Base
|
||||||
option *ShadowSocksROption
|
|
||||||
cipher core.Cipher
|
cipher core.Cipher
|
||||||
obfs obfs.Obfs
|
obfs obfs.Obfs
|
||||||
protocol protocol.Protocol
|
protocol protocol.Protocol
|
||||||
@ -67,12 +65,6 @@ func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(ssr.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ssr.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
@ -94,12 +86,6 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(ssr.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ssr.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -116,8 +102,8 @@ func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Di
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) SupportWithDialer() C.NetWork {
|
func (ssr *ShadowSocksR) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
@ -177,12 +163,10 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
protocol: protocol,
|
protocol: protocol,
|
||||||
|
@ -1,138 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
mux "github.com/sagernet/sing-mux"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SingMux struct {
|
|
||||||
C.ProxyAdapter
|
|
||||||
base ProxyBase
|
|
||||||
client *mux.Client
|
|
||||||
dialer *muxSingDialer
|
|
||||||
onlyTcp bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type SingMuxOption struct {
|
|
||||||
Enabled bool `proxy:"enabled,omitempty"`
|
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
|
||||||
MaxConnections int `proxy:"max-connections,omitempty"`
|
|
||||||
MinStreams int `proxy:"min-streams,omitempty"`
|
|
||||||
MaxStreams int `proxy:"max-streams,omitempty"`
|
|
||||||
Padding bool `proxy:"padding,omitempty"`
|
|
||||||
Statistic bool `proxy:"statistic,omitempty"`
|
|
||||||
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProxyBase interface {
|
|
||||||
DialOptions(opts ...dialer.Option) []dialer.Option
|
|
||||||
}
|
|
||||||
|
|
||||||
type muxSingDialer struct {
|
|
||||||
dialer dialer.Dialer
|
|
||||||
proxy C.ProxyAdapter
|
|
||||||
statistic bool
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.Dialer = (*muxSingDialer)(nil)
|
|
||||||
|
|
||||||
func (d *muxSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
|
||||||
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
|
||||||
return cDialer.DialContext(ctx, network, destination.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *muxSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
|
||||||
var cDialer C.Dialer = proxydialer.New(d.proxy, d.dialer, d.statistic)
|
|
||||||
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
options := s.base.DialOptions(opts...)
|
|
||||||
s.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
c, err := s.client.DialContext(ctx, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return NewConn(CN.NewRefConn(c, s), s.ProxyAdapter), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
if s.onlyTcp {
|
|
||||||
return s.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
|
||||||
}
|
|
||||||
options := s.base.DialOptions(opts...)
|
|
||||||
s.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
|
|
||||||
// sing-mux use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
pc, err := s.client.ListenPacket(ctx, M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if pc == nil {
|
|
||||||
return nil, E.New("packetConn is nil")
|
|
||||||
}
|
|
||||||
return newPacketConn(CN.NewRefPacketConn(pc, s), s.ProxyAdapter), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) SupportUDP() bool {
|
|
||||||
if s.onlyTcp {
|
|
||||||
return s.ProxyAdapter.SupportUOT()
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) SupportUOT() bool {
|
|
||||||
if s.onlyTcp {
|
|
||||||
return s.ProxyAdapter.SupportUOT()
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeSingMux(s *SingMux) {
|
|
||||||
_ = s.client.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSingMux(option SingMuxOption, proxy C.ProxyAdapter, base ProxyBase) (C.ProxyAdapter, error) {
|
|
||||||
singDialer := &muxSingDialer{dialer: dialer.NewDialer(), proxy: proxy, statistic: option.Statistic}
|
|
||||||
client, err := mux.NewClient(mux.Options{
|
|
||||||
Dialer: singDialer,
|
|
||||||
Protocol: option.Protocol,
|
|
||||||
MaxConnections: option.MaxConnections,
|
|
||||||
MinStreams: option.MinStreams,
|
|
||||||
MaxStreams: option.MaxStreams,
|
|
||||||
Padding: option.Padding,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
outbound := &SingMux{
|
|
||||||
ProxyAdapter: proxy,
|
|
||||||
base: base,
|
|
||||||
client: client,
|
|
||||||
dialer: singDialer,
|
|
||||||
onlyTcp: option.OnlyTcp,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeSingMux)
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
@ -8,7 +8,6 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/snell"
|
"github.com/Dreamacro/clash/transport/snell"
|
||||||
@ -16,7 +15,6 @@ import (
|
|||||||
|
|
||||||
type Snell struct {
|
type Snell struct {
|
||||||
*Base
|
*Base
|
||||||
option *SnellOption
|
|
||||||
psk []byte
|
psk []byte
|
||||||
pool *snell.Pool
|
pool *snell.Pool
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
@ -85,12 +83,6 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(s.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(s.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
@ -112,13 +104,6 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
var err error
|
|
||||||
if len(s.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(s.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -136,8 +121,8 @@ func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (s *Snell) SupportWithDialer() C.NetWork {
|
func (s *Snell) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -182,12 +167,10 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
version: option.Version,
|
version: option.Version,
|
||||||
@ -195,15 +178,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
|
|
||||||
if option.Version == snell.Version2 {
|
if option.Version == snell.Version2 {
|
||||||
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||||
var err error
|
c, err := dialer.DialContext(ctx, "tcp", addr, s.Base.DialOptions()...)
|
||||||
var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions()...)
|
|
||||||
if len(s.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(ctx, "tcp", addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -5,20 +5,18 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
*Base
|
*Base
|
||||||
option *Socks5Option
|
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@ -72,12 +70,6 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(ss.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@ -97,20 +89,13 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (ss *Socks5) SupportWithDialer() C.NetWork {
|
func (ss *Socks5) SupportWithDialer() bool {
|
||||||
return C.TCP
|
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) {
|
||||||
var cDialer C.Dialer = dialer.NewDialer(ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
if len(ss.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(ss.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(ctx, "tcp", ss.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
return
|
return
|
||||||
@ -182,7 +167,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 {
|
||||||
@ -197,12 +182,10 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
|
@ -4,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"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
@ -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)
|
||||||
}
|
}
|
||||||
@ -135,12 +125,6 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(t.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
@ -185,12 +169,6 @@ func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(t.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
@ -214,8 +192,8 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (t *Trojan) SupportWithDialer() C.NetWork {
|
func (t *Trojan) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
@ -233,25 +211,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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -265,7 +239,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),
|
||||||
@ -274,24 +247,9 @@ 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) {
|
||||||
var err error
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
||||||
var cDialer C.Dialer = dialer.NewDialer(t.Base.DialOptions()...)
|
|
||||||
if len(t.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(t.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(context.Background(), "tcp", t.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -307,7 +265,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 {
|
||||||
@ -315,7 +273,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{
|
||||||
|
@ -16,7 +16,6 @@ import (
|
|||||||
"github.com/metacubex/quic-go"
|
"github.com/metacubex/quic-go"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
"github.com/Dreamacro/clash/transport/tuic"
|
||||||
@ -24,7 +23,6 @@ import (
|
|||||||
|
|
||||||
type Tuic struct {
|
type Tuic struct {
|
||||||
*Base
|
*Base
|
||||||
option *TuicOption
|
|
||||||
client *tuic.PoolClient
|
client *tuic.PoolClient
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,17 +42,15 @@ type TuicOption struct {
|
|||||||
DisableSni bool `proxy:"disable-sni,omitempty"`
|
DisableSni bool `proxy:"disable-sni,omitempty"`
|
||||||
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
||||||
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
CustomCAString string `proxy:"ca-str,omitempty"`
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
|
|
||||||
SNI string `proxy:"sni,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -86,8 +82,8 @@ func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (t *Tuic) SupportWithDialer() C.NetWork {
|
func (t *Tuic) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
@ -95,12 +91,6 @@ func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketCo
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
if len(t.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
@ -116,14 +106,12 @@ func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.Pack
|
|||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
serverName := option.Server
|
serverName := option.Server
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: serverName,
|
ServerName: serverName,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
if option.SNI != "" {
|
|
||||||
tlsConfig.ServerName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
var bs []byte
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
@ -155,7 +143,7 @@ func NewTuic(option TuicOption) (*Tuic, 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 {
|
||||||
@ -177,22 +165,13 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
option.MaxUdpRelayPacketSize = 1252
|
option.MaxUdpRelayPacketSize = 1500
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxOpenStreams == 0 {
|
if option.MaxOpenStreams == 0 {
|
||||||
option.MaxOpenStreams = 100
|
option.MaxOpenStreams = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize == 0 {
|
|
||||||
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + tuic.PacketOverHead
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize > 1400 {
|
|
||||||
option.MaxDatagramFrameSize = 1400
|
|
||||||
}
|
|
||||||
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - tuic.PacketOverHead
|
|
||||||
|
|
||||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
||||||
@ -205,7 +184,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
MaxIncomingUniStreams: quicMaxOpenStreams,
|
MaxIncomingUniStreams: quicMaxOpenStreams,
|
||||||
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
|
|
||||||
EnableDatagrams: true,
|
EnableDatagrams: true,
|
||||||
}
|
}
|
||||||
if option.ReceiveWindowConn == 0 {
|
if option.ReceiveWindowConn == 0 {
|
||||||
@ -235,19 +213,12 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
udp: true,
|
udp: true,
|
||||||
tfo: option.FastOpen,
|
tfo: option.FastOpen,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
|
||||||
|
|
||||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
// to avoid tuic's "too many open streams", decrease to 0.9x
|
||||||
if clientMaxOpenStreams == 100 {
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
||||||
}
|
|
||||||
|
|
||||||
if clientMaxOpenStreams < 1 {
|
if clientMaxOpenStreams < 1 {
|
||||||
clientMaxOpenStreams = 1
|
clientMaxOpenStreams = 1
|
||||||
}
|
}
|
||||||
|
@ -14,19 +14,13 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmessSing "github.com/sagernet/sing-vmess"
|
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -43,46 +37,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,
|
||||||
@ -90,7 +73,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{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,12 +91,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 != "" {
|
||||||
@ -158,7 +137,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
|
||||||
@ -169,45 +152,21 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.streamConn(c, metadata)
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
|
||||||
if metadata.NetWork == C.UDP {
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
metadata = &C.Metadata{
|
|
||||||
NetWork: C.UDP,
|
|
||||||
Host: packetaddr.SeqPacketMagicAddress,
|
|
||||||
DstPort: "443",
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
metadata = &C.Metadata{ // a clear metadata only contains ip
|
|
||||||
NetWork: C.UDP,
|
|
||||||
DstIP: metadata.DstIP,
|
|
||||||
DstPort: metadata.DstPort,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
conn = packetaddr.NewBindConn(conn)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, false))
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
conn = nil
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(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 != "" {
|
||||||
@ -218,11 +177,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 {
|
||||||
@ -239,8 +196,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
|
||||||
@ -255,7 +212,7 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -267,12 +224,6 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(v.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -283,15 +234,12 @@ func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we 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(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -299,6 +247,7 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
@ -310,26 +259,20 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.streamConn(c, metadata)
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(v.option.DialerProxy) > 0 {
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -337,7 +280,6 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -348,40 +290,21 @@ func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vless) SupportWithDialer() C.NetWork {
|
func (v *Vless) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.XUDP {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: vmessSing.NewXUDPConn(c, M.SocksaddrFromNet(metadata.UDPAddr())),
|
|
||||||
}, v), nil
|
|
||||||
} else if v.option.PacketAddr {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
|
||||||
Conn: c, rAddr: metadata.UDPAddr(),
|
|
||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
|
||||||
}, v), nil
|
|
||||||
}
|
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -390,7 +313,7 @@ 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() {
|
||||||
@ -414,8 +337,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,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -516,9 +438,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,
|
||||||
@ -528,19 +447,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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if option.XUDP {
|
|
||||||
option.PacketAddr = false
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -552,21 +458,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 {
|
||||||
@ -574,15 +472,7 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
var err error
|
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
||||||
var cDialer C.Dialer = dialer.NewDialer(v.Base.DialOptions()...)
|
|
||||||
if len(v.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(v.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(context.Background(), "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -591,11 +481,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,
|
||||||
})
|
})
|
||||||
@ -608,8 +497,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,22 +5,20 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
@ -36,35 +34,31 @@ 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"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -92,13 +86,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,
|
||||||
@ -106,7 +96,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{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -125,8 +114,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
|
||||||
}
|
}
|
||||||
@ -144,15 +134,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
|
||||||
@ -171,11 +160,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 != "" {
|
||||||
@ -194,16 +181,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,42 +202,15 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return v.streamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vmess) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
if v.option.XUDP {
|
if v.option.XUDP {
|
||||||
if N.NeedHandshake(c) {
|
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
conn = v.client.DialEarlyXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
} else {
|
|
||||||
conn, err = v.client.DialXUDPPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
}
|
|
||||||
} else if v.option.PacketAddr {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
conn = v.client.DialEarlyPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
|
||||||
} else {
|
|
||||||
conn, err = v.client.DialPacketConn(c, M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
|
||||||
}
|
|
||||||
conn = packetaddr.NewBindConn(conn)
|
|
||||||
} else {
|
} else {
|
||||||
if N.NeedHandshake(c) {
|
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
conn = v.client.DialEarlyPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
} else {
|
|
||||||
conn, err = v.client.DialPacketConn(c, M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if N.NeedHandshake(c) {
|
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
conn = v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
conn, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if err != nil {
|
|
||||||
conn = nil
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -279,12 +237,6 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContextWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if len(v.option.DialerProxy) > 0 {
|
|
||||||
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
@ -300,7 +252,7 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we 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(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -308,6 +260,14 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
_metadata := *metadata // make a copy
|
||||||
|
metadata = &_metadata
|
||||||
|
metadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
metadata.DstPort = "443"
|
||||||
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
@ -319,25 +279,33 @@ func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.streamConn(c, metadata)
|
if v.option.XUDP {
|
||||||
|
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if len(v.option.DialerProxy) > 0 {
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
dialer, err = proxydialer.NewByName(v.option.DialerProxy, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -347,38 +315,23 @@ func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.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(ctx, c, metadata)
|
|
||||||
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
// SupportWithDialer implements C.ProxyAdapter
|
||||||
func (v *Vmess) SupportWithDialer() C.NetWork {
|
func (v *Vmess) SupportWithDialer() bool {
|
||||||
return C.ALLNet
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
if v.option.PacketAddr {
|
||||||
if !metadata.Resolved() {
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
if pc, ok := c.(net.PacketConn); ok {
|
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
@ -416,7 +369,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2", "grpc":
|
case "h2", "grpc":
|
||||||
if !option.TLS {
|
if !option.TLS {
|
||||||
option.TLS = true
|
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -426,8 +379,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),
|
||||||
@ -443,15 +394,7 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
var err error
|
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
||||||
var cDialer C.Dialer = dialer.NewDialer(v.Base.DialOptions()...)
|
|
||||||
if len(v.option.DialerProxy) > 0 {
|
|
||||||
cDialer, err = proxydialer.NewByName(v.option.DialerProxy, cDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c, err := cDialer.DialContext(context.Background(), "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
@ -460,9 +403,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,
|
||||||
@ -477,15 +419,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -509,9 +444,9 @@ type vmessPacketConn struct {
|
|||||||
// WriteTo implments C.PacketConn.WriteTo
|
// WriteTo implments C.PacketConn.WriteTo
|
||||||
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
allowedAddr := uc.rAddr
|
allowedAddr := uc.rAddr.(*net.UDPAddr)
|
||||||
destAddr := addr
|
destAddr := addr.(*net.UDPAddr)
|
||||||
if allowedAddr.String() != destAddr.String() {
|
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
||||||
return 0, ErrUDPRemoteAddrMismatch
|
return 0, ErrUDPRemoteAddrMismatch
|
||||||
}
|
}
|
||||||
uc.access.Lock()
|
uc.access.Lock()
|
||||||
|
@ -15,11 +15,9 @@ import (
|
|||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
CN "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/listener/sing"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
|
||||||
@ -36,100 +34,66 @@ type WireGuard struct {
|
|||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer *wgSingDialer
|
dialer *wgDialer
|
||||||
startOnce sync.Once
|
startOnce sync.Once
|
||||||
startErr error
|
startErr error
|
||||||
resolver *dns.Resolver
|
|
||||||
refP *refProxyAdapter
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardOption struct {
|
type WireGuardOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
WireGuardPeerOption
|
Name string `proxy:"name"`
|
||||||
Name string `proxy:"name"`
|
Server string `proxy:"server"`
|
||||||
PrivateKey string `proxy:"private-key"`
|
Port int `proxy:"port"`
|
||||||
Workers int `proxy:"workers,omitempty"`
|
Ip string `proxy:"ip,omitempty"`
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
PublicKey string `proxy:"public-key"`
|
||||||
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
|
Workers int `proxy:"workers,omitempty"`
|
||||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
Dns []string `proxy:"dns,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WireGuardPeerOption struct {
|
type wgDialer struct {
|
||||||
Server string `proxy:"server"`
|
options []dialer.Option
|
||||||
Port int `proxy:"port"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PublicKey string `proxy:"public-key,omitempty"`
|
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
|
||||||
AllowedIPs []string `proxy:"allowed_ips,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type wgSingDialer struct {
|
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
dialer dialer.Dialer
|
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
||||||
proxyName string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ N.Dialer = (*wgSingDialer)(nil)
|
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", destination.Addr), "", d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
var cDialer C.Dialer = d.dialer
|
outbound := &WireGuard{
|
||||||
if len(d.proxyName) > 0 {
|
Base: &Base{
|
||||||
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
name: option.Name,
|
||||||
if err != nil {
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
return nil, err
|
tp: C.WireGuard,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
dialer: &wgDialer{},
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
|
|
||||||
|
var reserved [3]uint8
|
||||||
|
if len(option.Reserved) > 0 {
|
||||||
|
if len(option.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
||||||
}
|
}
|
||||||
cDialer = pd
|
reserved[0] = uint8(option.Reserved[0])
|
||||||
|
reserved[1] = uint8(option.Reserved[1])
|
||||||
|
reserved[2] = uint8(option.Reserved[2])
|
||||||
}
|
}
|
||||||
return cDialer.DialContext(ctx, network, destination.String())
|
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
}
|
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
||||||
|
|
||||||
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
|
||||||
var cDialer C.Dialer = d.dialer
|
|
||||||
if len(d.proxyName) > 0 {
|
|
||||||
pd, err := proxydialer.NewByName(d.proxyName, d.dialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
cDialer = pd
|
|
||||||
}
|
|
||||||
return cDialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgSingErrorHandler struct {
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ E.Handler = (*wgSingErrorHandler)(nil)
|
|
||||||
|
|
||||||
func (w wgSingErrorHandler) NewError(ctx context.Context, err error) {
|
|
||||||
if E.IsClosedOrCanceled(err) {
|
|
||||||
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) connection closed: %s", w.name, err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", w.name, err))
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgNetDialer struct {
|
|
||||||
tunDevice wireguard.Device
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ dialer.NetDialer = (*wgNetDialer)(nil)
|
|
||||||
|
|
||||||
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
|
||||||
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (option WireGuardPeerOption) Prefixes() ([]netip.Prefix, error) {
|
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
if len(option.Ip) > 0 {
|
if len(option.Ip) > 0 {
|
||||||
if !strings.Contains(option.Ip, "/") {
|
if !strings.Contains(option.Ip, "/") {
|
||||||
@ -154,46 +118,7 @@ func (option WireGuardPeerOption) Prefixes() ([]netip.Prefix, error) {
|
|||||||
if len(localPrefixes) == 0 {
|
if len(localPrefixes) == 0 {
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
return localPrefixes, nil
|
var privateKey, peerPublicKey, preSharedKey string
|
||||||
}
|
|
||||||
|
|
||||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|
||||||
outbound := &WireGuard{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
tp: C.WireGuard,
|
|
||||||
udp: option.UDP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
dialer: &wgSingDialer{dialer: dialer.NewDialer(), proxyName: option.DialerProxy},
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
|
||||||
if len(option.Reserved) > 0 {
|
|
||||||
if len(option.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
|
||||||
}
|
|
||||||
copy(reserved[:], option.Reserved)
|
|
||||||
}
|
|
||||||
var isConnect bool
|
|
||||||
var connectAddr M.Socksaddr
|
|
||||||
if len(option.Peers) < 2 {
|
|
||||||
isConnect = true
|
|
||||||
if len(option.Peers) == 1 {
|
|
||||||
connectAddr = option.Peers[0].Addr()
|
|
||||||
} else {
|
|
||||||
connectAddr = option.Addr()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, outbound.dialer, isConnect, connectAddr, reserved)
|
|
||||||
|
|
||||||
var localPrefixes []netip.Prefix
|
|
||||||
|
|
||||||
var privateKey string
|
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -201,92 +126,40 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
privateKey = hex.EncodeToString(bytes)
|
privateKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
ipcConf := "private_key=" + privateKey
|
{
|
||||||
if peersLen := len(option.Peers); peersLen > 0 {
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
localPrefixes = make([]netip.Prefix, 0, peersLen*2)
|
|
||||||
for i, peer := range option.Peers {
|
|
||||||
var peerPublicKey, preSharedKey string
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode public key for peer ", i)
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
if peer.PreSharedKey != "" {
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
|
||||||
}
|
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
destination := peer.Addr()
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + destination.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
if len(peer.AllowedIPs) == 0 {
|
|
||||||
return nil, E.New("missing allowed_ips for peer ", i)
|
|
||||||
}
|
|
||||||
for _, allowedIP := range peer.AllowedIPs {
|
|
||||||
ipcConf += "\nallowed_ip=" + allowedIP
|
|
||||||
}
|
|
||||||
if len(peer.Reserved) > 0 {
|
|
||||||
if len(peer.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
|
||||||
}
|
|
||||||
copy(reserved[:], option.Reserved)
|
|
||||||
outbound.bind.SetReservedForEndpoint(destination, reserved)
|
|
||||||
}
|
|
||||||
prefixes, err := peer.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
localPrefixes = append(localPrefixes, prefixes...)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var peerPublicKey, preSharedKey string
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
if option.PreSharedKey != "" {
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
|
||||||
}
|
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + connectAddr.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
localPrefixes, err = option.Prefixes()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
}
|
}
|
||||||
var has4, has6 bool
|
peerPublicKey = hex.EncodeToString(bytes)
|
||||||
for _, address := range localPrefixes {
|
}
|
||||||
if address.Addr().Is4() {
|
if option.PreSharedKey != "" {
|
||||||
has4 = true
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
} else {
|
if err != nil {
|
||||||
has6 = true
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if has4 {
|
preSharedKey = hex.EncodeToString(bytes)
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
}
|
||||||
}
|
ipcConf := "private_key=" + privateKey
|
||||||
if has6 {
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
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 {
|
if option.PersistentKeepalive != 0 {
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
||||||
}
|
}
|
||||||
@ -294,9 +167,6 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
if len(localPrefixes) == 0 {
|
|
||||||
return nil, E.New("missing local address")
|
|
||||||
}
|
|
||||||
var err error
|
var err error
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -304,45 +174,20 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
sing.Logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
},
|
},
|
||||||
Errorf: func(format string, args ...interface{}) {
|
Errorf: func(format string, args ...interface{}) {
|
||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
sing.Logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
},
|
},
|
||||||
}, option.Workers)
|
}, option.Workers)
|
||||||
if debug.Enabled {
|
if debug.Enabled {
|
||||||
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", option.Name, ipcConf))
|
sing.Logger.Trace("created wireguard ipc conf: \n", ipcConf)
|
||||||
}
|
}
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
}
|
}
|
||||||
//err = outbound.tunDevice.Start()
|
//err = outbound.tunDevice.Start()
|
||||||
|
|
||||||
var has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if !address.Addr().Unmap().Is4() {
|
|
||||||
has6 = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
refP := &refProxyAdapter{}
|
|
||||||
outbound.refP = refP
|
|
||||||
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
|
||||||
nss, err := dns.ParseNameServer(option.Dns)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range nss {
|
|
||||||
nss[i].ProxyAdapter = refP
|
|
||||||
}
|
|
||||||
outbound.resolver = dns.NewResolver(dns.Config{
|
|
||||||
Main: nss,
|
|
||||||
IPv6: has6,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -354,8 +199,7 @@ func closeWireGuard(w *WireGuard) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
w.dialer.options = opts
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -363,19 +207,16 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
if w.startErr != nil {
|
if w.startErr != nil {
|
||||||
return nil, w.startErr
|
return nil, w.startErr
|
||||||
}
|
}
|
||||||
if !metadata.Resolved() || w.resolver != nil {
|
if !metadata.Resolved() {
|
||||||
r := resolver.DefaultResolver
|
var addrs []netip.Addr
|
||||||
if w.resolver != nil {
|
addrs, err = resolver.LookupIP(ctx, metadata.Host)
|
||||||
w.refP.SetProxyAdapter(w)
|
if err != nil {
|
||||||
defer w.refP.ClearProxyAdapter()
|
return nil, err
|
||||||
r = w.resolver
|
|
||||||
}
|
}
|
||||||
options = append(options, dialer.WithResolver(r))
|
conn, err = N.DialSerial(ctx, w.tunDevice, "tcp", M.ParseSocksaddr(metadata.RemoteAddress()), addrs)
|
||||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
|
||||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
|
||||||
} else {
|
} else {
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -387,8 +228,7 @@ func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
options := w.Base.DialOptions(opts...)
|
w.dialer.options = opts
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var pc net.PacketConn
|
var pc net.PacketConn
|
||||||
w.startOnce.Do(func() {
|
w.startOnce.Do(func() {
|
||||||
w.startErr = w.tunDevice.Start()
|
w.startErr = w.tunDevice.Start()
|
||||||
@ -399,21 +239,15 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
if !metadata.Resolved() {
|
||||||
r := resolver.DefaultResolver
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
if w.resolver != nil {
|
|
||||||
w.refP.SetProxyAdapter(w)
|
|
||||||
defer w.refP.ClearProxyAdapter()
|
|
||||||
r = w.resolver
|
|
||||||
}
|
|
||||||
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, errors.New("can't resolve ip")
|
||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -422,144 +256,3 @@ func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadat
|
|||||||
}
|
}
|
||||||
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
|
||||||
func (w *WireGuard) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type refProxyAdapter struct {
|
|
||||||
proxyAdapter C.ProxyAdapter
|
|
||||||
count int
|
|
||||||
mutex sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SetProxyAdapter(proxyAdapter C.ProxyAdapter) {
|
|
||||||
r.mutex.Lock()
|
|
||||||
defer r.mutex.Unlock()
|
|
||||||
r.proxyAdapter = proxyAdapter
|
|
||||||
r.count++
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) ClearProxyAdapter() {
|
|
||||||
r.mutex.Lock()
|
|
||||||
defer r.mutex.Unlock()
|
|
||||||
r.count--
|
|
||||||
if r.count == 0 {
|
|
||||||
r.proxyAdapter = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) Name() string {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.Name()
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) Type() C.AdapterType {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.Type()
|
|
||||||
}
|
|
||||||
return C.AdapterType(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) Addr() string {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.Addr()
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SupportUDP() bool {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.SupportUDP()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SupportXUDP() bool {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.SupportXUDP()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SupportTFO() bool {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.SupportTFO()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) MarshalJSON() ([]byte, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.MarshalJSON()
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.StreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.DialContext(ctx, metadata, opts...)
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SupportUOT() bool {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.SupportUOT()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) SupportWithDialer() C.NetWork {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.SupportWithDialer()
|
|
||||||
}
|
|
||||||
return C.InvalidNet
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.DialContextWithDialer(ctx, dialer, metadata)
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.ListenPacketWithDialer(ctx, dialer, metadata)
|
|
||||||
}
|
|
||||||
return nil, C.ErrNotSupport
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.IsL3Protocol(metadata)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *refProxyAdapter) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.Unwrap(metadata, touch)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ C.ProxyAdapter = (*refProxyAdapter)(nil)
|
|
||||||
|
@ -4,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,20 +29,11 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
|
f.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
f.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,11 +58,6 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
return proxy.SupportUDP()
|
return proxy.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
|
||||||
func (f *Fallback) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return f.findAliveProxy(false).IsL3Protocol(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@ -138,10 +121,6 @@ func (f *Fallback) Set(name string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) ForceSet(name string) {
|
|
||||||
f.selected = name
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
@ -153,7 +132,6 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
@ -3,26 +3,23 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filterRegs []*regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
excludeFilterReg *regexp2.Regexp
|
excludeFilterReg *regexp2.Regexp
|
||||||
excludeTypeArray []string
|
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
failedTestMux sync.Mutex
|
failedTestMux sync.Mutex
|
||||||
failedTimes int
|
failedTimes int
|
||||||
@ -36,7 +33,6 @@ type GroupBaseOption struct {
|
|||||||
outbound.BaseOption
|
outbound.BaseOption
|
||||||
filter string
|
filter string
|
||||||
excludeFilter string
|
excludeFilter string
|
||||||
excludeType string
|
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,10 +41,6 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
if opt.excludeFilter != "" {
|
if opt.excludeFilter != "" {
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
||||||
}
|
}
|
||||||
var excludeTypeArray []string
|
|
||||||
if opt.excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(opt.excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
if opt.filter != "" {
|
if opt.filter != "" {
|
||||||
@ -62,7 +54,6 @@ func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|||||||
Base: outbound.NewBase(opt.BaseOption),
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
filterRegs: filterRegs,
|
filterRegs: filterRegs,
|
||||||
excludeFilterReg: excludeFilterReg,
|
excludeFilterReg: excludeFilterReg,
|
||||||
excludeTypeArray: excludeTypeArray,
|
|
||||||
providers: opt.providers,
|
providers: opt.providers,
|
||||||
failedTesting: atomic.NewBool(false),
|
failedTesting: atomic.NewBool(false),
|
||||||
}
|
}
|
||||||
@ -157,25 +148,6 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
proxies = newProxies
|
proxies = newProxies
|
||||||
}
|
}
|
||||||
if gb.excludeTypeArray != nil {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
for _, p := range proxies {
|
|
||||||
mType := p.Type().String()
|
|
||||||
flag := false
|
|
||||||
for i := range gb.excludeTypeArray {
|
|
||||||
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
if gb.excludeFilterReg != nil {
|
if gb.excludeFilterReg != nil {
|
||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
|
@ -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
|
||||||
@ -86,24 +83,17 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := lb.Unwrap(metadata, true)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(lb)
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,32 +114,14 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
return !lb.disableUDP
|
return !lb.disableUDP
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
|
||||||
func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return lb.Unwrap(metadata, false).IsL3Protocol(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -160,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 {
|
||||||
@ -188,7 +160,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
lruCache := cache.New[uint64, int](
|
lruCache := cache.New[uint64, int](
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
cache.WithSize[uint64, int](1000))
|
cache.WithSize[uint64, int](1000))
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, 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)
|
||||||
@ -220,7 +192,7 @@ func strategyStickySessions() strategyFn {
|
|||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(touch)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata, touch)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -257,7 +229,6 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
|
@ -31,7 +31,6 @@ type GroupCommonOption struct {
|
|||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `group:"exclude-type,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
@ -78,7 +77,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,9 +3,13 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -14,6 +18,36 @@ type Relay struct {
|
|||||||
*GroupBase
|
*GroupBase
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type proxyDialer struct {
|
||||||
|
proxy C.Proxy
|
||||||
|
dialer C.Dialer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p proxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
currentMeta, err := addrToMetadata(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if strings.Contains(network, "udp") { // should not support this operation
|
||||||
|
currentMeta.NetWork = C.UDP
|
||||||
|
pc, err := p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return N.NewBindPacketConn(pc, currentMeta.UDPAddr()), nil
|
||||||
|
}
|
||||||
|
return p.proxy.DialContextWithDialer(ctx, p.dialer, currentMeta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p proxyDialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||||
|
currentMeta, err := addrToMetadata(rAddrPort.String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
currentMeta.NetWork = C.UDP
|
||||||
|
return p.proxy.ListenPacketWithDialer(ctx, p.dialer, currentMeta)
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
@ -27,7 +61,10 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
var d C.Dialer
|
var d C.Dialer
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
d = proxydialer.New(proxy, d, false)
|
d = proxyDialer{
|
||||||
|
proxy: proxy,
|
||||||
|
dialer: d,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
||||||
@ -58,7 +95,10 @@ func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
var d C.Dialer
|
var d C.Dialer
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
for _, proxy := range proxies[:len(proxies)-1] {
|
||||||
d = proxydialer.New(proxy, d, false)
|
d = proxyDialer{
|
||||||
|
proxy: proxy,
|
||||||
|
dialer: d,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
last := proxies[len(proxies)-1]
|
||||||
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
||||||
@ -89,10 +129,7 @@ func (r *Relay) SupportUDP() bool {
|
|||||||
if proxy.SupportUOT() {
|
if proxy.SupportUOT() {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
switch proxy.SupportWithDialer() {
|
if !proxy.SupportWithDialer() {
|
||||||
case C.ALLNet:
|
|
||||||
case C.UDP:
|
|
||||||
default: // C.TCP and C.InvalidNet
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -139,7 +176,7 @@ func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Addr() string {
|
func (r *Relay) Addr() string {
|
||||||
proxies, _ := r.proxies(nil, false)
|
proxies, _ := r.proxies(nil, true)
|
||||||
return proxies[len(proxies)-1].Addr()
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -154,7 +191,6 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
},
|
},
|
||||||
"",
|
"",
|
||||||
"",
|
"",
|
||||||
"",
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
@ -44,11 +44,6 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
return s.selectedProxy(false).SupportUDP()
|
return s.selectedProxy(false).SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
|
||||||
func (s *Selector) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return s.selectedProxy(false).IsL3Protocol(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@ -78,10 +73,6 @@ func (s *Selector) Set(name string) error {
|
|||||||
return errors.New("proxy not exist")
|
return errors.New("proxy not exist")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) ForceSet(name string) {
|
|
||||||
s.selected = name
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return s.selectedProxy(touch)
|
return s.selectedProxy(touch)
|
||||||
@ -109,7 +100,6 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
},
|
},
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
|
@ -3,12 +3,9 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -25,8 +22,6 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
selected string
|
|
||||||
testUrl string
|
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
@ -37,46 +32,16 @@ func (u *URLTest) Now() string {
|
|||||||
return u.fast(false).Name()
|
return u.fast(false).Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Set(name string) error {
|
|
||||||
var p C.Proxy
|
|
||||||
for _, proxy := range u.GetProxies(false) {
|
|
||||||
if proxy.Name() == name {
|
|
||||||
p = proxy
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if p == nil {
|
|
||||||
return errors.New("proxy not exist")
|
|
||||||
}
|
|
||||||
u.selected = name
|
|
||||||
u.fast(false)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) ForceSet(name string) {
|
|
||||||
u.selected = name
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := u.fast(true)
|
proxy := u.fast(true)
|
||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
|
u.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
u.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,24 +62,16 @@ func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
|||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
var s C.Proxy
|
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
if fast.Name() == u.selected {
|
|
||||||
s = fast
|
|
||||||
}
|
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
|
|
||||||
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
|
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
|
||||||
fastNotExist = false
|
fastNotExist = false
|
||||||
}
|
}
|
||||||
|
|
||||||
if proxy.Name() == u.selected {
|
|
||||||
s = proxy
|
|
||||||
}
|
|
||||||
if !proxy.Alive() {
|
if !proxy.Alive() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -125,15 +82,12 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
min = delay
|
min = delay
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// tolerance
|
// tolerance
|
||||||
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
if s != nil {
|
|
||||||
if s.Alive() && s.LastDelay() < fast.LastDelay()+u.tolerance {
|
|
||||||
u.fastNode = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
@ -148,12 +102,8 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
if u.disableUDP {
|
if u.disableUDP {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return u.fast(false).SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
return u.fast(false).SupportUDP()
|
||||||
func (u *URLTest) IsL3Protocol(metadata *C.Metadata) bool {
|
|
||||||
return u.fast(false).IsL3Protocol(metadata)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
@ -194,12 +144,10 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
|
|
||||||
option.Filter,
|
option.Filter,
|
||||||
option.ExcludeFilter,
|
option.ExcludeFilter,
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -1,10 +1,37 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
||||||
|
host, port, err := net.SplitHostPort(rawAddress)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip, err := netip.ParseAddr(host); err != nil {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
Host: host,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addr = &C.Metadata{
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip.Unmap(),
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
@ -14,5 +41,4 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
|
|
||||||
type SelectAble interface {
|
type SelectAble interface {
|
||||||
Set(string) error
|
Set(string) error
|
||||||
ForceSet(name string)
|
|
||||||
}
|
}
|
||||||
|
@ -2,9 +2,6 @@ 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"
|
||||||
@ -23,7 +20,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
)
|
)
|
||||||
switch proxyType {
|
switch proxyType {
|
||||||
case "ss":
|
case "ss":
|
||||||
ssOption := &outbound.ShadowSocksOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
ssOption := &outbound.ShadowSocksOption{}
|
||||||
err = decoder.Decode(mapping, ssOption)
|
err = decoder.Decode(mapping, ssOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -56,16 +53,14 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
ClientFingerprint: tlsC.GetGlobalFingerprint(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
vlessOption := &outbound.VlessOption{}
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -79,7 +74,7 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
trojanOption := &outbound.TrojanOption{}
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -114,19 +109,5 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if muxMapping, muxExist := mapping["smux"].(map[string]any); muxExist {
|
|
||||||
muxOption := &outbound.SingMuxOption{}
|
|
||||||
err = decoder.Decode(muxMapping, muxOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if muxOption.Enabled {
|
|
||||||
proxy, err = outbound.NewSingMux(*muxOption, proxy, proxy.(outbound.ProxyBase))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewProxy(proxy), nil
|
return NewProxy(proxy), nil
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -33,15 +34,16 @@ type HealthCheck struct {
|
|||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(30 * time.Second)
|
||||||
|
hc.lazyCheck()
|
||||||
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
now := time.Now().Unix()
|
hc.lazyCheck()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
}
|
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -49,6 +51,17 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) lazyCheck() bool {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -63,7 +76,10 @@ 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 := utils.NewUUIDV4().String()
|
id := ""
|
||||||
|
if uid, err := uuid.NewV4(); err == nil {
|
||||||
|
id = uid.String()
|
||||||
|
}
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
|
@ -3,10 +3,10 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -27,8 +27,6 @@ type proxyProviderSchema struct {
|
|||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
|
||||||
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,8 +63,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
|
excludeFilter := schema.ExcludeFilter
|
||||||
excludeType := schema.ExcludeType
|
return NewProxySetProvider(name, interval, filter, excludeFilter, vehicle, hc)
|
||||||
dialerProxy := schema.DialerProxy
|
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, vehicle, hc)
|
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,8 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
@ -17,10 +19,6 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel/statistic"
|
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -81,8 +79,6 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pp.OnUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
pp.getSubscriptionInfo()
|
|
||||||
pp.closeAllConnections()
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,7 +98,7 @@ func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
if pp.healthCheck.auto() {
|
if pp.healthCheck.auto() {
|
||||||
go pp.healthCheck.check()
|
defer func() { go pp.healthCheck.lazyCheck() }()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -140,33 +136,16 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) closeAllConnections() {
|
|
||||||
snapshot := statistic.DefaultManager.Snapshot()
|
|
||||||
for _, c := range snapshot.Connections {
|
|
||||||
for _, chain := range c.Chains() {
|
|
||||||
if chain == pp.Name() {
|
|
||||||
_ = c.Close()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.Fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, dialerProxy string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
}
|
}
|
||||||
var excludeTypeArray []string
|
|
||||||
if excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
var filterRegs []*regexp2.Regexp
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
filterReg, err := regexp2.Compile(filter, 0)
|
||||||
@ -185,8 +164,10 @@ 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, dialerProxy), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
|
pd.getSubscriptionInfo()
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -281,7 +262,7 @@ func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp, dialerProxy string) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
@ -301,28 +282,6 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
proxiesSet := map[string]struct{}{}
|
proxiesSet := map[string]struct{}{}
|
||||||
for _, filterReg := range filterRegs {
|
for _, filterReg := range filterRegs {
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
|
||||||
mType, ok := mapping["type"]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
pType, ok := mType.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
flag := false
|
|
||||||
for i := range excludeTypeArray {
|
|
||||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
mName, ok := mapping["name"]
|
mName, ok := mapping["name"]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@ -344,9 +303,6 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
if _, ok := proxiesSet[name]; ok {
|
if _, ok := proxiesSet[name]; ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(dialerProxy) > 0 {
|
|
||||||
mapping["dialer-proxy"] = dialerProxy
|
|
||||||
}
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
@ -1,205 +0,0 @@
|
|||||||
package atomic
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"sync/atomic"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Bool struct {
|
|
||||||
atomic.Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBool(val bool) *Bool {
|
|
||||||
i := &Bool{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Bool) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Bool) UnmarshalJSON(b []byte) error {
|
|
||||||
var v bool
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Bool) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatBool(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Pointer[T any] struct {
|
|
||||||
atomic.Pointer[T]
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPointer[T any](v *T) *Pointer[T] {
|
|
||||||
var p Pointer[T]
|
|
||||||
if v != nil {
|
|
||||||
p.Store(v)
|
|
||||||
}
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(p.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Pointer[T]) UnmarshalJSON(b []byte) error {
|
|
||||||
var v *T
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
p.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Pointer[T]) String() string {
|
|
||||||
return fmt.Sprint(p.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
type Int32 struct {
|
|
||||||
atomic.Int32
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInt32(val int32) *Int32 {
|
|
||||||
i := &Int32{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int32) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int32) UnmarshalJSON(b []byte) error {
|
|
||||||
var v int32
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int32) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatInt(int64(v), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Int64 struct {
|
|
||||||
atomic.Int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInt64(val int64) *Int64 {
|
|
||||||
i := &Int64{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int64) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int64) UnmarshalJSON(b []byte) error {
|
|
||||||
var v int64
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Int64) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatInt(int64(v), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Uint32 struct {
|
|
||||||
atomic.Uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUint32(val uint32) *Uint32 {
|
|
||||||
i := &Uint32{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint32) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint32) UnmarshalJSON(b []byte) error {
|
|
||||||
var v uint32
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint32) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatUint(uint64(v), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Uint64 struct {
|
|
||||||
atomic.Uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUint64(val uint64) *Uint64 {
|
|
||||||
i := &Uint64{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint64) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint64) UnmarshalJSON(b []byte) error {
|
|
||||||
var v uint64
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uint64) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatUint(uint64(v), 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Uintptr struct {
|
|
||||||
atomic.Uintptr
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUintptr(val uintptr) *Uintptr {
|
|
||||||
i := &Uintptr{}
|
|
||||||
i.Store(val)
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uintptr) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(i.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uintptr) UnmarshalJSON(b []byte) error {
|
|
||||||
var v uintptr
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
i.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *Uintptr) String() string {
|
|
||||||
v := i.Load()
|
|
||||||
return strconv.FormatUint(uint64(v), 10)
|
|
||||||
}
|
|
@ -1,58 +0,0 @@
|
|||||||
package atomic
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"sync/atomic"
|
|
||||||
)
|
|
||||||
|
|
||||||
func DefaultValue[T any]() T {
|
|
||||||
var defaultValue T
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
type TypedValue[T any] struct {
|
|
||||||
value atomic.Value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) Load() T {
|
|
||||||
value := t.value.Load()
|
|
||||||
if value == nil {
|
|
||||||
return DefaultValue[T]()
|
|
||||||
}
|
|
||||||
return value.(T)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) Store(value T) {
|
|
||||||
t.value.Store(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) Swap(new T) T {
|
|
||||||
old := t.value.Swap(new)
|
|
||||||
if old == nil {
|
|
||||||
return DefaultValue[T]()
|
|
||||||
}
|
|
||||||
return old.(T)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
|
||||||
return t.value.CompareAndSwap(old, new)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(t.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TypedValue[T]) UnmarshalJSON(b []byte) error {
|
|
||||||
var v T
|
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
t.Store(v)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTypedValue[T any](t T) *TypedValue[T] {
|
|
||||||
v := &TypedValue[T]{}
|
|
||||||
v.Store(t)
|
|
||||||
return v
|
|
||||||
}
|
|
@ -1,29 +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 NewSize = buf.NewSize
|
|
||||||
var StackNew = buf.StackNew
|
|
||||||
var StackNewSize = buf.StackNewSize
|
|
||||||
var With = buf.With
|
|
||||||
var As = buf.As
|
|
||||||
|
|
||||||
var KeepAlive = common.KeepAlive
|
|
||||||
|
|
||||||
//go:norace
|
|
||||||
func Dup[T any](obj T) T {
|
|
||||||
return common.Dup(obj)
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
Must = common.Must
|
|
||||||
Error = common.Error
|
|
||||||
)
|
|
@ -1,55 +0,0 @@
|
|||||||
package callback
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type firstWriteCallBackConn struct {
|
|
||||||
C.Conn
|
|
||||||
callback func(error)
|
|
||||||
written bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
|
||||||
defer func() {
|
|
||||||
if !c.written {
|
|
||||||
c.written = true
|
|
||||||
c.callback(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return c.Conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
|
|
||||||
defer func() {
|
|
||||||
if !c.written {
|
|
||||||
c.written = true
|
|
||||||
c.callback(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return c.Conn.WriteBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) Upstream() any {
|
|
||||||
return c.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) WriterReplaceable() bool {
|
|
||||||
return c.written
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.ExtendedConn = (*firstWriteCallBackConn)(nil)
|
|
||||||
|
|
||||||
func NewFirstWriteCallBackConn(c C.Conn, callback func(error)) C.Conn {
|
|
||||||
return &firstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
callback: callback,
|
|
||||||
written: false,
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,14 +2,11 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
@ -84,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 != "" {
|
||||||
@ -114,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":
|
||||||
@ -129,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)
|
||||||
}
|
}
|
||||||
@ -151,16 +138,20 @@ 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 != "" {
|
||||||
vmess["cipher"] = encryption
|
vmess["cipher"] = encryption
|
||||||
}
|
}
|
||||||
|
if packetEncoding := query.Get("packetEncoding"); packetEncoding != "" {
|
||||||
|
switch packetEncoding {
|
||||||
|
case "packet":
|
||||||
|
vmess["packet-addr"] = true
|
||||||
|
case "xudp":
|
||||||
|
vmess["xudp"] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
proxies = append(proxies, vmess)
|
proxies = append(proxies, vmess)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -171,11 +162,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
|
||||||
@ -189,7 +177,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
|
||||||
|
|
||||||
@ -202,8 +189,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["servername"] = sni
|
vmess["servername"] = sni
|
||||||
}
|
}
|
||||||
|
|
||||||
network, _ := values["net"].(string)
|
network := strings.ToLower(values["net"].(string))
|
||||||
network = strings.ToLower(network)
|
|
||||||
if values["type"] == "http" {
|
if values["type"] == "http" {
|
||||||
network = "http"
|
network = "http"
|
||||||
} else if network == "http" {
|
} else if network == "http" {
|
||||||
@ -211,12 +197,9 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
vmess["network"] = network
|
vmess["network"] = network
|
||||||
|
|
||||||
tls, ok := values["tls"].(string)
|
tls := strings.ToLower(values["tls"].(string))
|
||||||
if ok {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
tls = strings.ToLower(tls)
|
vmess["tls"] = true
|
||||||
if strings.HasSuffix(tls, "tls") {
|
|
||||||
vmess["tls"] = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
@ -289,25 +272,19 @@ 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, 10)
|
||||||
|
@ -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,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func RandHost() string {
|
func RandHost() string {
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(utils.NewUUIDV4().Bytes()))
|
id, _ := uuid.NewV4()
|
||||||
|
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
base = strings.ReplaceAll(base, "-", "")
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
base = strings.ReplaceAll(base, "_", "")
|
||||||
buf := []byte(base)
|
buf := []byte(base)
|
||||||
@ -302,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) {
|
||||||
@ -316,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()
|
||||||
@ -27,31 +18,12 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
proxy["skip-cert-verify"] = false
|
proxy["skip-cert-verify"] = false
|
||||||
proxy["tls"] = false
|
proxy["tls"] = false
|
||||||
tls := strings.ToLower(query.Get("security"))
|
tls := strings.ToLower(query.Get("security"))
|
||||||
if strings.HasSuffix(tls, "tls") || tls == "reality" {
|
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
|
||||||
}
|
}
|
||||||
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
|
|
||||||
proxy["reality-opts"] = map[string]any{
|
|
||||||
"public-key": realityPublicKey,
|
|
||||||
"short-id": query.Get("sid"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch query.Get("packetEncoding") {
|
|
||||||
case "none":
|
|
||||||
case "packet":
|
|
||||||
proxy["packet-addr"] = true
|
|
||||||
default:
|
|
||||||
proxy["xudp"] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
network := strings.ToLower(query.Get("type"))
|
||||||
if network == "" {
|
if network == "" {
|
||||||
@ -107,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":
|
||||||
@ -125,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 CustomAddr interface {
|
|
||||||
net.Addr
|
|
||||||
RawAddr() net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
type customAddr struct {
|
|
||||||
networkStr string
|
|
||||||
addrStr string
|
|
||||||
rawAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) Network() string {
|
|
||||||
return a.networkStr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) String() string {
|
|
||||||
return a.addrStr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) RawAddr() net.Addr {
|
|
||||||
return a.rawAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCustomAddr(networkStr string, addrStr string, rawAddr net.Addr) CustomAddr {
|
|
||||||
return customAddr{
|
|
||||||
networkStr: networkStr,
|
|
||||||
addrStr: addrStr,
|
|
||||||
rawAddr: rawAddr,
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,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,36 +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) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
length := c.r.Buffered()
|
|
||||||
b, _ := c.r.Peek(length)
|
|
||||||
_, _ = c.r.Discard(length)
|
|
||||||
return buf.As(b)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) ReaderReplaceable() bool {
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
@ -4,12 +4,10 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type refConn struct {
|
type refConn struct {
|
||||||
conn ExtendedConn
|
conn net.Conn
|
||||||
ref any
|
ref any
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -53,32 +51,8 @@ func (c *refConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return c.conn.SetWriteDeadline(t)
|
return c.conn.SetWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *refConn) Upstream() any {
|
|
||||||
return c.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) ReadBuffer(buffer *buf.Buffer) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) WriteBuffer(buffer *buf.Buffer) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.WriteBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) ReaderReplaceable() bool { // Relay() will handle reference
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) WriterReplaceable() bool { // Relay() will handle reference
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ ExtendedConn = (*refConn)(nil)
|
|
||||||
|
|
||||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
||||||
return &refConn{conn: NewExtendedConn(conn), ref: ref}
|
return &refConn{conn: conn, ref: ref}
|
||||||
}
|
}
|
||||||
|
|
||||||
type refPacketConn struct {
|
type refPacketConn struct {
|
||||||
|
@ -1,24 +1,24 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
//import (
|
import (
|
||||||
// "io"
|
"io"
|
||||||
// "net"
|
"net"
|
||||||
// "time"
|
"time"
|
||||||
//)
|
)
|
||||||
//
|
|
||||||
//// Relay copies between left and right bidirectionally.
|
// Relay copies between left and right bidirectionally.
|
||||||
//func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
// ch := make(chan error)
|
ch := make(chan error)
|
||||||
//
|
|
||||||
// go func() {
|
go func() {
|
||||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// // See also https://github.com/Dreamacro/clash/pull/1209
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
// leftConn.SetReadDeadline(time.Now())
|
leftConn.SetReadDeadline(time.Now())
|
||||||
// ch <- err
|
ch <- err
|
||||||
// }()
|
}()
|
||||||
//
|
|
||||||
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
// rightConn.SetReadDeadline(time.Now())
|
rightConn.SetReadDeadline(time.Now())
|
||||||
// <-ch
|
<-ch
|
||||||
//}
|
}
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
"github.com/sagernet/sing/common/bufio/deadline"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
var NewExtendedConn = bufio.NewExtendedConn
|
|
||||||
var NewExtendedWriter = bufio.NewExtendedWriter
|
|
||||||
var NewExtendedReader = bufio.NewExtendedReader
|
|
||||||
|
|
||||||
type ExtendedConn = network.ExtendedConn
|
|
||||||
type ExtendedWriter = network.ExtendedWriter
|
|
||||||
type ExtendedReader = network.ExtendedReader
|
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
|
||||||
return deadline.NewFallbackConn(conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDeadlinePacketConn(pc net.PacketConn) net.PacketConn {
|
|
||||||
return deadline.NewFallbackPacketConn(bufio.NewPacketConn(pc))
|
|
||||||
}
|
|
||||||
|
|
||||||
func NeedHandshake(conn any) bool {
|
|
||||||
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type CountFunc = network.CountFunc
|
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
|
||||||
defer runtime.KeepAlive(leftConn)
|
|
||||||
defer runtime.KeepAlive(rightConn)
|
|
||||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
|
||||||
}
|
|
@ -1,19 +1,11 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/big"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
if certificate == "" || privateKey == "" {
|
|
||||||
return newRandomTLSKeyPair()
|
|
||||||
}
|
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||||
if painTextErr == nil {
|
if painTextErr == nil {
|
||||||
return cert, nil
|
return cert, nil
|
||||||
@ -25,28 +17,3 @@ func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
|||||||
}
|
}
|
||||||
return cert, nil
|
return cert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
|
||||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
|
||||||
certDER, err := x509.CreateCertificate(
|
|
||||||
rand.Reader,
|
|
||||||
&template,
|
|
||||||
&template,
|
|
||||||
&key.PublicKey,
|
|
||||||
key)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
|
||||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
|
||||||
|
|
||||||
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
return tlsCert, nil
|
|
||||||
}
|
|
||||||
|
@ -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
|
|
||||||
}
|
|
@ -5,9 +5,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator[T any](item []T) chan T {
|
func iterator[T any](item []T) chan T {
|
||||||
@ -45,7 +44,7 @@ func TestObservable_MultiSubscribe(t *testing.T) {
|
|||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan int) {
|
waitCh := func(ch <-chan int) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count.Add(1)
|
count.Inc()
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math/rand"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(fastrand.Int())
|
msb(rand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,15 +0,0 @@
|
|||||||
//go:build with_low_memory
|
|
||||||
|
|
||||||
package pool
|
|
||||||
|
|
||||||
const (
|
|
||||||
// io.Copy default buffer size is 32 KiB
|
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
|
||||||
RelayBufferSize = 16 * 1024
|
|
||||||
|
|
||||||
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
|
||||||
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
|
||||||
// set to 9000, so the UDP Buffer size set to 16Kib
|
|
||||||
UDPBufferSize = 8 * 1024
|
|
||||||
)
|
|
@ -1,15 +0,0 @@
|
|||||||
//go:build !with_low_memory
|
|
||||||
|
|
||||||
package pool
|
|
||||||
|
|
||||||
const (
|
|
||||||
// io.Copy default buffer size is 32 KiB
|
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
|
||||||
RelayBufferSize = 20 * 1024
|
|
||||||
|
|
||||||
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
|
||||||
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
|
||||||
// set to 9000, so the UDP Buffer size set to 16Kib
|
|
||||||
UDPBufferSize = 16 * 1024
|
|
||||||
)
|
|
@ -1,5 +1,17 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
|
const (
|
||||||
|
// io.Copy default buffer size is 32 KiB
|
||||||
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
|
RelayBufferSize = 20 * 1024
|
||||||
|
|
||||||
|
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
||||||
|
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
||||||
|
// set to 9000, so the UDP Buffer size set to 16Kib
|
||||||
|
UDPBufferSize = 16 * 1024
|
||||||
|
)
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return defaultAllocator.Get(size)
|
return defaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
@ -5,9 +5,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBasic(t *testing.T) {
|
func TestBasic(t *testing.T) {
|
||||||
@ -27,7 +26,7 @@ func TestBasic(t *testing.T) {
|
|||||||
go func() {
|
go func() {
|
||||||
_, _, shard := single.Do(call)
|
_, _, shard := single.Do(call)
|
||||||
if shard {
|
if shard {
|
||||||
shardCount.Add(1)
|
shardCount.Inc()
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}()
|
}()
|
||||||
|
@ -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
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
func Reverse(s string) string {
|
|
||||||
a := []rune(s)
|
|
||||||
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
|
|
||||||
a[i], a[j] = a[j], a[i]
|
|
||||||
}
|
|
||||||
return string(a)
|
|
||||||
}
|
|
@ -1,51 +1,16 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid/v5"
|
"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{}))
|
|
||||||
|
|
||||||
func NewUUIDV1() uuid.UUID {
|
|
||||||
u, _ := UnsafeUUIDGenerator.NewV1() // fastrand.Read wouldn't cause error, so ignore err is safe
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUUIDV3(ns uuid.UUID, name string) uuid.UUID {
|
|
||||||
return UnsafeUUIDGenerator.NewV3(ns, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUUIDV4() uuid.UUID {
|
|
||||||
u, _ := UnsafeUUIDGenerator.NewV4() // fastrand.Read wouldn't cause error, so ignore err is safe
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUUIDV5(ns uuid.UUID, name string) uuid.UUID {
|
|
||||||
return UnsafeUUIDGenerator.NewV5(ns, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUUIDV6() uuid.UUID {
|
|
||||||
u, _ := UnsafeUUIDGenerator.NewV6() // fastrand.Read wouldn't cause error, so ignore err is safe
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUUIDV7() uuid.UUID {
|
|
||||||
u, _ := UnsafeUUIDGenerator.NewV7() // fastrand.Read wouldn't cause error, so ignore err is safe
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
func UUIDMap(str string) (uuid.UUID, error) {
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
u, err := uuid.FromString(str)
|
u, err := uuid.FromString(str)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewUUIDV5(uuid.Nil, str), nil
|
return uuid.NewV5(uuidNamespace, str), nil
|
||||||
}
|
}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gofrs/uuid/v5"
|
"github.com/gofrs/uuid"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
@ -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,101 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
IP_UNICAST_IF = 31
|
|
||||||
IPV6_UNICAST_IF = 31
|
|
||||||
)
|
|
||||||
|
|
||||||
func bind4(handle syscall.Handle, ifaceIdx int) error {
|
|
||||||
var bytes [4]byte
|
|
||||||
binary.BigEndian.PutUint32(bytes[:], uint32(ifaceIdx))
|
|
||||||
idx := *(*uint32)(unsafe.Pointer(&bytes[0]))
|
|
||||||
err := syscall.SetsockoptInt(handle, syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx))
|
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("bind4: %w", err)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func bind6(handle syscall.Handle, ifaceIdx int) error {
|
|
||||||
err := syscall.SetsockoptInt(handle, syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, ifaceIdx)
|
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("bind6: %w", err)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindControl(ifaceIdx int) controlFn {
|
|
||||||
return func(ctx context.Context, network, address string, c syscall.RawConn) (err error) {
|
|
||||||
addrPort, err := netip.ParseAddrPort(address)
|
|
||||||
if err == nil && !addrPort.Addr().IsGlobalUnicast() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var innerErr error
|
|
||||||
err = c.Control(func(fd uintptr) {
|
|
||||||
handle := syscall.Handle(fd)
|
|
||||||
bind6err := bind6(handle, ifaceIdx)
|
|
||||||
bind4err := bind4(handle, ifaceIdx)
|
|
||||||
switch network {
|
|
||||||
case "ip6", "tcp6":
|
|
||||||
innerErr = bind6err
|
|
||||||
case "ip4", "tcp4", "udp4":
|
|
||||||
innerErr = bind4err
|
|
||||||
case "udp6":
|
|
||||||
// golang will set network to udp6 when listenUDP on wildcard ip (eg: ":0", "")
|
|
||||||
if (!addrPort.Addr().IsValid() || addrPort.Addr().IsUnspecified()) && bind6err != nil {
|
|
||||||
// try bind ipv6, if failed, ignore. it's a workaround for windows disable interface ipv6
|
|
||||||
if bind4err != nil {
|
|
||||||
innerErr = fmt.Errorf("%w (%s)", bind6err, bind4err)
|
|
||||||
} else {
|
|
||||||
innerErr = nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
innerErr = bind6err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if innerErr != nil {
|
|
||||||
err = innerErr
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ netip.Addr) error {
|
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
addControlToDialer(dialer, bindControl(ifaceObj.Index))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
|
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
addControlToListenConfig(lc, bindControl(ifaceObj.Index))
|
|
||||||
return address, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ParseNetwork(network string, addr netip.Addr) string {
|
|
||||||
return network
|
|
||||||
}
|
|
@ -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,27 +2,40 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
)
|
|
||||||
|
|
||||||
type dialFunc func(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error)
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
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 ParseNetwork(network string, addr netip.Addr) string {
|
||||||
|
if runtime.GOOS == "windows" { // fix bindIfaceToListenConfig() in windows force bind to an ipv4 address
|
||||||
|
if !strings.HasSuffix(network, "4") &&
|
||||||
|
!strings.HasSuffix(network, "6") &&
|
||||||
|
addr.Unmap().Is6() {
|
||||||
|
network += "6"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return network
|
||||||
|
}
|
||||||
|
|
||||||
func applyOptions(options ...Option) *option {
|
func applyOptions(options ...Option) *option {
|
||||||
opt := &option{
|
opt := &option{
|
||||||
interfaceName: DefaultInterface.Load(),
|
interfaceName: DefaultInterface.Load(),
|
||||||
@ -53,23 +66,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 +108,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,182 +136,313 @@ 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 := resolver.SortationAddr(ips)
|
|
||||||
preferIPVersion := opt.prefer
|
|
||||||
|
|
||||||
fallbackTicker := time.NewTicker(fallbackTimeout)
|
|
||||||
defer fallbackTicker.Stop()
|
|
||||||
results := make(chan dialResult)
|
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
racer := func(ips []netip.Addr, isPrimary bool) {
|
|
||||||
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, r resolver.Resolver, ipv6 bool) {
|
||||||
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
case results <- result:
|
case results <- result:
|
||||||
case <-returned:
|
case <-returned:
|
||||||
if result.Conn != nil && 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 r == nil {
|
||||||
var fallback dialResult
|
ip, result.error = resolver.ResolveIPv6ProxyServerHost(ctx, 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.ResolveIPv6WithResolver(ctx, host, r)
|
||||||
errs = append([]error{fmt.Errorf("connect failed: %w", res.error)}, errs...)
|
}
|
||||||
} else {
|
} else {
|
||||||
errs = append(errs, fmt.Errorf("connect failed: %w", res.error))
|
if r == nil {
|
||||||
}
|
ip, result.error = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ip, result.error = resolver.ResolveIPv4WithResolver(ctx, host, r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if result.error != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result.resolved = true
|
||||||
|
|
||||||
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
}
|
}
|
||||||
if fallback.error == nil && fallback.Conn != nil {
|
|
||||||
return fallback.Conn, nil
|
go startRacer(ctx, network+"4", host, opt.resolver, false)
|
||||||
|
go startRacer(ctx, network+"6", host, opt.resolver, true)
|
||||||
|
|
||||||
|
count := 2
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
select {
|
||||||
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
|
return res.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !res.ipv6 {
|
||||||
|
primary = res
|
||||||
|
} else {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
|
||||||
|
if primary.done && fallback.done {
|
||||||
|
if primary.resolved {
|
||||||
|
return nil, primary.error
|
||||||
|
} else if fallback.resolved {
|
||||||
|
return nil, fallback.error
|
||||||
|
} else {
|
||||||
|
return nil, primary.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
err = ctx.Err()
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil, errorsJoin(errs...)
|
|
||||||
|
if err == nil {
|
||||||
|
err = fmt.Errorf("dual stack dial failed")
|
||||||
|
} else {
|
||||||
|
err = fmt.Errorf("dual stack dial failed:%w", err)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
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.resolver != nil {
|
||||||
|
ips, err = resolver.LookupIPWithResolver(ctx, host, opt.resolver)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
racer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
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
|
||||||
}
|
var primaryError error
|
||||||
return nil, os.ErrDeadlineExceeded
|
var finalError error
|
||||||
}
|
for i := 0; i < connCount; i++ {
|
||||||
|
select {
|
||||||
func serialDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
case res := <-results:
|
||||||
if len(ips) == 0 {
|
if res.error == nil {
|
||||||
return nil, ErrorNoIpAddress
|
if res.isPrimary {
|
||||||
}
|
return res.Conn, nil
|
||||||
var errs []error
|
} else {
|
||||||
for _, ip := range ips {
|
if !fallback.done || fallback.error != nil {
|
||||||
if conn, err := dialContext(ctx, network, ip, port, opt); err == nil {
|
fallback = res
|
||||||
return conn, nil
|
}
|
||||||
} else {
|
}
|
||||||
errs = append(errs, err)
|
} else {
|
||||||
|
if res.isPrimary {
|
||||||
|
primaryError = res.error
|
||||||
|
preferCount.Add(-1)
|
||||||
|
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
finalError = ctx.Err()
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, errorsJoin(errs...)
|
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if primaryError != nil {
|
||||||
|
return nil, primaryError
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback.error != nil {
|
||||||
|
return nil, fallback.error
|
||||||
|
}
|
||||||
|
|
||||||
|
if finalError == nil {
|
||||||
|
finalError = fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||||
|
} else {
|
||||||
|
finalError = fmt.Errorf("concurrent dial failed:%w", finalError)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, finalError
|
||||||
}
|
}
|
||||||
|
|
||||||
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.resolver == nil {
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, opt.resolver)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if opt.resolver == nil {
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, opt.resolver)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialContext(ctx, network, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
return concurrentIPv4DialContext(ctx, network, address, opt)
|
||||||
|
default:
|
||||||
|
return concurrentIPv6DialContext(ctx, network, address, opt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var ips []netip.Addr
|
var ips []netip.Addr
|
||||||
switch network {
|
if opt.resolver == nil {
|
||||||
case "tcp4", "udp4":
|
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
||||||
if preferResolver == nil {
|
} else {
|
||||||
ips, err = resolver.LookupIPv4ProxyServerHost(ctx, host)
|
ips, err = resolver.LookupIPv4WithResolver(ctx, host, opt.resolver)
|
||||||
} 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
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if opt.resolver == nil {
|
||||||
|
ips, err = resolver.LookupIPv6ProxyServerHost(ctx, host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.LookupIPv6WithResolver(ctx, host, opt.resolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Dialer struct {
|
type Dialer struct {
|
||||||
@ -318,12 +454,7 @@ func (d Dialer) DialContext(ctx context.Context, network, address string) (net.C
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
func (d Dialer) ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) {
|
||||||
opt := WithOption(d.Opt)
|
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, WithOption(d.Opt))
|
||||||
if rAddrPort.Addr().Unmap().IsLoopback() {
|
|
||||||
// avoid "The requested address is not valid in its context."
|
|
||||||
opt = WithInterface("")
|
|
||||||
}
|
|
||||||
return ListenPacket(ctx, ParseNetwork(network, rAddrPort.Addr()), address, opt)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDialer(options ...Option) Dialer {
|
func NewDialer(options ...Option) Dialer {
|
||||||
|
@ -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,22 +3,26 @@
|
|||||||
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() {
|
||||||
|
@ -1,32 +1,24 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
DefaultOptions []Option
|
DefaultOptions []Option
|
||||||
DefaultInterface = atomic.NewTypedValue[string]("")
|
DefaultInterface = atomic.NewString("")
|
||||||
DefaultRoutingMark = atomic.NewInt32(0)
|
DefaultRoutingMark = atomic.NewInt32(0)
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetDialer interface {
|
|
||||||
DialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type option struct {
|
type option struct {
|
||||||
interfaceName string
|
interfaceName string
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
network int
|
network int
|
||||||
prefer int
|
prefer int
|
||||||
tfo bool
|
|
||||||
resolver resolver.Resolver
|
resolver resolver.Resolver
|
||||||
netDialer NetDialer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -77,18 +69,6 @@ func WithOnlySingleStack(isIPv4 bool) Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithTFO(tfo bool) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.tfo = tfo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithNetDialer(netDialer NetDialer) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.netDialer = netDialer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithOption(o option) Option {
|
func WithOption(o option) Option {
|
||||||
return func(opt *option) {
|
return func(opt *option) {
|
||||||
*opt = o
|
*opt = o
|
||||||
|
@ -3,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,135 +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) NeedAdditionalReadDeadline() bool {
|
|
||||||
return c.Conn == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) NeedHandshake() bool {
|
|
||||||
return c.Conn == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) ReaderReplaceable() bool {
|
|
||||||
return c.Conn != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *tfoConn) WriterReplaceable() bool {
|
|
||||||
return c.Conn != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func dialTFO(ctx context.Context, netDialer net.Dialer, network, address string) (net.Conn, error) {
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
dialer := tfo.Dialer{Dialer: netDialer, DisableTFO: false}
|
|
||||||
return &tfoConn{
|
|
||||||
dialed: make(chan bool, 1),
|
|
||||||
cancel: cancel,
|
|
||||||
ctx: ctx,
|
|
||||||
dialFn: func(ctx context.Context, earlyData []byte) (net.Conn, error) {
|
|
||||||
return dialer.DialContext(ctx, network, address, earlyData)
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
@ -41,9 +41,9 @@ func loadBpf() (*ebpf.CollectionSpec, error) {
|
|||||||
//
|
//
|
||||||
// The following types are suitable as obj argument:
|
// The following types are suitable as obj argument:
|
||||||
//
|
//
|
||||||
// *bpfObjects
|
// *bpfObjects
|
||||||
// *bpfPrograms
|
// *bpfPrograms
|
||||||
// *bpfMaps
|
// *bpfMaps
|
||||||
//
|
//
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
@ -134,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
|
||||||
|
@ -1,10 +1,13 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type loader struct {
|
type loader struct {
|
||||||
@ -12,7 +15,47 @@ type loader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||||
return l.LoadSiteByPath(C.GeositeName, list)
|
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
||||||
|
parts := strings.Split(siteWithAttr, "@")
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return nil, errors.New("empty rule")
|
||||||
|
}
|
||||||
|
list := strings.TrimSpace(parts[0])
|
||||||
|
attrVal := parts[1:]
|
||||||
|
|
||||||
|
if len(list) == 0 {
|
||||||
|
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
||||||
|
}
|
||||||
|
|
||||||
|
domains, err := l.LoadSiteByPath(file, list)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := parseAttrs(attrVal)
|
||||||
|
if attrs.IsEmpty() {
|
||||||
|
if strings.Contains(siteWithAttr, "@") {
|
||||||
|
log.Warnln("empty attribute list: %s", siteWithAttr)
|
||||||
|
}
|
||||||
|
return domains, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
filteredDomains := make([]*router.Domain, 0, len(domains))
|
||||||
|
hasAttrMatched := false
|
||||||
|
for _, domain := range domains {
|
||||||
|
if attrs.Match(domain) {
|
||||||
|
hasAttrMatched = true
|
||||||
|
filteredDomains = append(filteredDomains, domain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hasAttrMatched {
|
||||||
|
log.Warnln("attribute match no rule: geosite: %s", siteWithAttr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredDomains, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
|
@ -14,5 +14,6 @@ type LoaderImplementation interface {
|
|||||||
type Loader interface {
|
type Loader interface {
|
||||||
LoaderImplementation
|
LoaderImplementation
|
||||||
LoadGeoSite(list string) ([]*router.Domain, error)
|
LoadGeoSite(list string) ([]*router.Domain, error)
|
||||||
|
LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error)
|
||||||
LoadGeoIP(country string) ([]*router.CIDR, error)
|
LoadGeoIP(country string) ([]*router.CIDR, error)
|
||||||
}
|
}
|
||||||
|
@ -1,21 +1,15 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
|
||||||
|
|
||||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
|
||||||
"github.com/Dreamacro/clash/component/mmdb"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var initGeoSite bool
|
var initFlag bool
|
||||||
var initGeoIP int
|
|
||||||
|
|
||||||
func InitGeoSite() error {
|
func InitGeoSite() error {
|
||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
@ -24,9 +18,8 @@ func InitGeoSite() error {
|
|||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
log.Infoln("Download GeoSite.dat finish")
|
log.Infoln("Download GeoSite.dat finish")
|
||||||
initGeoSite = false
|
|
||||||
}
|
}
|
||||||
if !initGeoSite {
|
if !initFlag {
|
||||||
if err := Verify(C.GeositeName); err != nil {
|
if err := Verify(C.GeositeName); err != nil {
|
||||||
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
||||||
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
||||||
@ -36,15 +29,13 @@ func InitGeoSite() error {
|
|||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
initGeoSite = true
|
initFlag = true
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoSite(path string) (err error) {
|
func downloadGeoSite(path string) (err error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
resp, err := http.Get(C.GeoSiteUrl)
|
||||||
defer cancel()
|
|
||||||
resp, err := clashHttp.HttpRequest(ctx, C.GeoSiteUrl, http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -59,70 +50,3 @@ func downloadGeoSite(path string) (err error) {
|
|||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoIP(path string) (err error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
|
||||||
defer cancel()
|
|
||||||
resp, err := clashHttp.HttpRequest(ctx, C.GeoIpUrl, http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, resp.Body)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitGeoIP() error {
|
|
||||||
if C.GeodataMode {
|
|
||||||
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
|
||||||
log.Infoln("Can't find GeoIP.dat, start download")
|
|
||||||
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
log.Infoln("Download GeoIP.dat finish")
|
|
||||||
initGeoIP = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if initGeoIP != 1 {
|
|
||||||
if err := Verify(C.GeoipName); err != nil {
|
|
||||||
log.Warnln("GeoIP.dat invalid, remove and download: %s", err)
|
|
||||||
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
initGeoIP = 1
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
|
||||||
log.Infoln("Can't find MMDB, start download")
|
|
||||||
if err := mmdb.DownloadMMDB(C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if initGeoIP != 2 {
|
|
||||||
if !mmdb.Verify() {
|
|
||||||
log.Warnln("MMDB invalid, remove and download")
|
|
||||||
if err := os.Remove(C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't remove invalid MMDB: %s", err.Error())
|
|
||||||
}
|
|
||||||
if err := mmdb.DownloadMMDB(C.Path.MMDB()); err != nil {
|
|
||||||
return fmt.Errorf("can't download MMDB: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
initGeoIP = 2
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
@ -118,7 +118,7 @@ func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error)
|
|||||||
|
|
||||||
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
||||||
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
||||||
log.Warnln("failed to decode geosite file: %s%s", filename, ", fallback to the original ReadFile method")
|
log.Warnln("failed to decode geoip file: %s%s", filename, ", fallback to the original ReadFile method")
|
||||||
geositeBytes, err = os.ReadFile(asset)
|
geositeBytes, err = os.ReadFile(asset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -1,14 +1,9 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"golang.org/x/sync/singleflight"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
var geoLoaderName = "memconservative"
|
||||||
@ -39,8 +34,6 @@ func Verify(name string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var loadGeoSiteMatcherSF = singleflight.Group{}
|
|
||||||
|
|
||||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
||||||
if len(countryCode) == 0 {
|
if len(countryCode) == 0 {
|
||||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
@ -51,52 +44,15 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
not = true
|
not = true
|
||||||
countryCode = countryCode[1:]
|
countryCode = countryCode[1:]
|
||||||
}
|
}
|
||||||
countryCode = strings.ToLower(countryCode)
|
|
||||||
|
|
||||||
parts := strings.Split(countryCode, "@")
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
if len(parts) == 0 {
|
|
||||||
return nil, 0, errors.New("empty rule")
|
|
||||||
}
|
|
||||||
listName := strings.TrimSpace(parts[0])
|
|
||||||
attrVal := parts[1:]
|
|
||||||
|
|
||||||
if len(listName) == 0 {
|
|
||||||
return nil, 0, fmt.Errorf("empty listname in rule: %s", countryCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
v, err, shared := loadGeoSiteMatcherSF.Do(listName, func() (interface{}, error) {
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return geoLoader.LoadGeoSite(listName)
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !shared {
|
|
||||||
loadGeoSiteMatcherSF.Forget(listName) // don't store the error result
|
|
||||||
}
|
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
domains := v.([]*router.Domain)
|
|
||||||
|
|
||||||
attrs := parseAttrs(attrVal)
|
domains, err := geoLoader.LoadGeoSite(countryCode)
|
||||||
if attrs.IsEmpty() {
|
if err != nil {
|
||||||
if strings.Contains(countryCode, "@") {
|
return nil, 0, err
|
||||||
log.Warnln("empty attribute list: %s", countryCode)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filteredDomains := make([]*router.Domain, 0, len(domains))
|
|
||||||
hasAttrMatched := false
|
|
||||||
for _, domain := range domains {
|
|
||||||
if attrs.Match(domain) {
|
|
||||||
hasAttrMatched = true
|
|
||||||
filteredDomains = append(filteredDomains, domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hasAttrMatched {
|
|
||||||
log.Warnln("attribute match no rule: geosite: %s", countryCode)
|
|
||||||
}
|
|
||||||
domains = filteredDomains
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -112,34 +68,25 @@ func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error)
|
|||||||
return matcher, len(domains), nil
|
return matcher, len(domains), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var loadGeoIPMatcherSF = singleflight.Group{}
|
|
||||||
|
|
||||||
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
||||||
if len(country) == 0 {
|
if len(country) == 0 {
|
||||||
return nil, 0, fmt.Errorf("country code could not be empty")
|
return nil, 0, fmt.Errorf("country code could not be empty")
|
||||||
}
|
}
|
||||||
|
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
not := false
|
not := false
|
||||||
if country[0] == '!' {
|
if country[0] == '!' {
|
||||||
not = true
|
not = true
|
||||||
country = country[1:]
|
country = country[1:]
|
||||||
}
|
}
|
||||||
country = strings.ToLower(country)
|
|
||||||
|
|
||||||
v, err, shared := loadGeoIPMatcherSF.Do(country, func() (interface{}, error) {
|
records, err := geoLoader.LoadGeoIP(country)
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return geoLoader.LoadGeoIP(country)
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !shared {
|
|
||||||
loadGeoIPMatcherSF.Forget(country) // don't store the error result
|
|
||||||
}
|
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
records := v.([]*router.CIDR)
|
|
||||||
|
|
||||||
geoIP := &router.GeoIP{
|
geoIP := &router.GeoIP{
|
||||||
CountryCode: country,
|
CountryCode: country,
|
||||||
@ -151,10 +98,6 @@ func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return matcher, len(records), nil
|
return matcher, len(records), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ClearCache() {
|
|
||||||
loadGeoSiteMatcherSF = singleflight.Group{}
|
|
||||||
loadGeoIPMatcherSF = singleflight.Group{}
|
|
||||||
}
|
|
||||||
|
@ -2,19 +2,18 @@ package http
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/listener/inner"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
URL "net/url"
|
URL "net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/tls"
|
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
UA = "clash.meta"
|
UA = "Clash"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
|
||||||
@ -53,7 +52,7 @@ func HttpRequest(ctx context.Context, url, method string, header map[string][]st
|
|||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
conn := inner.HandleTcp(address, "")
|
conn := inner.HandleTcp(address, urlRes.Hostname())
|
||||||
return conn, nil
|
return conn, nil
|
||||||
},
|
},
|
||||||
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
TLSClientConfig: tls.GetDefaultTLSConfig(),
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user