Compare commits
7 Commits
Meta
...
dev-vision
Author | SHA1 | Date | |
---|---|---|---|
![]() |
66f108bf24 | ||
![]() |
c5444a03ac | ||
![]() |
9aacfe11e7 | ||
![]() |
11e0bbebf4 | ||
![]() |
fc58f80cc8 | ||
![]() |
abced62f4d | ||
![]() |
4f27911659 |
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
|
|
||||||
"
|
|
32
.github/genReleaseNote.sh
vendored
32
.github/genReleaseNote.sh
vendored
@ -1,32 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
while getopts "v:" opt; do
|
|
||||||
case $opt in
|
|
||||||
v)
|
|
||||||
version_range=$OPTARG
|
|
||||||
;;
|
|
||||||
\?)
|
|
||||||
echo "Invalid option: -$OPTARG" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -z "$version_range" ]; then
|
|
||||||
echo "Please provide the version range using -v option. Example: ./genReleashNote.sh -v v1.14.1...v1.14.2"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "## What's Changed" > release.md
|
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
|
||||||
echo "" >> release.md
|
|
||||||
|
|
||||||
echo "## BUG & Fix" >> release.md
|
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
|
||||||
echo "" >> release.md
|
|
||||||
|
|
||||||
echo "## Maintenance" >> release.md
|
|
||||||
git log --pretty=format:"* %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
|
||||||
echo "" >> release.md
|
|
||||||
|
|
||||||
echo "**Full Changelog**: https://github.com/MetaCubeX/Clash.Meta/compare/$version_range" >> release.md
|
|
9
.github/rename-cgo.sh
vendored
9
.github/rename-cgo.sh
vendored
@ -15,15 +15,6 @@ do
|
|||||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
echo "rename windows amd64 $FILENAME"
|
echo "rename windows amd64 $FILENAME"
|
||||||
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
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
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
echo "rename linux $FILENAME"
|
echo "rename linux $FILENAME"
|
||||||
mv $FILENAME $FILENAME-cgo
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
98
.github/workflows/build.yml
vendored
98
.github/workflows/build.yml
vendored
@ -5,19 +5,17 @@ on:
|
|||||||
paths-ignore:
|
paths-ignore:
|
||||||
- "docs/**"
|
- "docs/**"
|
||||||
- "README.md"
|
- "README.md"
|
||||||
- ".github/ISSUE_TEMPLATE/**"
|
|
||||||
branches:
|
branches:
|
||||||
- Alpha
|
- Alpha
|
||||||
|
- Beta
|
||||||
|
- Meta
|
||||||
tags:
|
tags:
|
||||||
- "v*"
|
- "v*"
|
||||||
pull_request_target:
|
pull_request_target:
|
||||||
branches:
|
branches:
|
||||||
- Alpha
|
- Alpha
|
||||||
|
- Beta
|
||||||
concurrency:
|
- Meta
|
||||||
group: ${{ github.ref }}-${{ github.workflow }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: docker.io
|
REGISTRY: docker.io
|
||||||
jobs:
|
jobs:
|
||||||
@ -48,26 +46,25 @@ jobs:
|
|||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
||||||
id: "4",
|
id: "4",
|
||||||
}
|
}
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
|
||||||
- {
|
- {
|
||||||
type: "WithoutCGO",
|
type: "WithoutCGO",
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
||||||
id: "6",
|
id: "5",
|
||||||
}
|
}
|
||||||
- {
|
- {
|
||||||
type: "WithoutCGO",
|
type: "WithoutCGO",
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
target: "windows-amd64-compatible windows-amd64 windows-386",
|
||||||
id: "7",
|
id: "6",
|
||||||
}
|
}
|
||||||
- {
|
- {
|
||||||
type: "WithoutCGO",
|
type: "WithoutCGO",
|
||||||
target: "windows-arm64 windows-arm32v7",
|
target: "windows-arm64 windows-arm32v7",
|
||||||
id: "8",
|
id: "7",
|
||||||
}
|
}
|
||||||
- {
|
- {
|
||||||
type: "WithoutCGO",
|
type: "WithoutCGO",
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
target: "darwin-amd64 darwin-arm64 android-arm64",
|
||||||
id: "9",
|
id: "8",
|
||||||
}
|
}
|
||||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
- { type: "WithCGO", target: "windows/*", id: "1" }
|
||||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
- { type: "WithCGO", target: "linux/386", id: "2" }
|
||||||
@ -94,6 +91,11 @@ jobs:
|
|||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
shell: bash
|
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
|
- name: Set variables
|
||||||
if: ${{github.ref_name=='Meta'}}
|
if: ${{github.ref_name=='Meta'}}
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
@ -106,11 +108,10 @@ jobs:
|
|||||||
|
|
||||||
- name: Set ENV
|
- name: Set ENV
|
||||||
run: |
|
run: |
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
|
||||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
echo "NAME=clash.meta" >> $GITHUB_ENV
|
||||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
||||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
echo "BUILDTIME=$(date -u)" >> $GITHUB_ENV
|
||||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
@ -121,9 +122,9 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: "1.21"
|
go-version: "1.20"
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
@ -142,7 +143,7 @@ jobs:
|
|||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
||||||
id: setup-ndk
|
id: setup-ndk
|
||||||
with:
|
with:
|
||||||
ndk-version: r26
|
ndk-version: r25b
|
||||||
add-to-path: false
|
add-to-path: false
|
||||||
local-cache: true
|
local-cache: true
|
||||||
|
|
||||||
@ -192,10 +193,6 @@ jobs:
|
|||||||
ls -la
|
ls -la
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
- name: Save version
|
|
||||||
run: echo ${VERSION} > bin/version.txt
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
- uses: actions/upload-artifact@v3
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
@ -204,8 +201,8 @@ jobs:
|
|||||||
|
|
||||||
Upload-Prerelease:
|
Upload-Prerelease:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='branch' && github.event_name != 'pull_request' }}
|
if: ${{ github.ref_type=='branch' }}
|
||||||
needs: [Build]
|
needs: [ Build ]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v3
|
||||||
@ -218,17 +215,12 @@ jobs:
|
|||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Delete current release assets
|
- name: Delete current release assets
|
||||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
deleteOnlyFromDrafts: false
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
- name: Set Env
|
|
||||||
run: |
|
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Tag Repo
|
- name: Tag Repo
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
uses: richardsimko/update-tag@v1.0.6
|
||||||
with:
|
with:
|
||||||
@ -236,49 +228,22 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
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>
|
|
||||||
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/Clash.Meta/wiki/FAQ)
|
|
||||||
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
- name: Upload Prerelease
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
|
tag: ${{ github.ref_name }}
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
files: |
|
files: bin/*
|
||||||
bin/*
|
|
||||||
prerelease: true
|
prerelease: true
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
Upload-Release:
|
Upload-Release:
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
if: ${{ github.ref_type=='tag' }}
|
if: ${{ github.ref_type=='tag' }}
|
||||||
needs: [Build]
|
needs: [ Build ]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Get tags
|
|
||||||
run: |
|
|
||||||
echo "CURRENTVERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
|
||||||
git fetch --tags
|
|
||||||
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD^)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Generate release notes
|
|
||||||
run: |
|
|
||||||
cp ./.github/genReleaseNote.sh ./
|
|
||||||
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
|
||||||
rm ./genReleaseNote.sh
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
- uses: actions/download-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: artifact
|
name: artifact
|
||||||
@ -292,15 +257,14 @@ jobs:
|
|||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
if: ${{ success() }}
|
if: ${{ success() }}
|
||||||
with:
|
with:
|
||||||
|
tag: ${{ github.ref_name }}
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.ref_name }}
|
||||||
files: bin/*
|
files: bin/*
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
body_path: release.md
|
|
||||||
|
|
||||||
Docker:
|
Docker:
|
||||||
if: ${{ github.event_name != 'pull_request' }}
|
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
needs: [Build]
|
needs: [ Build ]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
@ -318,10 +282,10 @@ jobs:
|
|||||||
working-directory: bin
|
working-directory: bin
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2
|
uses: docker/setup-qemu-action@v1
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
- name: Setup Docker buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v1
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
|
|
||||||
@ -329,7 +293,7 @@ jobs:
|
|||||||
# https://github.com/docker/metadata-action
|
# https://github.com/docker/metadata-action
|
||||||
- name: Extract Docker metadata
|
- name: Extract Docker metadata
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v4
|
uses: docker/metadata-action@v3
|
||||||
with:
|
with:
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
||||||
- name: Show files
|
- name: Show files
|
||||||
@ -338,7 +302,7 @@ jobs:
|
|||||||
ls bin/
|
ls bin/
|
||||||
- name: Log into registry
|
- name: Log into registry
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v1
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
@ -348,7 +312,7 @@ jobs:
|
|||||||
# https://github.com/docker/build-push-action
|
# https://github.com/docker/build-push-action
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
id: build-and-push
|
id: build-and-push
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v2
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
@ -357,7 +321,5 @@ jobs:
|
|||||||
linux/386
|
linux/386
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64/v8
|
linux/arm64/v8
|
||||||
linux/arm/v7
|
|
||||||
# linux/riscv64
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
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
|
|
10
Dockerfile
10
Dockerfile
@ -1,18 +1,16 @@
|
|||||||
FROM alpine:latest as builder
|
FROM alpine:latest as builder
|
||||||
ARG TARGETPLATFORM
|
|
||||||
RUN echo "I'm building for $TARGETPLATFORM"
|
|
||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /clash-config && \
|
mkdir /clash-config && \
|
||||||
wget -O /clash-config/geoip.metadb https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.metadb && \
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
wget -O /clash-config/geosite.dat https://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/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://fastly.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@release/geoip.dat
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
|
|
||||||
COPY docker/file-name.sh /clash/file-name.sh
|
COPY docker/file-name.sh /clash/file-name.sh
|
||||||
WORKDIR /clash
|
WORKDIR /clash
|
||||||
COPY bin/ bin/
|
COPY bin/ bin/
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && \
|
||||||
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
mv bin/$FILE_NAME clash.gz && gzip -d clash.gz && echo "$FILE_NAME" > /clash-config/test
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
8
Makefile
8
Makefile
@ -31,8 +31,6 @@ PLATFORM_LIST = \
|
|||||||
linux-mips-hardfloat \
|
linux-mips-hardfloat \
|
||||||
linux-mipsle-softfloat \
|
linux-mipsle-softfloat \
|
||||||
linux-mipsle-hardfloat \
|
linux-mipsle-hardfloat \
|
||||||
linux-riscv64 \
|
|
||||||
linux-loong64 \
|
|
||||||
android-arm64 \
|
android-arm64 \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64 \
|
freebsd-amd64 \
|
||||||
@ -103,12 +101,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)-$@
|
|
||||||
|
|
||||||
linux-loong64:
|
|
||||||
GOARCH=loong64 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)-$@
|
||||||
|
|
||||||
|
35
README.md
35
README.md
@ -24,22 +24,14 @@
|
|||||||
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
||||||
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
||||||
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
||||||
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
||||||
based off latency
|
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
||||||
- Remote providers, allowing users to get node lists remotely instead of hard-coding in config
|
|
||||||
- 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
|
||||||
|
|
||||||
## Dashboard
|
|
||||||
|
|
||||||
We made an official web dashboard providing first class support for this project, check it out
|
|
||||||
at [metacubexd](https://github.com/MetaCubeX/metacubexd)
|
|
||||||
|
|
||||||
## Wiki
|
## Wiki
|
||||||
|
|
||||||
Configuration examples can be found
|
Documentation and configuring examples are available on [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki) and [Clash.Meta Wiki](https://docs.metacubex.one/).
|
||||||
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).
|
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
@ -52,7 +44,7 @@ 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
|
||||||
@ -333,27 +325,36 @@ ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clash-meta daemon on system startup with:
|
Launch clashd on system startup with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ systemctl enable Clash-Meta
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clash-meta daemon immediately with:
|
Launch clashd immediately with:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ systemctl start Clash-Meta
|
$ systemctl start Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Display Process name
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
### 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
|
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
|
## Debugging
|
||||||
|
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
||||||
|
|
||||||
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug
|
|
||||||
API.
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
|
@ -3,42 +3,25 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"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"
|
||||||
"strconv"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
"go.uber.org/atomic"
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"github.com/puzpuzpuz/xsync/v2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
|
|
||||||
const (
|
|
||||||
defaultHistoriesNum = 10
|
|
||||||
)
|
|
||||||
|
|
||||||
type extraProxyState struct {
|
|
||||||
history *queue.Queue[C.DelayHistory]
|
|
||||||
alive *atomic.Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
alive *atomic.Bool
|
alive *atomic.Bool
|
||||||
url string
|
|
||||||
extra *xsync.MapOf[string, *extraProxyState]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alive implements C.Proxy
|
// Alive implements C.Proxy
|
||||||
@ -46,15 +29,6 @@ func (p *Proxy) Alive() bool {
|
|||||||
return p.alive.Load()
|
return p.alive.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
// AliveForTestUrl implements C.Proxy
|
|
||||||
func (p *Proxy) AliveForTestUrl(url string) bool {
|
|
||||||
if state, ok := p.extra.Load(url); ok {
|
|
||||||
return state.alive.Load()
|
|
||||||
}
|
|
||||||
|
|
||||||
return p.alive.Load()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dial implements C.Proxy
|
// Dial implements C.Proxy
|
||||||
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
||||||
@ -88,51 +62,9 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|||||||
for _, item := range queueM {
|
for _, item := range queueM {
|
||||||
histories = append(histories, item)
|
histories = append(histories, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
// DelayHistoryForTestUrl implements C.Proxy
|
|
||||||
func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
|
||||||
var queueM []C.DelayHistory
|
|
||||||
|
|
||||||
if state, ok := p.extra.Load(url); ok {
|
|
||||||
queueM = state.history.Copy()
|
|
||||||
}
|
|
||||||
|
|
||||||
if queueM == nil {
|
|
||||||
queueM = p.history.Copy()
|
|
||||||
}
|
|
||||||
|
|
||||||
histories := []C.DelayHistory{}
|
|
||||||
for _, item := range queueM {
|
|
||||||
histories = append(histories, item)
|
|
||||||
}
|
|
||||||
return histories
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *Proxy) ExtraDelayHistory() map[string][]C.DelayHistory {
|
|
||||||
extraHistory := map[string][]C.DelayHistory{}
|
|
||||||
|
|
||||||
p.extra.Range(func(k string, v *extraProxyState) bool {
|
|
||||||
|
|
||||||
testUrl := k
|
|
||||||
state := v
|
|
||||||
|
|
||||||
histories := []C.DelayHistory{}
|
|
||||||
queueM := state.history.Copy()
|
|
||||||
|
|
||||||
for _, item := range queueM {
|
|
||||||
histories = append(histories, item)
|
|
||||||
}
|
|
||||||
|
|
||||||
extraHistory[testUrl] = histories
|
|
||||||
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return extraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) LastDelay() (delay uint16) {
|
func (p *Proxy) LastDelay() (delay uint16) {
|
||||||
@ -148,28 +80,6 @@ func (p *Proxy) LastDelay() (delay uint16) {
|
|||||||
return history.Delay
|
return history.Delay
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastDelayForTestUrl implements C.Proxy
|
|
||||||
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
|
||||||
var max uint16 = 0xffff
|
|
||||||
|
|
||||||
alive := p.alive.Load()
|
|
||||||
history := p.history.Last()
|
|
||||||
|
|
||||||
if state, ok := p.extra.Load(url); ok {
|
|
||||||
alive = state.alive.Load()
|
|
||||||
history = state.history.Last()
|
|
||||||
}
|
|
||||||
|
|
||||||
if !alive {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
if history.Delay == 0 {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
return history.Delay
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
func (p *Proxy) MarshalJSON() ([]byte, error) {
|
||||||
inner, err := p.ProxyAdapter.MarshalJSON()
|
inner, err := p.ProxyAdapter.MarshalJSON()
|
||||||
@ -180,8 +90,6 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping := map[string]any{}
|
mapping := map[string]any{}
|
||||||
_ = json.Unmarshal(inner, &mapping)
|
_ = json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["extra"] = p.ExtraDelayHistory()
|
|
||||||
mapping["alive"] = p.Alive()
|
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["xudp"] = p.SupportXUDP()
|
mapping["xudp"] = p.SupportXUDP()
|
||||||
@ -191,54 +99,17 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16], store C.DelayHistoryStoreType) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
alive := err == nil
|
p.alive.Store(err == nil)
|
||||||
store = p.determineFinalStoreType(store, url)
|
|
||||||
|
|
||||||
switch store {
|
|
||||||
case C.OriginalHistory:
|
|
||||||
p.alive.Store(alive)
|
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
if alive {
|
if err == nil {
|
||||||
record.Delay = t
|
record.Delay = t
|
||||||
}
|
}
|
||||||
p.history.Put(record)
|
p.history.Put(record)
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
if p.history.Len() > 10 {
|
||||||
p.history.Pop()
|
p.history.Pop()
|
||||||
}
|
}
|
||||||
|
|
||||||
// test URL configured by the proxy provider
|
|
||||||
if len(p.url) == 0 {
|
|
||||||
p.url = url
|
|
||||||
}
|
|
||||||
case C.ExtraHistory:
|
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
|
||||||
if alive {
|
|
||||||
record.Delay = t
|
|
||||||
}
|
|
||||||
p.history.Put(record)
|
|
||||||
if p.history.Len() > defaultHistoriesNum {
|
|
||||||
p.history.Pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
state, ok := p.extra.Load(url)
|
|
||||||
if !ok {
|
|
||||||
state = &extraProxyState{
|
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
|
||||||
alive: atomic.NewBool(true),
|
|
||||||
}
|
|
||||||
p.extra.Store(url, state)
|
|
||||||
}
|
|
||||||
|
|
||||||
state.alive.Store(alive)
|
|
||||||
state.history.Put(record)
|
|
||||||
if state.history.Len() > defaultHistoriesNum {
|
|
||||||
state.history.Pop()
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
log.Debugln("health check result will be discarded, url: %s alive: %t, delay: %d", url, alive, t)
|
|
||||||
}
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
@ -301,22 +172,12 @@ func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.In
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if expectedStatus != nil && !expectedStatus.Check(uint16(resp.StatusCode)) {
|
|
||||||
// maybe another value should be returned for differentiation
|
|
||||||
err = errors.New("response status is inconsistent with the expected status")
|
|
||||||
}
|
|
||||||
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{
|
return &Proxy{adapter, queue.New[C.DelayHistory](10), atomic.NewBool(true)}
|
||||||
ProxyAdapter: adapter,
|
|
||||||
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
|
||||||
alive: atomic.NewBool(true),
|
|
||||||
url: "",
|
|
||||||
extra: xsync.NewMapOf[*extraProxyState]()}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
@ -337,36 +198,11 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
uintPort, err := strconv.ParseUint(port, 10, 16)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
Host: u.Hostname(),
|
Host: u.Hostname(),
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: uint16(uintPort),
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Proxy) determineFinalStoreType(store C.DelayHistoryStoreType, url string) C.DelayHistoryStoreType {
|
|
||||||
if store != C.DropHistory {
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(p.url) == 0 || url == p.url {
|
|
||||||
return C.OriginalHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.extra.Size() < 2*C.DefaultMaxHealthCheckUrlNum {
|
|
||||||
return C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok := p.extra.Load(url)
|
|
||||||
if ok {
|
|
||||||
return C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
return store
|
|
||||||
}
|
|
||||||
|
@ -16,12 +16,6 @@ func WithInName(name string) Addition {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithInUser(user string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.InUser = user
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSpecialRules(specialRules string) Addition {
|
func WithSpecialRules(specialRules string) Addition {
|
||||||
return func(metadata *C.Metadata) {
|
return func(metadata *C.Metadata) {
|
||||||
metadata.SpecialRules = specialRules
|
metadata.SpecialRules = specialRules
|
||||||
|
@ -17,10 +17,6 @@ func SetTfo(open bool) {
|
|||||||
lc.DisableTFO = !open
|
lc.DisableTFO = !open
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetMPTCP(open bool) {
|
|
||||||
setMultiPathTCP(&lc.ListenConfig, open)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||||
return lc.Listen(ctx, network, address)
|
return lc.Listen(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
@ -1,10 +0,0 @@
|
|||||||
//go:build !go1.21
|
|
||||||
|
|
||||||
package inbound
|
|
||||||
|
|
||||||
import "net"
|
|
||||||
|
|
||||||
const multipathTCPAvailable = false
|
|
||||||
|
|
||||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
//go:build go1.21
|
|
||||||
|
|
||||||
package inbound
|
|
||||||
|
|
||||||
import "net"
|
|
||||||
|
|
||||||
const multipathTCPAvailable = true
|
|
||||||
|
|
||||||
func setMultiPathTCP(listenConfig *net.ListenConfig, open bool) {
|
|
||||||
listenConfig.SetMultipathTCP(open)
|
|
||||||
}
|
|
@ -3,7 +3,6 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -31,20 +30,19 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Ad
|
|||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInner(conn net.Conn, address string) *context.ConnContext {
|
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.DNSNormal
|
||||||
|
metadata.Host = host
|
||||||
metadata.Process = C.ClashName
|
metadata.Process = C.ClashName
|
||||||
if h, port, err := net.SplitHostPort(address); err == nil {
|
if h, port, err := net.SplitHostPort(dst); err == nil {
|
||||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
metadata.DstPort = port
|
||||||
metadata.DstPort = uint16(port)
|
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -20,14 +20,14 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
// trim for FQDN
|
// trim for FQDN
|
||||||
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
||||||
metadata.DstPort = uint16((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
||||||
metadata.DstPort = uint16((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks5.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len])
|
ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len])
|
||||||
metadata.DstIP = ip6.Unmap()
|
metadata.DstIP = ip6.Unmap()
|
||||||
metadata.DstPort = uint16((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
@ -43,16 +43,11 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
// trim FQDN (#737)
|
// trim FQDN (#737)
|
||||||
host = strings.TrimRight(host, ".")
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
var uint16Port uint16
|
|
||||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
|
||||||
uint16Port = uint16(port)
|
|
||||||
}
|
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: uint16Port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
@ -63,10 +58,10 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr net.Addr) (netip.Addr, uint16, error) {
|
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
||||||
// Filter when net.Addr interface is nil
|
// Filter when net.Addr interface is nil
|
||||||
if addr == nil {
|
if addr == nil {
|
||||||
return netip.Addr{}, 0, errors.New("nil addr")
|
return netip.Addr{}, "", errors.New("nil addr")
|
||||||
}
|
}
|
||||||
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
||||||
ip, port, err := parseAddr(rawAddr.RawAddr())
|
ip, port, err := parseAddr(rawAddr.RawAddr())
|
||||||
@ -77,14 +72,9 @@ func parseAddr(addr net.Addr) (netip.Addr, uint16, error) {
|
|||||||
addrStr := addr.String()
|
addrStr := addr.String()
|
||||||
host, port, err := net.SplitHostPort(addrStr)
|
host, port, err := net.SplitHostPort(addrStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return netip.Addr{}, 0, err
|
return netip.Addr{}, "", err
|
||||||
}
|
|
||||||
|
|
||||||
var uint16Port uint16
|
|
||||||
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
|
||||||
uint16Port = uint16(port)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
return ip, uint16Port, err
|
return ip, port, err
|
||||||
}
|
}
|
||||||
|
@ -3,14 +3,15 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
@ -21,7 +22,6 @@ type Base struct {
|
|||||||
udp bool
|
udp bool
|
||||||
xudp bool
|
xudp bool
|
||||||
tfo bool
|
tfo bool
|
||||||
mpTcp bool
|
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
id string
|
||||||
prefer C.DNSPrefer
|
prefer C.DNSPrefer
|
||||||
@ -35,7 +35,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
|
||||||
@ -46,33 +51,33 @@ func (b *Base) Type() C.AdapterType {
|
|||||||
return b.tp
|
return b.tp
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConnContext(ctx context.Context, 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
|
||||||
@ -95,11 +100,6 @@ 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{
|
||||||
@ -144,20 +144,14 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
opts = append(opts, dialer.WithTFO(true))
|
opts = append(opts, dialer.WithTFO(true))
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.mpTcp {
|
|
||||||
opts = append(opts, dialer.WithMPTCP(true))
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
||||||
MPTCP bool `proxy:"mptcp,omitempty" group:"mptcp,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 {
|
||||||
@ -167,7 +161,6 @@ type BaseOption struct {
|
|||||||
UDP bool
|
UDP bool
|
||||||
XUDP bool
|
XUDP bool
|
||||||
TFO bool
|
TFO bool
|
||||||
MPTCP bool
|
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
Prefer C.DNSPrefer
|
Prefer C.DNSPrefer
|
||||||
@ -181,7 +174,6 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
xudp: opt.XUDP,
|
xudp: opt.XUDP,
|
||||||
tfo: opt.TFO,
|
tfo: opt.TFO,
|
||||||
mpTcp: opt.MPTCP,
|
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
prefer: opt.Prefer,
|
prefer: opt.Prefer,
|
||||||
@ -212,26 +204,13 @@ func (c *conn) Upstream() any {
|
|||||||
return c.ExtendedConn
|
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
|
|
||||||
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
|
||||||
}
|
|
||||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
N.EnhancePacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
adapterName string
|
|
||||||
connID string
|
|
||||||
actualRemoteDestination string
|
actualRemoteDestination string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,29 +228,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.EnhancePacketConn.LocalAddr()
|
|
||||||
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) Upstream() any {
|
|
||||||
return c.EnhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
epc := N.NewEnhancePacketConn(pc)
|
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
|
||||||
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
|
||||||
}
|
|
||||||
return &packetConn{epc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func parseRemoteDestination(addr string) string {
|
||||||
|
@ -2,10 +2,8 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"net"
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -15,11 +13,6 @@ type Direct struct {
|
|||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
type DirectOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
||||||
@ -27,40 +20,22 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return NewConn(c, d), nil
|
return NewConn(c, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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() {
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
||||||
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.NewDialer(d.Base.DialOptions(opts...)...).ListenPacket(ctx, "udp", "", netip.AddrPortFrom(metadata.DstIP, metadata.DstPort))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(pc, d), nil
|
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirectWithOption(option DirectOption) *Direct {
|
type directPacketConn struct {
|
||||||
return &Direct{
|
net.PacketConn
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Direct,
|
|
||||||
udp: true,
|
|
||||||
tfo: option.TFO,
|
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
|
@ -7,16 +7,14 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -42,10 +40,12 @@ type HttpOption struct {
|
|||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
err := cc.HandshakeContext(ctx)
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -66,23 +66,17 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = h.StreamConnContext(ctx, c, metadata)
|
c, err = h.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -91,42 +85,40 @@ 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 {
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
req := &http.Request{
|
||||||
tempHeaders := map[string]string{
|
Method: http.MethodConnect,
|
||||||
"Host": addr,
|
URL: &url.URL{
|
||||||
"User-Agent": "Go-http-client/1.1",
|
Host: addr,
|
||||||
"Proxy-Connection": "Keep-Alive",
|
},
|
||||||
|
Host: addr,
|
||||||
|
Header: http.Header{
|
||||||
|
"Proxy-Connection": []string{"Keep-Alive"},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//增加headers
|
||||||
|
if len(h.option.Headers) != 0 {
|
||||||
for key, value := range h.option.Headers {
|
for key, value := range h.option.Headers {
|
||||||
tempHeaders[key] = value
|
req.Header.Add(key, value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
}
|
}
|
||||||
|
|
||||||
for key, value := range tempHeaders {
|
if err := req.Write(rw); err != nil {
|
||||||
HeaderString += key + ": " + value + "\r\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
HeaderString += "\r\n"
|
|
||||||
|
|
||||||
_, err := rw.Write([]byte(HeaderString))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := http.ReadResponse(bufio.NewReader(rw), nil)
|
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -157,15 +149,21 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
var err error
|
if len(option.Fingerprint) == 0 {
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: sni,
|
ServerName: sni,
|
||||||
}, option.Fingerprint)
|
})
|
||||||
if err != nil {
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}, option.Fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@ -173,7 +171,6 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
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,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
@ -2,11 +2,16 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -14,9 +19,8 @@ import (
|
|||||||
"github.com/metacubex/quic-go/congestion"
|
"github.com/metacubex/quic-go/congestion"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
@ -24,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 (
|
||||||
@ -38,15 +41,26 @@ const (
|
|||||||
DefaultHopInterval = 10
|
DefaultHopInterval = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
@ -55,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 {
|
||||||
@ -113,12 +115,12 @@ type HysteriaOption struct {
|
|||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
var up, down uint64
|
var up, down uint64
|
||||||
up = StringToBps(c.Up)
|
up = stringToBps(c.Up)
|
||||||
if up == 0 {
|
if up == 0 {
|
||||||
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||||
}
|
}
|
||||||
|
|
||||||
down = StringToBps(c.Down)
|
down = stringToBps(c.Down)
|
||||||
if down == 0 {
|
if down == 0 {
|
||||||
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||||
}
|
}
|
||||||
@ -146,11 +148,38 @@ func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|||||||
MinVersion: tls.VersionTLS13,
|
MinVersion: tls.VersionTLS13,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
if len(option.CustomCA) > 0 {
|
||||||
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
if len(option.ALPN) > 0 {
|
||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
@ -229,11 +258,46 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func stringToBps(s string) uint64 {
|
||||||
|
if s == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// when have not unit, use Mbps
|
||||||
|
if v, err := strconv.Atoi(s); err == nil {
|
||||||
|
return stringToBps(fmt.Sprintf("%d Mbps", v))
|
||||||
|
}
|
||||||
|
|
||||||
|
m := rateStringRegexp.FindStringSubmatch(s)
|
||||||
|
if m == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var n uint64
|
||||||
|
switch m[2] {
|
||||||
|
case "K":
|
||||||
|
n = 1 << 10
|
||||||
|
case "M":
|
||||||
|
n = 1 << 20
|
||||||
|
case "G":
|
||||||
|
n = 1 << 30
|
||||||
|
case "T":
|
||||||
|
n = 1 << 40
|
||||||
|
default:
|
||||||
|
n = 1
|
||||||
|
}
|
||||||
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
n = v * n
|
||||||
|
if m[3] == "b" {
|
||||||
|
// Bits, need to convert to bytes
|
||||||
|
n = n >> 3
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
type hyPacketConn struct {
|
type hyPacketConn struct {
|
||||||
core.UDPConn
|
core.UDPConn
|
||||||
}
|
}
|
||||||
@ -248,16 +312,6 @@ func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *hyPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
b, addrStr, err := c.UDPConn.ReadFrom()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data = b
|
|
||||||
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,157 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/proxydialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
tuicCommon "github.com/Dreamacro/clash/transport/tuic/common"
|
|
||||||
|
|
||||||
"github.com/metacubex/sing-quic/hysteria2"
|
|
||||||
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
|
||||||
}
|
|
||||||
|
|
||||||
type Hysteria2 struct {
|
|
||||||
*Base
|
|
||||||
|
|
||||||
option *Hysteria2Option
|
|
||||||
client *hysteria2.Client
|
|
||||||
dialer proxydialer.SingDialer
|
|
||||||
}
|
|
||||||
|
|
||||||
type Hysteria2Option struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Up string `proxy:"up,omitempty"`
|
|
||||||
Down string `proxy:"down,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
Obfs string `proxy:"obfs,omitempty"`
|
|
||||||
ObfsPassword string `proxy:"obfs-password,omitempty"`
|
|
||||||
SNI string `proxy:"sni,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
CWND int `proxy:"cwnd,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
options := h.Base.DialOptions(opts...)
|
|
||||||
h.dialer.SetDialer(dialer.NewDialer(options...))
|
|
||||||
c, err := h.client.DialConn(ctx, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return NewConn(CN.NewRefConn(c, h), h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria2) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
options := h.Base.DialOptions(opts...)
|
|
||||||
h.dialer.SetDialer(dialer.NewDialer(options...))
|
|
||||||
pc, err := h.client.ListenPacket(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if pc == nil {
|
|
||||||
return nil, errors.New("packetConn is nil")
|
|
||||||
}
|
|
||||||
return newPacketConn(CN.NewRefPacketConn(CN.NewThreadSafePacketConn(pc), h), h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeHysteria2(h *Hysteria2) {
|
|
||||||
if h.client != nil {
|
|
||||||
_ = h.client.CloseWithError(errors.New("proxy removed"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
var salamanderPassword string
|
|
||||||
if len(option.Obfs) > 0 {
|
|
||||||
if option.ObfsPassword == "" {
|
|
||||||
return nil, errors.New("missing obfs password")
|
|
||||||
}
|
|
||||||
switch option.Obfs {
|
|
||||||
case hysteria2.ObfsTypeSalamander:
|
|
||||||
salamanderPassword = option.ObfsPassword
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
serverName := option.Server
|
|
||||||
if option.SNI != "" {
|
|
||||||
serverName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
tlsConfig.NextProtos = option.ALPN
|
|
||||||
}
|
|
||||||
|
|
||||||
singDialer := proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer())
|
|
||||||
|
|
||||||
clientOptions := hysteria2.ClientOptions{
|
|
||||||
Context: context.TODO(),
|
|
||||||
Dialer: singDialer,
|
|
||||||
ServerAddress: M.ParseSocksaddrHostPort(option.Server, uint16(option.Port)),
|
|
||||||
SendBPS: StringToBps(option.Up),
|
|
||||||
ReceiveBPS: StringToBps(option.Down),
|
|
||||||
SalamanderPassword: salamanderPassword,
|
|
||||||
Password: option.Password,
|
|
||||||
TLSConfig: tlsConfig,
|
|
||||||
UDPDisabled: false,
|
|
||||||
CWND: option.CWND,
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := hysteria2.NewClient(clientOptions)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
outbound := &Hysteria2{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Hysteria2,
|
|
||||||
udp: true,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
option: &option,
|
|
||||||
client: client,
|
|
||||||
dialer: singDialer,
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeHysteria2)
|
|
||||||
|
|
||||||
return outbound, 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,40 +48,30 @@ 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
|
if len(b) == 0 {
|
||||||
}
|
return 0, nil
|
||||||
|
}
|
||||||
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) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
func (npc *nopPacketConn) Close() error { return nil }
|
||||||
return nil, nil, nil, io.EOF
|
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) Close() error { return nil }
|
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
func (npc *nopPacketConn) SetWriteDeadline(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) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
@ -7,19 +7,17 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
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"
|
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
restlsC "github.com/3andne/restls-client-go"
|
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/common/uot"
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
@ -34,7 +32,6 @@ type ShadowSocks struct {
|
|||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
restlsConfig *restlsC.Config
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
@ -48,8 +45,6 @@ type ShadowSocksOption struct {
|
|||||||
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,20 +67,28 @@ type shadowTLSOption struct {
|
|||||||
Password string `obfs:"password"`
|
Password string `obfs:"password"`
|
||||||
Host string `obfs:"host"`
|
Host string `obfs:"host"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
ClientFingerprint string `obfs:"client-fingerprint,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Version int `obfs:"version,omitempty"`
|
Version int `obfs:"version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type restlsOption struct {
|
// StreamConn implements C.ProxyAdapter
|
||||||
Password string `obfs:"password"`
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
Host string `obfs:"host"`
|
switch ss.obfsMode {
|
||||||
VersionHint string `obfs:"version-hint"`
|
case shadowtls.Mode:
|
||||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
// fix tls handshake not timeout
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
var err error
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ss.streamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
func (ss *ShadowSocks) streamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
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)
|
||||||
@ -94,39 +97,15 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
|
|||||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
case "websocket":
|
case "websocket":
|
||||||
var err error
|
var err error
|
||||||
c, err = v2rayObfs.NewV2rayObfs(ctx, c, ss.v2rayOption)
|
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||||
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.DialEarlyConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443")), nil
|
||||||
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
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
} else {
|
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -136,23 +115,25 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConnContext(ctx, c, metadata)
|
switch ss.obfsMode {
|
||||||
|
case shadowtls.Mode:
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = ss.streamConn(c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -163,18 +144,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 {
|
||||||
@ -185,35 +160,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(N.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
|
return nil, errors.New("no support")
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@ -223,9 +184,7 @@ 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 := shadowsocks.CreateMethod(context.Background(), option.Cipher, shadowsocks.MethodOptions{
|
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||||
Password: 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)
|
||||||
}
|
}
|
||||||
@ -233,7 +192,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
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})
|
||||||
@ -282,29 +240,10 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
Password: opt.Password,
|
Password: opt.Password,
|
||||||
Host: opt.Host,
|
Host: opt.Host,
|
||||||
Fingerprint: opt.Fingerprint,
|
Fingerprint: opt.Fingerprint,
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
ClientFingerprint: opt.ClientFingerprint,
|
||||||
SkipCertVerify: opt.SkipCertVerify,
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
Version: opt.Version,
|
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)
|
|
||||||
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.LegacyVersion
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
@ -314,7 +253,6 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -326,6 +264,38 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
shadowTLSOption: shadowTLSOpt,
|
shadowTLSOption: shadowTLSOpt,
|
||||||
restlsConfig: restlsConfig,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ssPacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := spc.PacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), udpAddr, e
|
||||||
|
}
|
||||||
|
@ -2,26 +2,21 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
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/transport/shadowsocks/core"
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
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
|
||||||
@ -41,8 +36,8 @@ type ShadowSocksROption struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = ssr.obfs.StreamConn(c)
|
c = ssr.obfs.StreamConn(c)
|
||||||
c = ssr.cipher.StreamConn(c)
|
c = ssr.cipher.StreamConn(c)
|
||||||
var (
|
var (
|
||||||
@ -70,23 +65,17 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ssr.StreamConnContext(ctx, c, metadata)
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,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
|
||||||
@ -113,14 +96,14 @@ func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Di
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
|
pc = ssr.cipher.PacketConn(pc)
|
||||||
epc = ssr.protocol.PacketConn(epc)
|
pc = ssr.protocol.PacketConn(pc)
|
||||||
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
@ -181,73 +164,12 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
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,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type ssrPacketConn struct {
|
|
||||||
N.EnhancePacketConn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|
||||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, _, e := spc.EnhancePacketConn.ReadFrom(b)
|
|
||||||
if e != nil {
|
|
||||||
return 0, nil, e
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := socks5.SplitAddr(b[:n])
|
|
||||||
if addr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
udpAddr := addr.UDPAddr()
|
|
||||||
if udpAddr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
copy(b, b[len(addr):])
|
|
||||||
return n - len(addr), udpAddr, e
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
data, put, _, err = spc.EnhancePacketConn.WaitReadFrom()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_addr := socks5.SplitAddr(data)
|
|
||||||
if _addr == nil {
|
|
||||||
if put != nil {
|
|
||||||
put()
|
|
||||||
}
|
|
||||||
return nil, nil, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = _addr.UDPAddr()
|
|
||||||
if addr == nil {
|
|
||||||
if put != nil {
|
|
||||||
put()
|
|
||||||
}
|
|
||||||
return nil, nil, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
data = data[len(_addr):]
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
@ -1,118 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SingMux struct {
|
|
||||||
C.ProxyAdapter
|
|
||||||
base ProxyBase
|
|
||||||
client *mux.Client
|
|
||||||
dialer proxydialer.SingDialer
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
options := s.base.DialOptions(opts...)
|
|
||||||
s.dialer.SetDialer(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.SetDialer(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(CN.NewThreadSafePacketConn(pc), s), s.ProxyAdapter), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SingMux) SupportUDP() bool {
|
|
||||||
if s.onlyTcp {
|
|
||||||
return s.ProxyAdapter.SupportUDP()
|
|
||||||
}
|
|
||||||
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 := proxydialer.NewSingDialer(proxy, dialer.NewDialer(), 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
|
|
||||||
}
|
|
@ -6,10 +6,8 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
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"
|
|
||||||
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"
|
||||||
@ -17,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
|
||||||
@ -53,14 +50,15 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
return snell.StreamConn(c, option.psk, option.version)
|
return snell.StreamConn(c, option.psk, option.version)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
err := snell.WriteUDPHeader(c, s.version)
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
err := snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -72,7 +70,8 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version); err != nil {
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
|
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||||
c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -84,23 +83,17 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = s.StreamConnContext(ctx, c, metadata)
|
c, err = s.StreamConn(c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,18 +104,11 @@ 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
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
err = snell.WriteUDPHeader(c, s.version)
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
@ -135,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 +168,10 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
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,20 +179,12 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -9,17 +9,14 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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
|
||||||
@ -40,10 +37,12 @@ type Socks5Option struct {
|
|||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
err := cc.HandshakeContext(ctx)
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -71,23 +70,17 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConnContext(ctx, c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -96,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
|
||||||
@ -127,7 +113,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
if ss.user != "" {
|
if ss.user != "" {
|
||||||
user = &socks5.User{
|
user = &socks5.User{
|
||||||
@ -156,7 +142,7 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
bindUDPAddr.IP = serverAddr.IP
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := cDialer.ListenPacket(ctx, "udp", "", bindUDPAddr.AddrPort())
|
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", bindUDPAddr.AddrPort().Addr()), "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -180,12 +166,15 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@ -194,12 +183,10 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
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,
|
||||||
|
@ -9,13 +9,12 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
N "github.com/Dreamacro/clash/common/net"
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@ -27,8 +26,6 @@ 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 {
|
||||||
@ -43,13 +40,14 @@ type TrojanOption struct {
|
|||||||
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"`
|
||||||
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
if t.option.Network == "ws" {
|
if t.option.Network == "ws" {
|
||||||
host, port, _ := net.SplitHostPort(t.addr)
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
wsOpts := &trojan.WebsocketOption{
|
wsOpts := &trojan.WebsocketOption{
|
||||||
@ -70,14 +68,14 @@ func (t *Trojan) plainStream(ctx context.Context, c net.Conn) (net.Conn, error)
|
|||||||
wsOpts.Headers = header
|
wsOpts.Headers = header
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamWebsocketConn(ctx, c, wsOpts)
|
return t.instance.StreamWebsocketConn(c, wsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamConn(ctx, c)
|
return t.instance.StreamConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (t *Trojan) StreamConnContext(ctx context.Context, 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 {
|
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
||||||
@ -85,21 +83,26 @@ func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.
|
|||||||
}
|
}
|
||||||
|
|
||||||
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(ctx, c)
|
c, err = t.plainStream(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return N.NewExtendedConn(c), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -111,6 +114,12 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -123,23 +132,17 @@ 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)
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = t.StreamConnContext(ctx, c, metadata)
|
c, err = t.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -173,12 +176,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)
|
||||||
@ -186,8 +183,8 @@ func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = t.plainStream(ctx, c)
|
c, err = t.plainStream(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
@ -202,8 +199,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
|
||||||
@ -225,10 +222,24 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
Fingerprint: option.Fingerprint,
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "", "tcp":
|
||||||
|
if len(option.Flow) >= 16 {
|
||||||
|
option.Flow = option.Flow[:16]
|
||||||
|
switch option.Flow {
|
||||||
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
|
tOption.Flow = option.Flow
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
tOption.ServerName = option.SNI
|
tOption.ServerName = option.SNI
|
||||||
}
|
}
|
||||||
@ -240,7 +251,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -249,28 +259,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
|
||||||
t.realityConfig, err = option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
tOption.Reality = t.realityConfig
|
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -281,13 +276,16 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint)
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
|
@ -2,30 +2,27 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
"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"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
"github.com/Dreamacro/clash/transport/tuic"
|
||||||
|
|
||||||
"github.com/gofrs/uuid/v5"
|
|
||||||
"github.com/metacubex/quic-go"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
"github.com/sagernet/sing/common/uot"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Tuic struct {
|
type Tuic struct {
|
||||||
*Base
|
*Base
|
||||||
option *TuicOption
|
|
||||||
client *tuic.PoolClient
|
client *tuic.PoolClient
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,9 +31,7 @@ type TuicOption struct {
|
|||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Token string `proxy:"token,omitempty"`
|
Token string `proxy:"token"`
|
||||||
UUID string `proxy:"uuid,omitempty"`
|
|
||||||
Password string `proxy:"password,omitempty"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
Ip string `proxy:"ip,omitempty"`
|
||||||
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
@ -49,7 +44,6 @@ type TuicOption struct {
|
|||||||
|
|
||||||
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"`
|
||||||
CWND int `proxy:"cwnd,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"`
|
||||||
@ -57,11 +51,7 @@ type TuicOption struct {
|
|||||||
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"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
|
||||||
UDPOverStream bool `proxy:"udp-over-stream,omitempty"`
|
|
||||||
UDPOverStreamVersion int `proxy:"udp-over-stream-version,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -85,32 +75,6 @@ func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
// ListenPacketWithDialer implements C.ProxyAdapter
|
||||||
func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
if t.option.UDPOverStream {
|
|
||||||
uotDestination := uot.RequestDestination(uint8(t.option.UDPOverStreamVersion))
|
|
||||||
uotMetadata := *metadata
|
|
||||||
uotMetadata.Host = uotDestination.Fqdn
|
|
||||||
uotMetadata.DstPort = uotDestination.Port
|
|
||||||
c, err := t.DialContextWithDialer(ctx, dialer, &uotMetadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// tuic uos 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
|
|
||||||
}
|
|
||||||
|
|
||||||
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
|
||||||
if t.option.UDPOverStreamVersion == uot.LegacyVersion {
|
|
||||||
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
|
|
||||||
} else {
|
|
||||||
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pc, err := t.client.ListenPacketWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
pc, err := t.client.ListenPacketWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -119,30 +83,24 @@ 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) dialWithDialer(ctx context.Context, dialer C.Dialer) (transport *quic.Transport, addr net.Addr, err error) {
|
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
if len(t.option.DialerProxy) > 0 {
|
return t.dialWithDialer(ctx, dialer.NewDialer(opts...))
|
||||||
dialer, err = proxydialer.NewByName(t.option.DialerProxy, dialer)
|
}
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
||||||
}
|
|
||||||
}
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
addr = udpAddr
|
addr = udpAddr
|
||||||
var pc net.PacketConn
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
transport = &quic.Transport{Conn: pc}
|
|
||||||
transport.SetCreatedConn(true) // auto close conn
|
|
||||||
transport.SetSingleUse(true) // auto close transport
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -158,13 +116,40 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
tlsConfig.ServerName = option.SNI
|
tlsConfig.ServerName = option.SNI
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
var err error
|
var err error
|
||||||
tlsConfig, err = ca.GetTLSConfig(tlsConfig, option.Fingerprint, option.CustomCA, option.CustomCAString)
|
if len(option.CustomCA) > 0 {
|
||||||
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("tuic %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
if len(option.ALPN) > 0 {
|
||||||
tlsConfig.NextProtos = option.ALPN
|
tlsConfig.NextProtos = option.ALPN
|
||||||
} else {
|
} else {
|
||||||
tlsConfig.NextProtos = []string{"h3"}
|
tlsConfig.NextProtos = []string{"h3"}
|
||||||
@ -178,9 +163,8 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
option.HeartbeatInterval = 10000
|
option.HeartbeatInterval = 10000
|
||||||
}
|
}
|
||||||
|
|
||||||
udpRelayMode := tuic.QUIC
|
|
||||||
if option.UdpRelayMode != "quic" {
|
if option.UdpRelayMode != "quic" {
|
||||||
udpRelayMode = tuic.NATIVE
|
option.UdpRelayMode = "native"
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
@ -191,24 +175,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
option.MaxOpenStreams = 100
|
option.MaxOpenStreams = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.CWND == 0 {
|
|
||||||
option.CWND = 32
|
|
||||||
}
|
|
||||||
|
|
||||||
packetOverHead := tuic.PacketOverHeadV4
|
|
||||||
if len(option.Token) == 0 {
|
|
||||||
packetOverHead = tuic.PacketOverHeadV5
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize == 0 {
|
|
||||||
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + packetOverHead
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize > 1400 {
|
|
||||||
option.MaxDatagramFrameSize = 1400
|
|
||||||
}
|
|
||||||
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - 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))
|
||||||
@ -221,7 +187,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 {
|
||||||
@ -236,18 +201,12 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
if len(option.Ip) > 0 {
|
if len(option.Ip) > 0 {
|
||||||
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
||||||
}
|
}
|
||||||
|
host := option.Server
|
||||||
if option.DisableSni {
|
if option.DisableSni {
|
||||||
|
host = ""
|
||||||
tlsConfig.ServerName = ""
|
tlsConfig.ServerName = ""
|
||||||
tlsConfig.InsecureSkipVerify = true // tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.UDPOverStreamVersion {
|
|
||||||
case uot.Version, uot.LegacyVersion:
|
|
||||||
case 0:
|
|
||||||
option.UDPOverStreamVersion = uot.LegacyVersion
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("tuic %s unknown udp over stream protocol version: %d", addr, option.UDPOverStreamVersion)
|
|
||||||
}
|
}
|
||||||
|
tkn := tuic.GenTKN(option.Token)
|
||||||
|
|
||||||
t := &Tuic{
|
t := &Tuic{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
@ -260,7 +219,6 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
option: &option,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
@ -273,44 +231,21 @@ func NewTuic(option TuicOption) (*Tuic, error) {
|
|||||||
if clientMaxOpenStreams < 1 {
|
if clientMaxOpenStreams < 1 {
|
||||||
clientMaxOpenStreams = 1
|
clientMaxOpenStreams = 1
|
||||||
}
|
}
|
||||||
|
clientOption := &tuic.ClientOption{
|
||||||
if len(option.Token) > 0 {
|
|
||||||
tkn := tuic.GenTKN(option.Token)
|
|
||||||
clientOption := &tuic.ClientOptionV4{
|
|
||||||
TlsConfig: tlsConfig,
|
TlsConfig: tlsConfig,
|
||||||
QuicConfig: quicConfig,
|
QuicConfig: quicConfig,
|
||||||
|
Host: host,
|
||||||
Token: tkn,
|
Token: tkn,
|
||||||
UdpRelayMode: udpRelayMode,
|
UdpRelayMode: option.UdpRelayMode,
|
||||||
CongestionController: option.CongestionController,
|
CongestionController: option.CongestionController,
|
||||||
ReduceRtt: option.ReduceRtt,
|
ReduceRtt: option.ReduceRtt,
|
||||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||||
FastOpen: option.FastOpen,
|
FastOpen: option.FastOpen,
|
||||||
MaxOpenStreams: clientMaxOpenStreams,
|
MaxOpenStreams: clientMaxOpenStreams,
|
||||||
CWND: option.CWND,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
t.client = tuic.NewPoolClientV4(clientOption)
|
t.client = tuic.NewPoolClient(clientOption)
|
||||||
} else {
|
|
||||||
maxUdpRelayPacketSize := option.MaxUdpRelayPacketSize
|
|
||||||
if maxUdpRelayPacketSize > tuic.MaxFragSizeV5 {
|
|
||||||
maxUdpRelayPacketSize = tuic.MaxFragSizeV5
|
|
||||||
}
|
|
||||||
clientOption := &tuic.ClientOptionV5{
|
|
||||||
TlsConfig: tlsConfig,
|
|
||||||
QuicConfig: quicConfig,
|
|
||||||
Uuid: uuid.FromStringOrNil(option.UUID),
|
|
||||||
Password: option.Password,
|
|
||||||
UdpRelayMode: udpRelayMode,
|
|
||||||
CongestionController: option.CongestionController,
|
|
||||||
ReduceRtt: option.ReduceRtt,
|
|
||||||
MaxUdpRelayPacketSize: maxUdpRelayPacketSize,
|
|
||||||
MaxOpenStreams: clientMaxOpenStreams,
|
|
||||||
CWND: option.CWND,
|
|
||||||
}
|
|
||||||
|
|
||||||
t.client = tuic.NewPoolClientV5(clientOption)
|
|
||||||
}
|
|
||||||
|
|
||||||
return t, nil
|
return t, nil
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,12 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -18,9 +18,17 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
globalClientSessionCache tls.ClientSessionCache
|
globalClientSessionCache tls.ClientSessionCache
|
||||||
|
globalClientXSessionCache xtls.ClientSessionCache
|
||||||
once sync.Once
|
once sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func getClientSessionCache() tls.ClientSessionCache {
|
func getClientSessionCache() tls.ClientSessionCache {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
||||||
@ -28,11 +36,18 @@ func getClientSessionCache() tls.ClientSessionCache {
|
|||||||
return globalClientSessionCache
|
return globalClientSessionCache
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getClientXSessionCache() xtls.ClientSessionCache {
|
||||||
|
once.Do(func() {
|
||||||
|
globalClientXSessionCache = xtls.NewLRUClientSessionCache(128)
|
||||||
|
})
|
||||||
|
return globalClientXSessionCache
|
||||||
|
}
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
addrType := metadata.AddrType()
|
addrType := metadata.AddrType()
|
||||||
aType := uint8(addrType)
|
aType := uint8(addrType)
|
||||||
p := uint(metadata.DstPort)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch addrType {
|
switch addrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -123,41 +138,3 @@ func safeConnClose(c net.Conn, err error) {
|
|||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
|
||||||
|
|
||||||
func StringToBps(s string) uint64 {
|
|
||||||
if s == "" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// when have not unit, use Mbps
|
|
||||||
if v, err := strconv.Atoi(s); err == nil {
|
|
||||||
return StringToBps(fmt.Sprintf("%d Mbps", v))
|
|
||||||
}
|
|
||||||
|
|
||||||
m := rateStringRegexp.FindStringSubmatch(s)
|
|
||||||
if m == nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
var n uint64
|
|
||||||
switch m[2] {
|
|
||||||
case "K":
|
|
||||||
n = 1 << 10
|
|
||||||
case "M":
|
|
||||||
n = 1 << 20
|
|
||||||
case "G":
|
|
||||||
n = 1 << 30
|
|
||||||
case "T":
|
|
||||||
n = 1 << 40
|
|
||||||
default:
|
|
||||||
n = 1
|
|
||||||
}
|
|
||||||
v, _ := strconv.ParseUint(m[1], 10, 64)
|
|
||||||
n = v * n
|
|
||||||
if m[3] == "b" {
|
|
||||||
// Bits, need to convert to bytes
|
|
||||||
n = n >> 3
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
@ -13,22 +13,17 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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/metacubex/sing-vmess"
|
vmessSing "github.com/sagernet/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -46,8 +41,6 @@ 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 {
|
||||||
@ -57,14 +50,13 @@ type VlessOption struct {
|
|||||||
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"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
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"`
|
||||||
@ -77,7 +69,7 @@ type VlessOption struct {
|
|||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConnContext(ctx context.Context, 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 {
|
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
||||||
@ -86,6 +78,7 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
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,
|
||||||
@ -111,10 +104,14 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
if len(v.option.Fingerprint) == 0 {
|
||||||
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
@ -127,10 +124,10 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
convert.SetUserAgent(wsOpts.Headers)
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
c, err = v.streamTLSConn(ctx, c, false)
|
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -145,7 +142,7 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
c, err = v.streamTLSConn(ctx, c, true)
|
c, err = v.streamTLSOrXTLSConn(c, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -157,59 +154,42 @@ func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
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)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS
|
// handle TLS And XTLS
|
||||||
c, err = v.streamTLSConn(ctx, c, false)
|
c, err = v.streamTLSOrXTLSConn(c, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.streamConn(c, metadata)
|
return v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamConn(c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, 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) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error) {
|
|
||||||
if v.option.TLS {
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
|
if v.isLegacyXTLSEnabled() && !isH2 {
|
||||||
|
xtlsOpts := vless.XTLSConfig{
|
||||||
|
Host: host,
|
||||||
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
xtlsOpts.Host = v.option.ServerName
|
||||||
|
}
|
||||||
|
|
||||||
|
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||||
|
|
||||||
|
} 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,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
|
||||||
NextProtos: v.option.ALPN,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -220,12 +200,16 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
return vmess.StreamTLSConn(ctx, conn, &tlsOpts)
|
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return conn, nil
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (v *Vless) isLegacyXTLSEnabled() bool {
|
||||||
|
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
// gun transport
|
// gun transport
|
||||||
@ -250,22 +234,16 @@ 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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
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())
|
||||||
}
|
}
|
||||||
@ -282,6 +260,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 {
|
||||||
@ -293,25 +272,27 @@ 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)
|
if v.option.PacketAddr {
|
||||||
|
packetAddrMetadata := *metadata // make a copy
|
||||||
|
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
packetAddrMetadata.DstPort = "443"
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(&packetAddrMetadata, false))
|
||||||
|
} else {
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
|
}
|
||||||
|
|
||||||
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 {
|
|
||||||
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
|
// 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)
|
||||||
@ -320,56 +301,49 @@ 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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
if v.option.PacketAddr {
|
||||||
|
packetAddrMetadata := *metadata // make a copy
|
||||||
|
packetAddrMetadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
packetAddrMetadata.DstPort = "443"
|
||||||
|
|
||||||
|
c, err = v.StreamConn(c, &packetAddrMetadata)
|
||||||
|
} else {
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
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 {
|
if v.option.XUDP {
|
||||||
var globalID [8]byte
|
return newPacketConn(&threadSafePacketConn{
|
||||||
if metadata.SourceValid() {
|
PacketConn: vmessSing.NewXUDPConn(c, M.ParseSocksaddr(metadata.RemoteAddress())),
|
||||||
globalID = utils.GlobalID(metadata.SourceAddress())
|
}, v), nil
|
||||||
}
|
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(
|
|
||||||
vmessSing.NewXUDPConn(c,
|
|
||||||
globalID,
|
|
||||||
M.SocksaddrFromNet(metadata.UDPAddr())),
|
|
||||||
), v), nil
|
|
||||||
} else if v.option.PacketAddr {
|
} else if v.option.PacketAddr {
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(
|
return newPacketConn(&threadSafePacketConn{
|
||||||
packetaddr.NewConn(&vlessPacketConn{
|
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
||||||
Conn: c, rAddr: metadata.UDPAddr(),
|
Conn: c, rAddr: metadata.UDPAddr(),
|
||||||
}, M.SocksaddrFromNet(metadata.UDPAddr())),
|
}, M.ParseSocksaddr(metadata.RemoteAddress())),
|
||||||
), v), nil
|
}, v), nil
|
||||||
}
|
}
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
@ -398,11 +372,12 @@ func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
|||||||
copy(addr[1:], metadata.Host)
|
copy(addr[1:], metadata.Host)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
return &vless.DstAddr{
|
return &vless.DstAddr{
|
||||||
UDP: metadata.NetWork == C.UDP,
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: metadata.DstPort,
|
Port: uint16(port),
|
||||||
Mux: metadata.NetWork == C.UDP && xudp,
|
Mux: metadata.NetWork == C.UDP && xudp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -504,13 +479,10 @@ 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:
|
case vless.XRO, vless.XRD, vless.XRS, vless.XRV:
|
||||||
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
}
|
}
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
|
||||||
log.Fatalln("Legacy XTLS protocol %s is deprecated and no longer supported", option.Flow)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
}
|
}
|
||||||
@ -525,11 +497,8 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
option.XUDP = true
|
option.XUDP = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if option.XUDP {
|
|
||||||
option.PacketAddr = false
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -542,7 +511,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
xudp: option.XUDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -551,11 +519,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
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 {
|
||||||
@ -563,19 +526,11 @@ 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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -584,25 +539,22 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
if option.ServerName == "" {
|
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
||||||
gunConfig.Host = v.addr
|
|
||||||
}
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if option.TLS {
|
|
||||||
tlsConfig = ca.GetGlobalTLSConfig(&tls.Config{
|
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
})
|
||||||
if option.ServerName == "" {
|
|
||||||
|
if v.option.ServerName == "" {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsConfig.ServerName = host
|
tlsConfig.ServerName = host
|
||||||
}
|
gunConfig.Host = host
|
||||||
}
|
}
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -11,20 +11,15 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/ca"
|
|
||||||
"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/ntp"
|
|
||||||
"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/metacubex/sing-vmess"
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"github.com/metacubex/sing-vmess/packetaddr"
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -39,8 +34,6 @@ 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 {
|
||||||
@ -54,11 +47,9 @@ type VmessOption struct {
|
|||||||
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"`
|
||||||
ALPN []string `proxy:"alpn,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"`
|
||||||
@ -93,8 +84,8 @@ type WSOptions struct {
|
|||||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConnContext implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) StreamConnContext(ctx context.Context, 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) {
|
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
||||||
@ -103,6 +94,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
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,
|
||||||
@ -128,10 +120,13 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
wsOpts.TLSConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
if len(v.option.Fingerprint) == 0 {
|
||||||
if err != nil {
|
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
@ -139,7 +134,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
c, err = clashVMess.StreamWebsocketConn(c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
@ -148,14 +143,13 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
|
||||||
NextProtos: v.option.ALPN,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
|
||||||
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -177,14 +171,13 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
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(ctx, c, &tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -196,7 +189,7 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
|
|
||||||
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 {
|
||||||
@ -205,71 +198,28 @@ func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.M
|
|||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
Reality: v.realityConfig,
|
|
||||||
NextProtos: v.option.ALPN,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(ctx, c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
var globalID [8]byte
|
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
if metadata.SourceValid() {
|
|
||||||
globalID = utils.GlobalID(metadata.SourceAddress())
|
|
||||||
}
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
conn = v.client.DialEarlyXUDPPacketConn(c,
|
|
||||||
globalID,
|
|
||||||
M.SocksaddrFromNet(metadata.UDPAddr()))
|
|
||||||
} else {
|
} else {
|
||||||
conn, err = v.client.DialXUDPPacketConn(c,
|
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
globalID,
|
|
||||||
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 {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
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.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
||||||
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
|
||||||
@ -296,22 +246,16 @@ 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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -325,6 +269,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 {
|
||||||
@ -336,24 +288,22 @@ 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 = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c = v.client.DialEarlyPacketConn(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)
|
||||||
}
|
}
|
||||||
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 {
|
|
||||||
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
|
// 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)
|
||||||
@ -367,36 +317,29 @@ func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer func(c net.Conn) {
|
||||||
safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
}(c)
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConnContext(ctx, c, metadata)
|
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 newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
if pc, ok := c.(net.PacketConn); ok {
|
|
||||||
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
|
||||||
}
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
@ -415,7 +358,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
if option.AuthenticatedLength {
|
if option.AuthenticatedLength {
|
||||||
options = append(options, vmess.ClientWithAuthenticatedLength())
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
}
|
}
|
||||||
options = append(options, vmess.ClientWithTimeFunc(ntp.Now))
|
|
||||||
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -431,6 +373,13 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
option.PacketAddr = false
|
option.PacketAddr = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch option.Network {
|
||||||
|
case "h2", "grpc":
|
||||||
|
if !option.TLS {
|
||||||
|
option.TLS = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
v := &Vmess{
|
v := &Vmess{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
@ -439,7 +388,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
xudp: option.XUDP,
|
||||||
tfo: option.TFO,
|
tfo: option.TFO,
|
||||||
mpTcp: option.MPTCP,
|
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
@ -455,19 +403,11 @@ 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())
|
||||||
}
|
}
|
||||||
N.TCPKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -476,35 +416,37 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
}
|
}
|
||||||
if option.ServerName == "" {
|
tlsConfig := &tls.Config{
|
||||||
gunConfig.Host = v.addr
|
|
||||||
}
|
|
||||||
var tlsConfig *tls.Config
|
|
||||||
if option.TLS {
|
|
||||||
tlsConfig = ca.GetGlobalTLSConfig(&tls.Config{
|
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
}
|
||||||
if option.ServerName == "" {
|
|
||||||
|
if v.option.ServerName == "" {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsConfig.ServerName = host
|
tlsConfig.ServerName = host
|
||||||
}
|
gunConfig.Host = host
|
||||||
}
|
}
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint)
|
||||||
}
|
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type threadSafePacketConn struct {
|
||||||
|
net.PacketConn
|
||||||
|
access sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
c.access.Lock()
|
||||||
|
defer c.access.Unlock()
|
||||||
|
return c.PacketConn.WriteTo(b, addr)
|
||||||
|
}
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
@ -514,9 +456,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,10 +15,8 @@ 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/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
@ -27,6 +25,7 @@ import (
|
|||||||
"github.com/sagernet/sing/common/debug"
|
"github.com/sagernet/sing/common/debug"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/wireguard-go/device"
|
"github.com/sagernet/wireguard-go/device"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -35,69 +34,66 @@ type WireGuard struct {
|
|||||||
bind *wireguard.ClientBind
|
bind *wireguard.ClientBind
|
||||||
device *device.Device
|
device *device.Device
|
||||||
tunDevice wireguard.Device
|
tunDevice wireguard.Device
|
||||||
dialer proxydialer.SingDialer
|
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"`
|
||||||
PrivateKey string `proxy:"private-key"`
|
|
||||||
Workers int `proxy:"workers,omitempty"`
|
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
|
||||||
|
|
||||||
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
|
||||||
|
|
||||||
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
|
||||||
Dns []string `proxy:"dns,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type WireGuardPeerOption struct {
|
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Ip string `proxy:"ip,omitempty"`
|
Ip string `proxy:"ip,omitempty"`
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
PublicKey string `proxy:"public-key,omitempty"`
|
PrivateKey string `proxy:"private-key"`
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
Workers int `proxy:"workers,omitempty"`
|
||||||
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type wgSingErrorHandler struct {
|
type wgDialer struct {
|
||||||
name string
|
options []dialer.Option
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ E.Handler = (*wgSingErrorHandler)(nil)
|
func (d *wgDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, destination.String(), d.options...)
|
||||||
|
}
|
||||||
|
|
||||||
func (w wgSingErrorHandler) NewError(ctx context.Context, err error) {
|
func (d *wgDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
if E.IsClosedOrCanceled(err) {
|
return dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", destination.Addr), "", d.options...)
|
||||||
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) connection closed: %s", w.name, err))
|
}
|
||||||
return
|
|
||||||
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
|
outbound := &WireGuard{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.WireGuard,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
dialer: &wgDialer{},
|
||||||
}
|
}
|
||||||
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", w.name, err))
|
runtime.SetFinalizer(outbound, closeWireGuard)
|
||||||
}
|
|
||||||
|
|
||||||
type wgNetDialer struct {
|
var reserved [3]uint8
|
||||||
tunDevice wireguard.Device
|
if len(option.Reserved) > 0 {
|
||||||
}
|
if len(option.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
||||||
var _ dialer.NetDialer = (*wgNetDialer)(nil)
|
}
|
||||||
|
reserved[0] = uint8(option.Reserved[0])
|
||||||
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
reserved[1] = uint8(option.Reserved[1])
|
||||||
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
reserved[2] = uint8(option.Reserved[2])
|
||||||
}
|
}
|
||||||
|
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
||||||
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, "/") {
|
||||||
@ -122,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: proxydialer.NewByNameSingDialer(option.DialerProxy, dialer.NewDialer()),
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
|
||||||
if len(option.Reserved) > 0 {
|
|
||||||
if len(option.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
|
||||||
}
|
|
||||||
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 {
|
||||||
@ -169,52 +126,6 @@ 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 {
|
|
||||||
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)
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -229,16 +140,12 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
}
|
}
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
preSharedKey = hex.EncodeToString(bytes)
|
||||||
}
|
}
|
||||||
|
ipcConf := "private_key=" + privateKey
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
ipcConf += "\nendpoint=" + connectAddr.String()
|
ipcConf += "\nendpoint=" + peerAddr.String()
|
||||||
if preSharedKey != "" {
|
if preSharedKey != "" {
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
}
|
}
|
||||||
var err error
|
|
||||||
localPrefixes, err = option.Prefixes()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
var has4, has6 bool
|
||||||
for _, address := range localPrefixes {
|
for _, address := range localPrefixes {
|
||||||
if address.Addr().Is4() {
|
if address.Addr().Is4() {
|
||||||
@ -253,8 +160,6 @@ func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|||||||
if has6 {
|
if has6 {
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
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)
|
||||||
}
|
}
|
||||||
@ -262,55 +167,27 @@ 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 {
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
}
|
}
|
||||||
outbound.device = device.NewDevice(context.Background(), 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...)))
|
log.SingLogger.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...)))
|
log.SingLogger.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))
|
log.SingLogger.Trace("created wireguard ipc conf: \n", ipcConf)
|
||||||
}
|
}
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
err = outbound.device.IpcSet(ipcConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -322,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.SetDialer(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()
|
||||||
@ -331,18 +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 {
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
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
|
||||||
@ -354,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.SetDialer(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()
|
||||||
@ -366,20 +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
|
||||||
}
|
}
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
port, _ := strconv.Atoi(metadata.DstPort)
|
||||||
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -388,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) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
if r.proxyAdapter != nil {
|
|
||||||
return r.proxyAdapter.StreamConnContext(ctx, 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)
|
|
||||||
|
@ -8,8 +8,6 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
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"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -20,7 +18,6 @@ type Fallback struct {
|
|||||||
disableUDP bool
|
disableUDP bool
|
||||||
testUrl string
|
testUrl string
|
||||||
selected string
|
selected string
|
||||||
expectedStatus string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -38,14 +35,15 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
c = &callback.FirstWriteCallBackConn{
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.onDialSuccess()
|
f.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed(proxy.Type(), err)
|
f.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
@ -72,11 +70,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{}
|
||||||
@ -87,8 +80,6 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": f.testUrl,
|
|
||||||
"expected": f.expectedStatus,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,14 +93,12 @@ func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
|||||||
proxies := f.GetProxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if len(f.selected) == 0 {
|
if len(f.selected) == 0 {
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if proxy.Name() == f.selected {
|
if proxy.Name() == f.selected {
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(f.testUrl) {
|
|
||||||
return proxy
|
return proxy
|
||||||
} else {
|
} else {
|
||||||
f.selected = ""
|
f.selected = ""
|
||||||
@ -135,21 +124,15 @@ func (f *Fallback) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
f.selected = name
|
f.selected = name
|
||||||
// if !p.Alive() {
|
if !p.Alive() {
|
||||||
if !p.AliveForTestUrl(f.testUrl) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
defer cancel()
|
defer cancel()
|
||||||
expectedStatus, _ := utils.NewIntRanges[uint16](f.expectedStatus)
|
_, _ = p.URLTest(ctx, f.testUrl)
|
||||||
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus, C.ExtraHistory)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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{
|
||||||
@ -166,6 +149,5 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
testUrl: option.URL,
|
||||||
expectedStatus: option.ExpectedStatus,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,8 +8,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
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"
|
||||||
@ -17,6 +15,7 @@ import (
|
|||||||
"github.com/Dreamacro/clash/tunnel"
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
@ -131,6 +130,10 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
|
||||||
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||||
var newProxies []C.Proxy
|
var newProxies []C.Proxy
|
||||||
proxiesSet := map[string]struct{}{}
|
proxiesSet := map[string]struct{}{}
|
||||||
@ -186,14 +189,10 @@ func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|||||||
proxies = newProxies
|
proxies = newProxies
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (map[string]uint16, error) {
|
func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16, error) {
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
var lock sync.Mutex
|
var lock sync.Mutex
|
||||||
mp := map[string]uint16{}
|
mp := map[string]uint16{}
|
||||||
@ -202,7 +201,7 @@ func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus uti
|
|||||||
proxy := proxy
|
proxy := proxy
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
delay, err := proxy.URLTest(ctx, url, expectedStatus, C.DropHistory)
|
delay, err := proxy.URLTest(ctx, url)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
lock.Lock()
|
lock.Lock()
|
||||||
mp[proxy.Name()] = delay
|
mp[proxy.Name()] = delay
|
||||||
|
@ -6,14 +6,12 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/Dreamacro/clash/common/callback"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
"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"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -21,14 +19,12 @@ 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
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
testUrl string
|
|
||||||
expectedStatus string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
@ -96,16 +92,16 @@ func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
lb.onDialFailed(proxy.Type(), err)
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
c = &callback.FirstWriteCallBackConn{
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
lb.onDialSuccess()
|
lb.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
lb.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,33 +122,23 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
return !lb.disableUDP
|
return !lb.disableUDP
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsL3Protocol implements C.ProxyAdapter
|
func strategyRoundRobin() strategyFn {
|
||||||
func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool {
|
flag := true
|
||||||
return lb.Unwrap(metadata, false).IsL3Protocol(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func strategyRoundRobin(url string) 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 {
|
flag = !flag
|
||||||
defer func() {
|
if flag {
|
||||||
idx = (idx + i) % length
|
idx = (idx - 1) % length
|
||||||
}()
|
} else {
|
||||||
|
idx = (idx + 2) % length
|
||||||
}
|
}
|
||||||
|
if idx < 0 {
|
||||||
for ; i < length; i++ {
|
idx = idx + length
|
||||||
id := (idx + i) % length
|
}
|
||||||
proxy := proxies[id]
|
proxy := proxies[idx]
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
|
||||||
i++
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -161,24 +147,22 @@ func strategyRoundRobin(url string) strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func strategyConsistentHashing(url string) 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 := utils.MapHash(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 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := proxies[idx]
|
proxy := proxies[idx]
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// when availability is poor, traverse the entire list to get the available nodes
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -187,14 +171,14 @@ func strategyConsistentHashing(url string) strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func strategyStickySessions(url string) strategyFn {
|
func strategyStickySessions() strategyFn {
|
||||||
ttl := time.Minute * 10
|
ttl := time.Minute * 10
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
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 := utils.MapHash(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)
|
||||||
if !has {
|
if !has {
|
||||||
@ -204,8 +188,7 @@ func strategyStickySessions(url string) strategyFn {
|
|||||||
nowIdx := idx
|
nowIdx := idx
|
||||||
for i := 1; i < maxRetry; i++ {
|
for i := 1; i < maxRetry; i++ {
|
||||||
proxy := proxies[nowIdx]
|
proxy := proxies[nowIdx]
|
||||||
// if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
if proxy.AliveForTestUrl(url) {
|
|
||||||
if nowIdx != idx {
|
if nowIdx != idx {
|
||||||
lruCache.Delete(key)
|
lruCache.Delete(key)
|
||||||
lruCache.Set(key, nowIdx)
|
lruCache.Set(key, nowIdx)
|
||||||
@ -226,7 +209,7 @@ func strategyStickySessions(url string) 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
|
||||||
@ -238,8 +221,6 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": lb.Type().String(),
|
"type": lb.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": lb.testUrl,
|
|
||||||
"expectedStatus": lb.expectedStatus,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -247,11 +228,11 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
var strategyFn strategyFn
|
var strategyFn strategyFn
|
||||||
switch strategy {
|
switch strategy {
|
||||||
case "consistent-hashing":
|
case "consistent-hashing":
|
||||||
strategyFn = strategyConsistentHashing(option.URL)
|
strategyFn = strategyConsistentHashing()
|
||||||
case "round-robin":
|
case "round-robin":
|
||||||
strategyFn = strategyRoundRobin(option.URL)
|
strategyFn = strategyRoundRobin()
|
||||||
case "sticky-sessions":
|
case "sticky-sessions":
|
||||||
strategyFn = strategyStickySessions(option.URL)
|
strategyFn = strategyStickySessions()
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
@ -270,7 +251,5 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
|
||||||
expectedStatus: option.ExpectedStatus,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
@ -3,20 +3,19 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errFormat = errors.New("format error")
|
errFormat = errors.New("format error")
|
||||||
errType = errors.New("unsupported type")
|
errType = errors.New("unsupport type")
|
||||||
errMissProxy = errors.New("`use` or `proxies` missing")
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
|
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||||
errDuplicateProvider = errors.New("duplicate provider name")
|
errDuplicateProvider = errors.New("duplicate provider name")
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -33,7 +32,6 @@ type GroupCommonOption struct {
|
|||||||
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"`
|
ExcludeType string `group:"exclude-type,omitempty"`
|
||||||
ExpectedStatus string `group:"expected-status,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) {
|
||||||
@ -55,36 +53,30 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providers := []types.ProxyProvider{}
|
providers := []types.ProxyProvider{}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
return nil, errMissProxy
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewIntRanges[uint16](groupOption.ExpectedStatus)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
status := strings.TrimSpace(groupOption.ExpectedStatus)
|
|
||||||
if status == "" {
|
|
||||||
status = "*"
|
|
||||||
}
|
|
||||||
groupOption.ExpectedStatus = status
|
|
||||||
testUrl := groupOption.URL
|
|
||||||
|
|
||||||
if len(groupOption.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := providersMap[groupName]; ok {
|
if _, ok := providersMap[groupName]; ok {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
return nil, errDuplicateProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
var url string
|
|
||||||
var interval uint
|
|
||||||
|
|
||||||
// select don't need health check
|
// select don't need health check
|
||||||
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
} else {
|
||||||
if groupOption.URL == "" {
|
if groupOption.URL == "" {
|
||||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
||||||
}
|
}
|
||||||
@ -93,29 +85,22 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
groupOption.Interval = 300
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
|
|
||||||
url = groupOption.URL
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
interval = uint(groupOption.Interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, url, interval, true, expectedStatus)
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
list, err := getProviders(providersMap, groupOption.Use)
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s: %w", groupName, err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// different proxy groups use different test URL
|
|
||||||
addTestUrlToProviders(list, testUrl, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
|
||||||
|
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
} else {
|
} else {
|
||||||
groupOption.Filter = ""
|
groupOption.Filter = ""
|
||||||
@ -169,13 +154,3 @@ func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]type
|
|||||||
}
|
}
|
||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func addTestUrlToProviders(providers []types.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
|
||||||
if len(providers) == 0 || len(url) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, pd := range providers {
|
|
||||||
pd.RegisterHealthCheckTask(url, expectedStatus, filter, interval)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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)
|
||||||
|
@ -3,12 +3,10 @@ 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"
|
"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,9 +23,6 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
selected string
|
|
||||||
testUrl string
|
|
||||||
expectedStatus string
|
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
@ -38,26 +33,6 @@ 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)
|
||||||
@ -68,16 +43,16 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
c = &callback.FirstWriteCallBackConn{
|
||||||
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
Conn: c,
|
||||||
|
Callback: func(err error) {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
u.onDialSuccess()
|
u.onDialSuccess()
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed(proxy.Type(), err)
|
u.onDialFailed(proxy.Type(), err)
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,24 +72,10 @@ 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 {
|
||||||
|
|
||||||
proxies := u.GetProxies(touch)
|
|
||||||
if u.selected != "" {
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
if !proxy.Alive() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if proxy.Name() == u.selected {
|
|
||||||
u.fastNode = proxy
|
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
// min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
min := fast.LastDelayForTestUrl(u.testUrl)
|
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
@ -122,24 +83,22 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
fastNotExist = false
|
fastNotExist = false
|
||||||
}
|
}
|
||||||
|
|
||||||
// if !proxy.Alive() {
|
if !proxy.Alive() {
|
||||||
if !proxy.AliveForTestUrl(u.testUrl) {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// delay := proxy.LastDelay()
|
delay := proxy.LastDelay()
|
||||||
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
|
||||||
if delay < min {
|
if delay < min {
|
||||||
fast = proxy
|
fast = 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 {
|
||||||
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@ -154,12 +113,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
|
||||||
@ -172,8 +127,6 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
"testUrl": u.testUrl,
|
|
||||||
"expected": u.expectedStatus,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -207,8 +160,6 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
}),
|
}),
|
||||||
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,
|
|
||||||
expectedStatus: option.ExpectedStatus,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -1,6 +1,44 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"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) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type SelectAble interface {
|
type SelectAble interface {
|
||||||
Set(string) error
|
Set(string) error
|
||||||
ForceSet(name string)
|
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,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,7 +56,10 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
ClientFingerprint: tlsC.GetGlobalFingerprint(),
|
}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
vmessOption.ClientFingerprint = GlobalUtlsClient
|
||||||
}
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
@ -65,7 +68,12 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
vlessOption := &outbound.VlessOption{}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
vlessOption.ClientFingerprint = GlobalUtlsClient
|
||||||
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -79,7 +87,12 @@ 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{}
|
||||||
|
|
||||||
|
if GlobalUtlsClient := tlsC.GetGlobalFingerprint(); len(GlobalUtlsClient) != 0 {
|
||||||
|
trojanOption.ClientFingerprint = GlobalUtlsClient
|
||||||
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -92,13 +105,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
case "hysteria2":
|
|
||||||
hyOption := &outbound.Hysteria2Option{}
|
|
||||||
err = decoder.Decode(mapping, hyOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewHysteria2(*hyOption)
|
|
||||||
case "wireguard":
|
case "wireguard":
|
||||||
wgOption := &outbound.WireGuardOption{}
|
wgOption := &outbound.WireGuardOption{}
|
||||||
err = decoder.Decode(mapping, wgOption)
|
err = decoder.Decode(mapping, wgOption)
|
||||||
@ -113,13 +119,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewTuic(*tuicOption)
|
proxy, err = outbound.NewTuic(*tuicOption)
|
||||||
case "direct":
|
|
||||||
directOption := &outbound.DirectOption{}
|
|
||||||
err = decoder.Decode(mapping, directOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = outbound.NewDirectWithOption(*directOption)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
@ -128,19 +127,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
|
||||||
}
|
}
|
||||||
|
@ -2,18 +2,15 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"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/dlclark/regexp2"
|
"github.com/gofrs/uuid"
|
||||||
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -25,47 +22,43 @@ type HealthCheckOption struct {
|
|||||||
Interval uint
|
Interval uint
|
||||||
}
|
}
|
||||||
|
|
||||||
type extraOption struct {
|
|
||||||
expectedStatus utils.IntRanges[uint16]
|
|
||||||
filters map[string]struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type HealthCheck struct {
|
type HealthCheck struct {
|
||||||
url string
|
url string
|
||||||
extra map[string]*extraOption
|
|
||||||
mu sync.Mutex
|
|
||||||
started *atomic.Bool
|
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
interval uint
|
interval uint
|
||||||
lazy bool
|
lazy bool
|
||||||
expectedStatus utils.IntRanges[uint16]
|
|
||||||
lastTouch *atomic.Int64
|
lastTouch *atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
singleDo *singledo.Single[struct{}]
|
singleDo *singledo.Single[struct{}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
if hc.started.Load() {
|
|
||||||
log.Warnln("Skip start health check timer due to it's started")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
hc.start()
|
|
||||||
|
go func() {
|
||||||
|
time.Sleep(30 * time.Second)
|
||||||
|
hc.lazyCheck()
|
||||||
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
|
hc.lazyCheck()
|
||||||
|
case <-hc.done:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) lazyCheck() bool {
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
hc.check()
|
hc.check()
|
||||||
|
return true
|
||||||
} else {
|
} else {
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
}
|
return false
|
||||||
case <-hc.done:
|
|
||||||
ticker.Stop()
|
|
||||||
hc.stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -73,63 +66,6 @@ func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
|||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
|
||||||
url = strings.TrimSpace(url)
|
|
||||||
if len(url) == 0 || url == hc.url {
|
|
||||||
log.Debugln("ignore invalid health check url: %s", url)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
hc.mu.Lock()
|
|
||||||
defer hc.mu.Unlock()
|
|
||||||
|
|
||||||
// if the provider has not set up health checks, then modify it to be the same as the group's interval
|
|
||||||
if hc.interval == 0 {
|
|
||||||
hc.interval = interval
|
|
||||||
}
|
|
||||||
|
|
||||||
if hc.extra == nil {
|
|
||||||
hc.extra = make(map[string]*extraOption)
|
|
||||||
}
|
|
||||||
|
|
||||||
// prioritize the use of previously registered configurations, especially those from provider
|
|
||||||
if _, ok := hc.extra[url]; ok {
|
|
||||||
// provider default health check does not set filter
|
|
||||||
if url != hc.url && len(filter) != 0 {
|
|
||||||
splitAndAddFiltersToExtra(filter, hc.extra[url])
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debugln("health check url: %s exists", url)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// due to the time-consuming nature of health checks, a maximum of defaultMaxTestURLNum URLs can be set for testing
|
|
||||||
if len(hc.extra) > C.DefaultMaxHealthCheckUrlNum {
|
|
||||||
log.Debugln("skip add url: %s to health check because it has reached the maximum limit: %d", url, C.DefaultMaxHealthCheckUrlNum)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
|
||||||
splitAndAddFiltersToExtra(filter, option)
|
|
||||||
hc.extra[url] = option
|
|
||||||
|
|
||||||
if hc.auto() && !hc.started.Load() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitAndAddFiltersToExtra(filter string, option *extraOption) {
|
|
||||||
filter = strings.TrimSpace(filter)
|
|
||||||
if len(filter) != 0 {
|
|
||||||
for _, regex := range strings.Split(filter, "`") {
|
|
||||||
regex = strings.TrimSpace(regex)
|
|
||||||
if len(regex) != 0 {
|
|
||||||
option.filters[regex] = struct{}{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) auto() bool {
|
func (hc *HealthCheck) auto() bool {
|
||||||
return hc.interval != 0
|
return hc.interval != 0
|
||||||
}
|
}
|
||||||
@ -138,100 +74,42 @@ func (hc *HealthCheck) touch() {
|
|||||||
hc.lastTouch.Store(time.Now().Unix())
|
hc.lastTouch.Store(time.Now().Unix())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) start() {
|
|
||||||
hc.started.Store(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) stop() {
|
|
||||||
hc.started.Store(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
||||||
// execute default health check
|
p := proxy
|
||||||
option := &extraOption{filters: nil, expectedStatus: hc.expectedStatus}
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
hc.execute(b, hc.url, id, option)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
defer cancel()
|
||||||
// execute extra health check
|
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
||||||
if len(hc.extra) != 0 {
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
for url, option := range hc.extra {
|
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
||||||
hc.execute(b, url, id, option)
|
return false, nil
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Wait()
|
b.Wait()
|
||||||
log.Debugln("Finish A Health Checking {%s}", id)
|
log.Debugln("Finish A Health Checking {%s}", id)
|
||||||
return struct{}{}, nil
|
return struct{}{}, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) execute(b *batch.Batch[bool], url, uid string, option *extraOption) {
|
|
||||||
url = strings.TrimSpace(url)
|
|
||||||
if len(url) == 0 {
|
|
||||||
log.Debugln("Health Check has been skipped due to testUrl is empty, {%s}", uid)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterReg *regexp2.Regexp
|
|
||||||
var store = C.OriginalHistory
|
|
||||||
var expectedStatus utils.IntRanges[uint16]
|
|
||||||
if option != nil {
|
|
||||||
if url != hc.url {
|
|
||||||
store = C.ExtraHistory
|
|
||||||
}
|
|
||||||
|
|
||||||
expectedStatus = option.expectedStatus
|
|
||||||
if len(option.filters) != 0 {
|
|
||||||
filters := make([]string, 0, len(option.filters))
|
|
||||||
for filter := range option.filters {
|
|
||||||
filters = append(filters, filter)
|
|
||||||
}
|
|
||||||
|
|
||||||
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, proxy := range hc.proxies {
|
|
||||||
// skip proxies that do not require health check
|
|
||||||
if filterReg != nil {
|
|
||||||
if match, _ := filterReg.FindStringMatch(proxy.Name()); match == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
p := proxy
|
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
||||||
defer cancel()
|
|
||||||
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
|
||||||
_, _ = p.URLTest(ctx, url, expectedStatus, store)
|
|
||||||
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
|
||||||
return false, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
hc.done <- struct{}{}
|
hc.done <- struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
|
||||||
if len(url) == 0 {
|
|
||||||
interval = 0
|
|
||||||
expectedStatus = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &HealthCheck{
|
return &HealthCheck{
|
||||||
proxies: proxies,
|
proxies: proxies,
|
||||||
url: url,
|
url: url,
|
||||||
extra: map[string]*extraOption{},
|
|
||||||
started: atomic.NewBool(false),
|
|
||||||
interval: interval,
|
interval: interval,
|
||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
expectedStatus: expectedStatus,
|
|
||||||
lastTouch: atomic.NewInt64(0),
|
lastTouch: atomic.NewInt64(0),
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
|
@ -6,34 +6,28 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var errVehicleType = errors.New("unsupport vehicle type")
|
||||||
errVehicleType = errors.New("unsupport vehicle type")
|
|
||||||
errSubPath = errors.New("path is not subpath of home directory")
|
|
||||||
)
|
|
||||||
|
|
||||||
type healthCheckSchema struct {
|
type healthCheckSchema struct {
|
||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
URL string `provider:"url"`
|
URL string `provider:"url"`
|
||||||
Interval int `provider:"interval"`
|
Interval int `provider:"interval"`
|
||||||
Lazy bool `provider:"lazy,omitempty"`
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
ExpectedStatus string `provider:"expected-status,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path,omitempty"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -49,33 +43,20 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedStatus, err := utils.NewIntRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var hcInterval uint
|
var hcInterval uint
|
||||||
if schema.HealthCheck.Enable {
|
if schema.HealthCheck.Enable {
|
||||||
hcInterval = uint(schema.HealthCheck.Interval)
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
}
|
}
|
||||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
|
||||||
|
|
||||||
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
|
||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
path := C.Path.Resolve(schema.Path)
|
|
||||||
vehicle = resource.NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
if schema.Path != "" {
|
|
||||||
path := C.Path.Resolve(schema.Path)
|
|
||||||
if !C.Path.IsSafePath(path) {
|
|
||||||
return nil, fmt.Errorf("%w: %s", errSubPath, path)
|
|
||||||
}
|
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||||
} else {
|
|
||||||
path := C.Path.GetPathByHash("proxies", schema.URL)
|
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
@ -84,7 +65,6 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
excludeFilter := schema.ExcludeFilter
|
excludeFilter := schema.ExcludeFilter
|
||||||
excludeType := schema.ExcludeType
|
excludeType := schema.ExcludeType
|
||||||
dialerProxy := schema.DialerProxy
|
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, dialerProxy, vehicle, hc)
|
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -12,13 +12,11 @@ import (
|
|||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
clashHttp "github.com/Dreamacro/clash/component/http"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
"github.com/Dreamacro/clash/tunnel/statistic"
|
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
"github.com/dlclark/regexp2"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@ -51,7 +49,6 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"testUrl": pp.healthCheck.url,
|
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
"subscriptionInfo": pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
@ -83,8 +80,6 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pp.OnUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
pp.getSubscriptionInfo()
|
|
||||||
pp.closeAllConnections()
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,15 +95,11 @@ func (pp *proxySetProvider) Touch() {
|
|||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
|
||||||
pp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
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() }()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,24 +137,12 @@ func (pp *proxySetProvider) getSubscriptionInfo() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) closeAllConnections() {
|
|
||||||
statistic.DefaultManager.Range(func(c statistic.Tracker) bool {
|
|
||||||
for _, chain := range c.Chains() {
|
|
||||||
if chain == pp.Name() {
|
|
||||||
_ = c.Close()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
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, excludeType 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)
|
||||||
@ -191,8 +170,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, excludeTypeArray, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
|
pd.getSubscriptionInfo()
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -216,7 +197,6 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": cp.Type().String(),
|
"type": cp.Type().String(),
|
||||||
"vehicleType": cp.VehicleType().String(),
|
"vehicleType": cp.VehicleType().String(),
|
||||||
"proxies": cp.Proxies(),
|
"proxies": cp.Proxies(),
|
||||||
"testUrl": cp.healthCheck.url,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -256,10 +236,6 @@ func (cp *compatibleProvider) Touch() {
|
|||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
|
||||||
cp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
}
|
}
|
||||||
@ -292,14 +268,14 @@ 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, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||||
if err1 != nil {
|
if err1 != nil {
|
||||||
return nil, fmt.Errorf("%w, %w", err, err1)
|
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
||||||
}
|
}
|
||||||
schema.Proxies = proxies
|
schema.Proxies = proxies
|
||||||
}
|
}
|
||||||
@ -355,9 +331,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
|
|
||||||
}
|
|
@ -5,16 +5,16 @@ import (
|
|||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
)
|
)
|
||||||
|
|
||||||
const BufferSize = buf.BufferSize
|
|
||||||
|
|
||||||
type Buffer = buf.Buffer
|
type Buffer = buf.Buffer
|
||||||
|
|
||||||
var New = buf.New
|
var StackNew = buf.StackNew
|
||||||
var NewSize = buf.NewSize
|
var StackNewSize = buf.StackNewSize
|
||||||
var With = buf.With
|
var KeepAlive = common.KeepAlive
|
||||||
var As = buf.As
|
|
||||||
|
|
||||||
var (
|
//go:norace
|
||||||
Must = common.Must
|
func Dup[T any](obj T) T {
|
||||||
Error = common.Error
|
return common.Dup(obj)
|
||||||
)
|
}
|
||||||
|
|
||||||
|
var Must = common.Must
|
||||||
|
var Error = common.Error
|
||||||
|
53
common/cache/lrucache.go
vendored
53
common/cache/lrucache.go
vendored
@ -7,8 +7,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/generics/list"
|
"github.com/Dreamacro/clash/common/generics/list"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Option is part of Functional Options Pattern
|
// Option is part of Functional Options Pattern
|
||||||
@ -84,27 +82,9 @@ func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
|||||||
// Get returns the any representation of a cached response and a bool
|
// Get returns the any representation of a cached response and a bool
|
||||||
// set to true if the key was found.
|
// set to true if the key was found.
|
||||||
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
func (c *LruCache[K, V]) Get(key K) (V, bool) {
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
el := c.get(key)
|
el := c.get(key)
|
||||||
if el == nil {
|
if el == nil {
|
||||||
return lo.Empty[V](), false
|
return getZero[V](), false
|
||||||
}
|
|
||||||
value := el.value
|
|
||||||
|
|
||||||
return value, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
el := c.get(key)
|
|
||||||
if el == nil {
|
|
||||||
value := constructor()
|
|
||||||
c.set(key, value)
|
|
||||||
return value, false
|
|
||||||
}
|
}
|
||||||
value := el.value
|
value := el.value
|
||||||
|
|
||||||
@ -116,12 +96,9 @@ func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
|
|||||||
// and a bool set to true if the key was found.
|
// and a bool set to true if the key was found.
|
||||||
// This method will NOT check the maxAge of element and will NOT update the expires.
|
// This method will NOT check the maxAge of element and will NOT update the expires.
|
||||||
func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
el := c.get(key)
|
el := c.get(key)
|
||||||
if el == nil {
|
if el == nil {
|
||||||
return lo.Empty[V](), time.Time{}, false
|
return getZero[V](), time.Time{}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
return el.value, time.Unix(el.expires, 0), true
|
return el.value, time.Unix(el.expires, 0), true
|
||||||
@ -138,18 +115,11 @@ func (c *LruCache[K, V]) Exist(key K) bool {
|
|||||||
|
|
||||||
// Set stores the any representation of a response for a given key.
|
// Set stores the any representation of a response for a given key.
|
||||||
func (c *LruCache[K, V]) Set(key K, value V) {
|
func (c *LruCache[K, V]) Set(key K, value V) {
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
c.set(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *LruCache[K, V]) set(key K, value V) {
|
|
||||||
expires := int64(0)
|
expires := int64(0)
|
||||||
if c.maxAge > 0 {
|
if c.maxAge > 0 {
|
||||||
expires = time.Now().Unix() + c.maxAge
|
expires = time.Now().Unix() + c.maxAge
|
||||||
}
|
}
|
||||||
c.setWithExpire(key, value, time.Unix(expires, 0))
|
c.SetWithExpire(key, value, time.Unix(expires, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
// SetWithExpire stores the any representation of a response for a given key and given expires.
|
||||||
@ -158,10 +128,6 @@ func (c *LruCache[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
|||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
c.setWithExpire(key, value, expires)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *LruCache[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
c.lru.MoveToBack(le)
|
c.lru.MoveToBack(le)
|
||||||
e := le.Value
|
e := le.Value
|
||||||
@ -199,6 +165,9 @@ func (c *LruCache[K, V]) CloneTo(n *LruCache[K, V]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
le, ok := c.cache[key]
|
le, ok := c.cache[key]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
@ -222,11 +191,12 @@ func (c *LruCache[K, V]) get(key K) *entry[K, V] {
|
|||||||
// Delete removes the value associated with a key.
|
// Delete removes the value associated with a key.
|
||||||
func (c *LruCache[K, V]) Delete(key K) {
|
func (c *LruCache[K, V]) Delete(key K) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
if le, ok := c.cache[key]; ok {
|
if le, ok := c.cache[key]; ok {
|
||||||
c.deleteElement(le)
|
c.deleteElement(le)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache[K, V]) maybeDeleteOldest() {
|
func (c *LruCache[K, V]) maybeDeleteOldest() {
|
||||||
@ -249,10 +219,10 @@ func (c *LruCache[K, V]) deleteElement(le *list.Element[*entry[K, V]]) {
|
|||||||
|
|
||||||
func (c *LruCache[K, V]) Clear() error {
|
func (c *LruCache[K, V]) Clear() error {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
|
||||||
|
|
||||||
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
c.cache = make(map[K]*list.Element[*entry[K, V]])
|
||||||
|
|
||||||
|
c.mu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -261,3 +231,8 @@ type entry[K comparable, V any] struct {
|
|||||||
value V
|
value V
|
||||||
expires int64
|
expires int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
@ -1,55 +1,25 @@
|
|||||||
package callback
|
package callback
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type firstWriteCallBackConn struct {
|
type FirstWriteCallBackConn struct {
|
||||||
C.Conn
|
C.Conn
|
||||||
callback func(error)
|
Callback func(error)
|
||||||
written bool
|
written bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
func (c *FirstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if !c.written {
|
if !c.written {
|
||||||
c.written = true
|
c.written = true
|
||||||
c.callback(err)
|
c.Callback(err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
return c.Conn.Write(b)
|
return c.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
|
func (c *FirstWriteCallBackConn) Upstream() any {
|
||||||
defer func() {
|
|
||||||
if !c.written {
|
|
||||||
c.written = true
|
|
||||||
c.callback(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return c.Conn.WriteBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *firstWriteCallBackConn) Upstream() any {
|
|
||||||
return c.Conn
|
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -21,7 +21,7 @@ func TestSplitArgs(t *testing.T) {
|
|||||||
|
|
||||||
func TestExecCmd(t *testing.T) {
|
func TestExecCmd(t *testing.T) {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
_, err := ExecCmd("cmd -c 'dir'")
|
_, err := ExecCmd("dir")
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -5,11 +5,10 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
"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
|
||||||
@ -50,9 +49,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["port"] = urlHysteria.Port()
|
hysteria["port"] = urlHysteria.Port()
|
||||||
hysteria["sni"] = query.Get("peer")
|
hysteria["sni"] = query.Get("peer")
|
||||||
hysteria["obfs"] = query.Get("obfs")
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
hysteria["alpn"] = []string{query.Get("alpn")}
|
||||||
hysteria["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
hysteria["auth_str"] = query.Get("auth")
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
hysteria["protocol"] = query.Get("protocol")
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
up := query.Get("up")
|
up := query.Get("up")
|
||||||
@ -68,79 +65,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
proxies = append(proxies, hysteria)
|
||||||
case "hysteria2":
|
|
||||||
urlHysteria2, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
query := urlHysteria2.Query()
|
|
||||||
name := uniqueName(names, urlHysteria2.Fragment)
|
|
||||||
hysteria2 := make(map[string]any, 20)
|
|
||||||
|
|
||||||
hysteria2["name"] = name
|
|
||||||
hysteria2["type"] = scheme
|
|
||||||
hysteria2["server"] = urlHysteria2.Hostname()
|
|
||||||
if port := urlHysteria2.Port(); port != "" {
|
|
||||||
hysteria2["port"] = port
|
|
||||||
} else {
|
|
||||||
hysteria2["port"] = "443"
|
|
||||||
}
|
|
||||||
hysteria2["obfs"] = query.Get("obfs")
|
|
||||||
hysteria2["obfs-password"] = query.Get("obfs-password")
|
|
||||||
hysteria2["sni"] = query.Get("sni")
|
|
||||||
hysteria2["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
|
||||||
hysteria2["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
if auth := urlHysteria2.User.String(); auth != "" {
|
|
||||||
hysteria2["password"] = auth
|
|
||||||
}
|
|
||||||
hysteria2["fingerprint"] = query.Get("pinSHA256")
|
|
||||||
hysteria2["down"] = query.Get("down")
|
|
||||||
hysteria2["up"] = query.Get("up")
|
|
||||||
|
|
||||||
proxies = append(proxies, hysteria2)
|
|
||||||
case "tuic":
|
|
||||||
// A temporary unofficial TUIC share link standard
|
|
||||||
// Modified from https://github.com/daeuniverse/dae/discussions/182
|
|
||||||
// Changes:
|
|
||||||
// 1. Support TUICv4, just replace uuid:password with token
|
|
||||||
// 2. Remove `allow_insecure` field
|
|
||||||
urlTUIC, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
query := urlTUIC.Query()
|
|
||||||
|
|
||||||
tuic := make(map[string]any, 20)
|
|
||||||
tuic["name"] = uniqueName(names, urlTUIC.Fragment)
|
|
||||||
tuic["type"] = scheme
|
|
||||||
tuic["server"] = urlTUIC.Hostname()
|
|
||||||
tuic["port"] = urlTUIC.Port()
|
|
||||||
tuic["udp"] = true
|
|
||||||
password, v5 := urlTUIC.User.Password()
|
|
||||||
if v5 {
|
|
||||||
tuic["uuid"] = urlTUIC.User.Username()
|
|
||||||
tuic["password"] = password
|
|
||||||
} else {
|
|
||||||
tuic["token"] = urlTUIC.User.Username()
|
|
||||||
}
|
|
||||||
if cc := query.Get("congestion_control"); cc != "" {
|
|
||||||
tuic["congestion-controller"] = cc
|
|
||||||
}
|
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
|
||||||
tuic["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
if sni := query.Get("sni"); sni != "" {
|
|
||||||
tuic["sni"] = sni
|
|
||||||
}
|
|
||||||
if query.Get("disable_sni") == "1" {
|
|
||||||
tuic["disable-sni"] = true
|
|
||||||
}
|
|
||||||
if udpRelayMode := query.Get("udp_relay_mode"); udpRelayMode != "" {
|
|
||||||
tuic["udp-relay-mode"] = udpRelayMode
|
|
||||||
}
|
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
@ -159,14 +83,12 @@ 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
|
||||||
|
|
||||||
if sni := query.Get("sni"); sni != "" {
|
sni := query.Get("sni")
|
||||||
|
if sni != "" {
|
||||||
trojan["sni"] = sni
|
trojan["sni"] = sni
|
||||||
}
|
}
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
|
||||||
trojan["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
network := strings.ToLower(query.Get("type"))
|
||||||
if network != "" {
|
if network != "" {
|
||||||
@ -279,8 +201,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" {
|
||||||
@ -288,16 +209,10 @@ 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 {
|
|
||||||
tls = strings.ToLower(tls)
|
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
vmess["tls"] = true
|
vmess["tls"] = true
|
||||||
}
|
}
|
||||||
if alpn, ok := values["alpn"].(string); ok {
|
|
||||||
vmess["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "http":
|
case "http":
|
||||||
@ -412,7 +327,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
|
|
||||||
case "ssr":
|
case "ssr":
|
||||||
dcBuf, err := encRaw.DecodeString(body)
|
dcBuf, err := encRaw.DecodeString(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,35 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
// https://v2.hysteria.network/zh/docs/developers/URI-Scheme/
|
|
||||||
func TestConvertsV2Ray_normal(t *testing.T) {
|
|
||||||
hy2test := "hysteria2://letmein@example.com:8443/?insecure=1&obfs=salamander&obfs-password=gawrgura&pinSHA256=deadbeef&sni=real.example.com&up=114&down=514&alpn=h3,h4#hy2test"
|
|
||||||
|
|
||||||
expected := []map[string]interface{}{
|
|
||||||
{
|
|
||||||
"name": "hy2test",
|
|
||||||
"type": "hysteria2",
|
|
||||||
"server": "example.com",
|
|
||||||
"port": "8443",
|
|
||||||
"sni": "real.example.com",
|
|
||||||
"obfs": "salamander",
|
|
||||||
"obfs-password": "gawrgura",
|
|
||||||
"alpn": []string{"h3", "h4"},
|
|
||||||
"password": "letmein",
|
|
||||||
"up": "114",
|
|
||||||
"down": "514",
|
|
||||||
"skip-cert-verify": true,
|
|
||||||
"fingerprint": "deadbeef",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := ConvertsV2Ray([]byte(hy2test))
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, expected, proxies)
|
|
||||||
}
|
|
@ -2,14 +2,12 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/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 +292,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 +301,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) {
|
||||||
@ -318,6 +317,6 @@ func SetUserAgent(header http.Header) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func VerifyMethod(cipher, password string) (err error) {
|
func VerifyMethod(cipher, password string) (err error) {
|
||||||
_, err = shadowimpl.FetchMethod(cipher, password, time.Now)
|
_, err = shadowimpl.FetchMethod(cipher, password)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -24,27 +24,20 @@ func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy m
|
|||||||
proxy["port"] = url.Port()
|
proxy["port"] = url.Port()
|
||||||
proxy["uuid"] = url.User.Username()
|
proxy["uuid"] = url.User.Username()
|
||||||
proxy["udp"] = true
|
proxy["udp"] = true
|
||||||
|
proxy["skip-cert-verify"] = 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 == "" {
|
if fingerprint := query.Get("fp"); fingerprint == "" {
|
||||||
proxy["client-fingerprint"] = "chrome"
|
proxy["client-fingerprint"] = "chrome"
|
||||||
} else {
|
} else {
|
||||||
proxy["client-fingerprint"] = fingerprint
|
proxy["client-fingerprint"] = fingerprint
|
||||||
}
|
}
|
||||||
if alpn := query.Get("alpn"); alpn != "" {
|
|
||||||
proxy["alpn"] = strings.Split(alpn, ",")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if sni := query.Get("sni"); sni != "" {
|
if sni := query.Get("sni"); sni != "" {
|
||||||
proxy["servername"] = sni
|
proxy["servername"] = sni
|
||||||
}
|
}
|
||||||
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
|
|
||||||
proxy["reality-opts"] = map[string]any{
|
|
||||||
"public-key": realityPublicKey,
|
|
||||||
"short-id": query.Get("sid"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch query.Get("packetEncoding") {
|
switch query.Get("packetEncoding") {
|
||||||
case "none":
|
case "none":
|
||||||
|
@ -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,43 +3,34 @@ package net
|
|||||||
import "net"
|
import "net"
|
||||||
|
|
||||||
type bindPacketConn struct {
|
type bindPacketConn struct {
|
||||||
EnhancePacketConn
|
net.PacketConn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *bindPacketConn) Read(b []byte) (n int, err error) {
|
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
||||||
n, _, err = c.EnhancePacketConn.ReadFrom(b)
|
n, _, err = wpc.PacketConn.ReadFrom(b)
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *bindPacketConn) WaitRead() (data []byte, put func(), err error) {
|
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
||||||
data, put, _, err = c.EnhancePacketConn.WaitReadFrom()
|
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *bindPacketConn) Write(b []byte) (n int, err error) {
|
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
||||||
return c.EnhancePacketConn.WriteTo(b, c.rAddr)
|
return wpc.rAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *bindPacketConn) RemoteAddr() net.Addr {
|
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
||||||
return c.rAddr
|
if wpc.PacketConn.LocalAddr() == nil {
|
||||||
}
|
|
||||||
|
|
||||||
func (c *bindPacketConn) LocalAddr() net.Addr {
|
|
||||||
if c.EnhancePacketConn.LocalAddr() == nil {
|
|
||||||
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
} else {
|
} else {
|
||||||
return c.EnhancePacketConn.LocalAddr()
|
return wpc.PacketConn.LocalAddr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *bindPacketConn) Upstream() any {
|
|
||||||
return c.EnhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
||||||
return &bindPacketConn{
|
return &bindPacketConn{
|
||||||
EnhancePacketConn: NewEnhancePacketConn(pc),
|
PacketConn: pc,
|
||||||
rAddr: rAddr,
|
rAddr: rAddr,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -27,10 +27,6 @@ func (c *BufferedConn) Reader() *bufio.Reader {
|
|||||||
return c.r
|
return c.r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ResetPeeked() {
|
|
||||||
c.peeked = false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Peeked() bool {
|
func (c *BufferedConn) Peeked() bool {
|
||||||
return c.peeked
|
return c.peeked
|
||||||
}
|
}
|
||||||
@ -62,35 +58,20 @@ func (c *BufferedConn) Buffered() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
||||||
if c.r != nil && c.r.Buffered() > 0 {
|
if c.r.Buffered() > 0 {
|
||||||
_, err = buffer.ReadOnceFrom(c.r)
|
_, err = buffer.ReadOnceFrom(c.r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return c.ExtendedConn.ReadBuffer(buffer)
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ReadCached() *buf.Buffer { // call in sing/common/bufio.Copy
|
|
||||||
if c.r != nil && c.r.Buffered() > 0 {
|
|
||||||
length := c.r.Buffered()
|
|
||||||
b, _ := c.r.Peek(length)
|
|
||||||
_, _ = c.r.Discard(length)
|
|
||||||
c.r = nil // drop bufio.Reader to let gc can clean up its internal buf
|
|
||||||
return buf.As(b)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Upstream() any {
|
func (c *BufferedConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ReaderReplaceable() bool {
|
func (c *BufferedConn) ReaderReplaceable() bool {
|
||||||
if c.r != nil && c.r.Buffered() > 0 {
|
if c.r.Buffered() > 0 {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
@ -1,154 +0,0 @@
|
|||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/atomic"
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
|
||||||
)
|
|
||||||
|
|
||||||
type readResult struct {
|
|
||||||
data []byte
|
|
||||||
addr net.Addr
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type NetPacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
deadline atomic.TypedValue[time.Time]
|
|
||||||
pipeDeadline pipeDeadline
|
|
||||||
disablePipe atomic.Bool
|
|
||||||
inRead atomic.Bool
|
|
||||||
resultCh chan any
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewNetPacketConn(pc net.PacketConn) net.PacketConn {
|
|
||||||
npc := &NetPacketConn{
|
|
||||||
PacketConn: pc,
|
|
||||||
pipeDeadline: makePipeDeadline(),
|
|
||||||
resultCh: make(chan any, 1),
|
|
||||||
}
|
|
||||||
npc.resultCh <- nil
|
|
||||||
if enhancePC, isEnhance := pc.(packet.EnhancePacketConn); isEnhance {
|
|
||||||
epc := &EnhancePacketConn{
|
|
||||||
NetPacketConn: npc,
|
|
||||||
enhancePacketConn: enhancePacketConn{
|
|
||||||
netPacketConn: npc,
|
|
||||||
enhancePacketConn: enhancePC,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
|
||||||
return &EnhanceSingPacketConn{
|
|
||||||
EnhancePacketConn: epc,
|
|
||||||
singPacketConn: singPacketConn{
|
|
||||||
netPacketConn: npc,
|
|
||||||
singPacketConn: singPC,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return epc
|
|
||||||
}
|
|
||||||
if singPC, isSingPC := pc.(packet.SingPacketConn); isSingPC {
|
|
||||||
return &SingPacketConn{
|
|
||||||
NetPacketConn: npc,
|
|
||||||
singPacketConn: singPacketConn{
|
|
||||||
netPacketConn: npc,
|
|
||||||
singPacketConn: singPC,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return npc
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
FOR:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case result := <-c.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
if result, ok := result.(*readResult); ok {
|
|
||||||
n = copy(p, result.data)
|
|
||||||
addr = result.addr
|
|
||||||
err = result.err
|
|
||||||
c.resultCh <- nil // finish cache read
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.resultCh <- result // another type of read
|
|
||||||
runtime.Gosched() // allowing other goroutines to run
|
|
||||||
continue FOR
|
|
||||||
} else {
|
|
||||||
c.resultCh <- nil
|
|
||||||
break FOR
|
|
||||||
}
|
|
||||||
case <-c.pipeDeadline.wait():
|
|
||||||
return 0, nil, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.disablePipe.Load() {
|
|
||||||
return c.PacketConn.ReadFrom(p)
|
|
||||||
} else if c.deadline.Load().IsZero() {
|
|
||||||
c.inRead.Store(true)
|
|
||||||
defer c.inRead.Store(false)
|
|
||||||
n, addr, err = c.PacketConn.ReadFrom(p)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.resultCh
|
|
||||||
go c.pipeReadFrom(len(p))
|
|
||||||
|
|
||||||
return c.ReadFrom(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) pipeReadFrom(size int) {
|
|
||||||
buffer := make([]byte, size)
|
|
||||||
n, addr, err := c.PacketConn.ReadFrom(buffer)
|
|
||||||
buffer = buffer[:n]
|
|
||||||
result := &readResult{}
|
|
||||||
result.data = buffer
|
|
||||||
result.addr = addr
|
|
||||||
result.err = err
|
|
||||||
c.resultCh <- result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
if c.disablePipe.Load() {
|
|
||||||
return c.PacketConn.SetReadDeadline(t)
|
|
||||||
} else if c.inRead.Load() {
|
|
||||||
c.disablePipe.Store(true)
|
|
||||||
return c.PacketConn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
c.deadline.Store(t)
|
|
||||||
c.pipeDeadline.set(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) ReaderReplaceable() bool {
|
|
||||||
select {
|
|
||||||
case result := <-c.resultCh:
|
|
||||||
c.resultCh <- result
|
|
||||||
if result != nil {
|
|
||||||
return false // cache reading
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return false // pipe reading
|
|
||||||
}
|
|
||||||
return c.disablePipe.Load() || c.deadline.Load().IsZero()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) Upstream() any {
|
|
||||||
return c.PacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *NetPacketConn) NeedAdditionalReadDeadline() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
@ -1,83 +0,0 @@
|
|||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
|
||||||
)
|
|
||||||
|
|
||||||
type EnhancePacketConn struct {
|
|
||||||
*NetPacketConn
|
|
||||||
enhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ packet.EnhancePacketConn = (*EnhancePacketConn)(nil)
|
|
||||||
|
|
||||||
func NewEnhancePacketConn(pc packet.EnhancePacketConn) packet.EnhancePacketConn {
|
|
||||||
return NewNetPacketConn(pc).(packet.EnhancePacketConn)
|
|
||||||
}
|
|
||||||
|
|
||||||
type enhanceReadResult struct {
|
|
||||||
data []byte
|
|
||||||
put func()
|
|
||||||
addr net.Addr
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type enhancePacketConn struct {
|
|
||||||
netPacketConn *NetPacketConn
|
|
||||||
enhancePacketConn packet.EnhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
FOR:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case result := <-c.netPacketConn.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
if result, ok := result.(*enhanceReadResult); ok {
|
|
||||||
data = result.data
|
|
||||||
put = result.put
|
|
||||||
addr = result.addr
|
|
||||||
err = result.err
|
|
||||||
c.netPacketConn.resultCh <- nil // finish cache read
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.netPacketConn.resultCh <- result // another type of read
|
|
||||||
runtime.Gosched() // allowing other goroutines to run
|
|
||||||
continue FOR
|
|
||||||
} else {
|
|
||||||
c.netPacketConn.resultCh <- nil
|
|
||||||
break FOR
|
|
||||||
}
|
|
||||||
case <-c.netPacketConn.pipeDeadline.wait():
|
|
||||||
return nil, nil, nil, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.netPacketConn.disablePipe.Load() {
|
|
||||||
return c.enhancePacketConn.WaitReadFrom()
|
|
||||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
|
||||||
c.netPacketConn.inRead.Store(true)
|
|
||||||
defer c.netPacketConn.inRead.Store(false)
|
|
||||||
data, put, addr, err = c.enhancePacketConn.WaitReadFrom()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.netPacketConn.resultCh
|
|
||||||
go c.pipeWaitReadFrom()
|
|
||||||
|
|
||||||
return c.WaitReadFrom()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) pipeWaitReadFrom() {
|
|
||||||
data, put, addr, err := c.enhancePacketConn.WaitReadFrom()
|
|
||||||
result := &enhanceReadResult{}
|
|
||||||
result.data = data
|
|
||||||
result.put = put
|
|
||||||
result.addr = addr
|
|
||||||
result.err = err
|
|
||||||
c.netPacketConn.resultCh <- result
|
|
||||||
}
|
|
@ -1,177 +0,0 @@
|
|||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SingPacketConn struct {
|
|
||||||
*NetPacketConn
|
|
||||||
singPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ packet.SingPacketConn = (*SingPacketConn)(nil)
|
|
||||||
|
|
||||||
func NewSingPacketConn(pc packet.SingPacketConn) packet.SingPacketConn {
|
|
||||||
return NewNetPacketConn(pc).(packet.SingPacketConn)
|
|
||||||
}
|
|
||||||
|
|
||||||
type EnhanceSingPacketConn struct {
|
|
||||||
*EnhancePacketConn
|
|
||||||
singPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEnhanceSingPacketConn(pc packet.EnhanceSingPacketConn) packet.EnhanceSingPacketConn {
|
|
||||||
return NewNetPacketConn(pc).(packet.EnhanceSingPacketConn)
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ packet.EnhanceSingPacketConn = (*EnhanceSingPacketConn)(nil)
|
|
||||||
|
|
||||||
type singReadResult struct {
|
|
||||||
buffer *buf.Buffer
|
|
||||||
destination M.Socksaddr
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type singPacketConn struct {
|
|
||||||
netPacketConn *NetPacketConn
|
|
||||||
singPacketConn packet.SingPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
|
||||||
FOR:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case result := <-c.netPacketConn.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
if result, ok := result.(*singReadResult); ok {
|
|
||||||
destination = result.destination
|
|
||||||
err = result.err
|
|
||||||
n, _ := buffer.Write(result.buffer.Bytes())
|
|
||||||
result.buffer.Advance(n)
|
|
||||||
if result.buffer.IsEmpty() {
|
|
||||||
result.buffer.Release()
|
|
||||||
}
|
|
||||||
c.netPacketConn.resultCh <- nil // finish cache read
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.netPacketConn.resultCh <- result // another type of read
|
|
||||||
runtime.Gosched() // allowing other goroutines to run
|
|
||||||
continue FOR
|
|
||||||
} else {
|
|
||||||
c.netPacketConn.resultCh <- nil
|
|
||||||
break FOR
|
|
||||||
}
|
|
||||||
case <-c.netPacketConn.pipeDeadline.wait():
|
|
||||||
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.netPacketConn.disablePipe.Load() {
|
|
||||||
return c.singPacketConn.ReadPacket(buffer)
|
|
||||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
|
||||||
c.netPacketConn.inRead.Store(true)
|
|
||||||
defer c.netPacketConn.inRead.Store(false)
|
|
||||||
destination, err = c.singPacketConn.ReadPacket(buffer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.netPacketConn.resultCh
|
|
||||||
go c.pipeReadPacket(buffer.FreeLen())
|
|
||||||
|
|
||||||
return c.ReadPacket(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketConn) pipeReadPacket(pLen int) {
|
|
||||||
buffer := buf.NewSize(pLen)
|
|
||||||
destination, err := c.singPacketConn.ReadPacket(buffer)
|
|
||||||
result := &singReadResult{}
|
|
||||||
result.destination = destination
|
|
||||||
result.err = err
|
|
||||||
c.netPacketConn.resultCh <- result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
||||||
return c.singPacketConn.WritePacket(buffer, destination)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketConn) CreateReadWaiter() (N.PacketReadWaiter, bool) {
|
|
||||||
prw, isReadWaiter := bufio.CreatePacketReadWaiter(c.singPacketConn)
|
|
||||||
if isReadWaiter {
|
|
||||||
return &singPacketReadWaiter{
|
|
||||||
netPacketConn: c.netPacketConn,
|
|
||||||
packetReadWaiter: prw,
|
|
||||||
}, true
|
|
||||||
}
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.PacketReadWaiter = (*singPacketReadWaiter)(nil)
|
|
||||||
|
|
||||||
type singPacketReadWaiter struct {
|
|
||||||
netPacketConn *NetPacketConn
|
|
||||||
packetReadWaiter N.PacketReadWaiter
|
|
||||||
}
|
|
||||||
|
|
||||||
type singWaitReadResult singReadResult
|
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) InitializeReadWaiter(newBuffer func() *buf.Buffer) {
|
|
||||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) WaitReadPacket() (destination M.Socksaddr, err error) {
|
|
||||||
FOR:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case result := <-c.netPacketConn.resultCh:
|
|
||||||
if result != nil {
|
|
||||||
if result, ok := result.(*singWaitReadResult); ok {
|
|
||||||
destination = result.destination
|
|
||||||
err = result.err
|
|
||||||
c.netPacketConn.resultCh <- nil // finish cache read
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.netPacketConn.resultCh <- result // another type of read
|
|
||||||
runtime.Gosched() // allowing other goroutines to run
|
|
||||||
continue FOR
|
|
||||||
} else {
|
|
||||||
c.netPacketConn.resultCh <- nil
|
|
||||||
break FOR
|
|
||||||
}
|
|
||||||
case <-c.netPacketConn.pipeDeadline.wait():
|
|
||||||
return M.Socksaddr{}, os.ErrDeadlineExceeded
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.netPacketConn.disablePipe.Load() {
|
|
||||||
return c.packetReadWaiter.WaitReadPacket()
|
|
||||||
} else if c.netPacketConn.deadline.Load().IsZero() {
|
|
||||||
c.netPacketConn.inRead.Store(true)
|
|
||||||
defer c.netPacketConn.inRead.Store(false)
|
|
||||||
destination, err = c.packetReadWaiter.WaitReadPacket()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
<-c.netPacketConn.resultCh
|
|
||||||
go c.pipeWaitReadPacket()
|
|
||||||
|
|
||||||
return c.WaitReadPacket()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) pipeWaitReadPacket() {
|
|
||||||
destination, err := c.packetReadWaiter.WaitReadPacket()
|
|
||||||
result := &singWaitReadResult{}
|
|
||||||
result.destination = destination
|
|
||||||
result.err = err
|
|
||||||
c.netPacketConn.resultCh <- result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *singPacketReadWaiter) Upstream() any {
|
|
||||||
return c.packetReadWaiter
|
|
||||||
}
|
|
@ -1,84 +0,0 @@
|
|||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package deadline
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// pipeDeadline is an abstraction for handling timeouts.
|
|
||||||
type pipeDeadline struct {
|
|
||||||
mu sync.Mutex // Guards timer and cancel
|
|
||||||
timer *time.Timer
|
|
||||||
cancel chan struct{} // Must be non-nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func makePipeDeadline() pipeDeadline {
|
|
||||||
return pipeDeadline{cancel: make(chan struct{})}
|
|
||||||
}
|
|
||||||
|
|
||||||
// set sets the point in time when the deadline will time out.
|
|
||||||
// A timeout event is signaled by closing the channel returned by waiter.
|
|
||||||
// Once a timeout has occurred, the deadline can be refreshed by specifying a
|
|
||||||
// t value in the future.
|
|
||||||
//
|
|
||||||
// A zero value for t prevents timeout.
|
|
||||||
func (d *pipeDeadline) set(t time.Time) {
|
|
||||||
d.mu.Lock()
|
|
||||||
defer d.mu.Unlock()
|
|
||||||
|
|
||||||
if d.timer != nil && !d.timer.Stop() {
|
|
||||||
<-d.cancel // Wait for the timer callback to finish and close cancel
|
|
||||||
}
|
|
||||||
d.timer = nil
|
|
||||||
|
|
||||||
// Time is zero, then there is no deadline.
|
|
||||||
closed := isClosedChan(d.cancel)
|
|
||||||
if t.IsZero() {
|
|
||||||
if closed {
|
|
||||||
d.cancel = make(chan struct{})
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Time in the future, setup a timer to cancel in the future.
|
|
||||||
if dur := time.Until(t); dur > 0 {
|
|
||||||
if closed {
|
|
||||||
d.cancel = make(chan struct{})
|
|
||||||
}
|
|
||||||
d.timer = time.AfterFunc(dur, func() {
|
|
||||||
close(d.cancel)
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Time in the past, so close immediately.
|
|
||||||
if !closed {
|
|
||||||
close(d.cancel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// wait returns a channel that is closed when the deadline is exceeded.
|
|
||||||
func (d *pipeDeadline) wait() chan struct{} {
|
|
||||||
d.mu.Lock()
|
|
||||||
defer d.mu.Unlock()
|
|
||||||
return d.cancel
|
|
||||||
}
|
|
||||||
|
|
||||||
func isClosedChan(c <-chan struct{}) bool {
|
|
||||||
select {
|
|
||||||
case <-c:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeFilledChan() chan struct{} {
|
|
||||||
ch := make(chan struct{}, 1)
|
|
||||||
ch <- struct{}{}
|
|
||||||
return ch
|
|
||||||
}
|
|
@ -1,18 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/common/net/deadline"
|
|
||||||
"github.com/Dreamacro/clash/common/net/packet"
|
|
||||||
)
|
|
||||||
|
|
||||||
type EnhancePacketConn = packet.EnhancePacketConn
|
|
||||||
type WaitReadFrom = packet.WaitReadFrom
|
|
||||||
|
|
||||||
var NewEnhancePacketConn = packet.NewEnhancePacketConn
|
|
||||||
var NewThreadSafePacketConn = packet.NewThreadSafePacketConn
|
|
||||||
var NewRefPacketConn = packet.NewRefPacketConn
|
|
||||||
|
|
||||||
var NewDeadlineNetPacketConn = deadline.NewNetPacketConn
|
|
||||||
var NewDeadlineEnhancePacketConn = deadline.NewEnhancePacketConn
|
|
||||||
var NewDeadlineSingPacketConn = deadline.NewSingPacketConn
|
|
||||||
var NewDeadlineEnhanceSingPacketConn = deadline.NewEnhanceSingPacketConn
|
|
@ -1,77 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
)
|
|
||||||
|
|
||||||
type WaitReadFrom interface {
|
|
||||||
WaitReadFrom() (data []byte, put func(), addr net.Addr, err error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type EnhancePacketConn interface {
|
|
||||||
net.PacketConn
|
|
||||||
WaitReadFrom
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEnhancePacketConn(pc net.PacketConn) EnhancePacketConn {
|
|
||||||
if udpConn, isUDPConn := pc.(*net.UDPConn); isUDPConn {
|
|
||||||
return &enhanceUDPConn{UDPConn: udpConn}
|
|
||||||
}
|
|
||||||
if enhancePC, isEnhancePC := pc.(EnhancePacketConn); isEnhancePC {
|
|
||||||
return enhancePC
|
|
||||||
}
|
|
||||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
|
||||||
return newEnhanceSingPacketConn(singPC)
|
|
||||||
}
|
|
||||||
return &enhancePacketConn{PacketConn: pc}
|
|
||||||
}
|
|
||||||
|
|
||||||
type enhancePacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
return waitReadFrom(c.PacketConn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) Upstream() any {
|
|
||||||
return c.PacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhancePacketConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceUDPConn) Upstream() any {
|
|
||||||
return c.UDPConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceUDPConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceUDPConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func waitReadFrom(pc net.PacketConn) (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
readBuf := pool.Get(pool.UDPBufferSize)
|
|
||||||
put = func() {
|
|
||||||
_ = pool.Put(readBuf)
|
|
||||||
}
|
|
||||||
var readN int
|
|
||||||
readN, addr, err = pc.ReadFrom(readBuf)
|
|
||||||
if readN > 0 {
|
|
||||||
data = readBuf[:readN]
|
|
||||||
} else {
|
|
||||||
put()
|
|
||||||
put = nil
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,65 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
)
|
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
|
||||||
*net.UDPConn
|
|
||||||
rawConn syscall.RawConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
if c.rawConn == nil {
|
|
||||||
c.rawConn, _ = c.UDPConn.SyscallConn()
|
|
||||||
}
|
|
||||||
var readErr error
|
|
||||||
err = c.rawConn.Read(func(fd uintptr) (done bool) {
|
|
||||||
readBuf := pool.Get(pool.UDPBufferSize)
|
|
||||||
put = func() {
|
|
||||||
_ = pool.Put(readBuf)
|
|
||||||
}
|
|
||||||
var readFrom syscall.Sockaddr
|
|
||||||
var readN int
|
|
||||||
readN, _, _, readFrom, readErr = syscall.Recvmsg(int(fd), readBuf, nil, 0)
|
|
||||||
if readN > 0 {
|
|
||||||
data = readBuf[:readN]
|
|
||||||
} else {
|
|
||||||
put()
|
|
||||||
put = nil
|
|
||||||
data = nil
|
|
||||||
}
|
|
||||||
if readErr == syscall.EAGAIN {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if readFrom != nil {
|
|
||||||
switch from := readFrom.(type) {
|
|
||||||
case *syscall.SockaddrInet4:
|
|
||||||
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 4 bytes
|
|
||||||
addr = &net.UDPAddr{IP: ip[:], Port: from.Port}
|
|
||||||
case *syscall.SockaddrInet6:
|
|
||||||
ip := from.Addr // copy from.Addr; ip escapes, so this line allocates 16 bytes
|
|
||||||
addr = &net.UDPAddr{IP: ip[:], Port: from.Port, Zone: strconv.FormatInt(int64(from.ZoneId), 10)}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// udp should not convert readN == 0 to io.EOF
|
|
||||||
//if readN == 0 {
|
|
||||||
// readErr = io.EOF
|
|
||||||
//}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if readErr != nil {
|
|
||||||
err = readErr
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,79 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SingPacketConn = N.NetPacketConn
|
|
||||||
|
|
||||||
type EnhanceSingPacketConn interface {
|
|
||||||
SingPacketConn
|
|
||||||
EnhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
type enhanceSingPacketConn struct {
|
|
||||||
SingPacketConn
|
|
||||||
packetReadWaiter N.PacketReadWaiter
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceSingPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
var buff *buf.Buffer
|
|
||||||
var dest M.Socksaddr
|
|
||||||
newBuffer := func() *buf.Buffer {
|
|
||||||
buff = buf.NewPacket() // do not use stack buffer
|
|
||||||
return buff
|
|
||||||
}
|
|
||||||
if c.packetReadWaiter != nil {
|
|
||||||
c.packetReadWaiter.InitializeReadWaiter(newBuffer)
|
|
||||||
defer c.packetReadWaiter.InitializeReadWaiter(nil)
|
|
||||||
dest, err = c.packetReadWaiter.WaitReadPacket()
|
|
||||||
} else {
|
|
||||||
dest, err = c.SingPacketConn.ReadPacket(newBuffer())
|
|
||||||
}
|
|
||||||
if dest.IsFqdn() {
|
|
||||||
addr = dest
|
|
||||||
} else {
|
|
||||||
addr = dest.UDPAddr()
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
if buff != nil {
|
|
||||||
buff.Release()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if buff == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if buff.IsEmpty() {
|
|
||||||
buff.Release()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
data = buff.Bytes()
|
|
||||||
put = buff.Release
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceSingPacketConn) Upstream() any {
|
|
||||||
return c.SingPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceSingPacketConn) WriterReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceSingPacketConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func newEnhanceSingPacketConn(conn SingPacketConn) *enhanceSingPacketConn {
|
|
||||||
epc := &enhanceSingPacketConn{SingPacketConn: conn}
|
|
||||||
if readWaiter, isReadWaiter := bufio.CreatePacketReadWaiter(conn); isReadWaiter {
|
|
||||||
epc.packetReadWaiter = readWaiter
|
|
||||||
}
|
|
||||||
return epc
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
|
|
||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
type enhanceUDPConn struct {
|
|
||||||
*net.UDPConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *enhanceUDPConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
return waitReadFrom(c.UDPConn)
|
|
||||||
}
|
|
@ -1,75 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type refPacketConn struct {
|
|
||||||
pc EnhancePacketConn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.WaitReadFrom()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.ReadFrom(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.WriteTo(p, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.pc.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) Upstream() any {
|
|
||||||
return c.pc
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) ReaderReplaceable() bool { // Relay() will handle reference
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refPacketConn) WriterReplaceable() bool { // Relay() will handle reference
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefPacketConn(pc net.PacketConn, ref any) EnhancePacketConn {
|
|
||||||
rPC := &refPacketConn{pc: NewEnhancePacketConn(pc), ref: ref}
|
|
||||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
|
||||||
return &refSingPacketConn{
|
|
||||||
refPacketConn: rPC,
|
|
||||||
singPacketConn: singPC,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return rPC
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type refSingPacketConn struct {
|
|
||||||
*refPacketConn
|
|
||||||
singPacketConn SingPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.NetPacketConn = (*refSingPacketConn)(nil)
|
|
||||||
|
|
||||||
func (c *refSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.singPacketConn.WritePacket(buffer, destination)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.singPacketConn.ReadPacket(buffer)
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type threadSafePacketConn struct {
|
|
||||||
EnhancePacketConn
|
|
||||||
access sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
c.access.Lock()
|
|
||||||
defer c.access.Unlock()
|
|
||||||
return c.EnhancePacketConn.WriteTo(b, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *threadSafePacketConn) Upstream() any {
|
|
||||||
return c.EnhancePacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *threadSafePacketConn) ReaderReplaceable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewThreadSafePacketConn(pc net.PacketConn) EnhancePacketConn {
|
|
||||||
tsPC := &threadSafePacketConn{EnhancePacketConn: NewEnhancePacketConn(pc)}
|
|
||||||
if singPC, isSingPC := pc.(SingPacketConn); isSingPC {
|
|
||||||
return &threadSafeSingPacketConn{
|
|
||||||
threadSafePacketConn: tsPC,
|
|
||||||
singPacketConn: singPC,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tsPC
|
|
||||||
}
|
|
@ -1,24 +0,0 @@
|
|||||||
package packet
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type threadSafeSingPacketConn struct {
|
|
||||||
*threadSafePacketConn
|
|
||||||
singPacketConn SingPacketConn
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.NetPacketConn = (*threadSafeSingPacketConn)(nil)
|
|
||||||
|
|
||||||
func (c *threadSafeSingPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
||||||
c.access.Lock()
|
|
||||||
defer c.access.Unlock()
|
|
||||||
return c.singPacketConn.WritePacket(buffer, destination)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *threadSafeSingPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
|
||||||
return c.singPacketConn.ReadPacket(buffer)
|
|
||||||
}
|
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,26 +55,50 @@ func (c *refConn) Upstream() any {
|
|||||||
return c.conn
|
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 {
|
||||||
|
pc net.PacketConn
|
||||||
|
ref any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.ReadFrom(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.WriteTo(p, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) Close() error {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) LocalAddr() net.Addr {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.LocalAddr()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.SetDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.SetReadDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *refPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
defer runtime.KeepAlive(pc.ref)
|
||||||
|
return pc.pc.SetWriteDeadline(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRefPacketConn(pc net.PacketConn, ref any) net.PacketConn {
|
||||||
|
return &refPacketConn{pc: pc, ref: ref}
|
||||||
}
|
}
|
||||||
|
@ -3,11 +3,8 @@ package net
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
"github.com/sagernet/sing/common/bufio/deadline"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
"github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -19,22 +16,7 @@ type ExtendedConn = network.ExtendedConn
|
|||||||
type ExtendedWriter = network.ExtendedWriter
|
type ExtendedWriter = network.ExtendedWriter
|
||||||
type ExtendedReader = network.ExtendedReader
|
type ExtendedReader = network.ExtendedReader
|
||||||
|
|
||||||
func NewDeadlineConn(conn net.Conn) ExtendedConn {
|
|
||||||
return deadline.NewFallbackConn(conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
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.
|
// Relay copies between left and right bidirectionally.
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
defer runtime.KeepAlive(leftConn)
|
|
||||||
defer runtime.KeepAlive(rightConn)
|
|
||||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
||||||
}
|
}
|
||||||
|
@ -4,11 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var KeepAliveInterval = 15 * time.Second
|
|
||||||
|
|
||||||
func SplitNetworkType(s string) (string, string, error) {
|
func SplitNetworkType(s string) (string, string, error) {
|
||||||
var (
|
var (
|
||||||
shecme string
|
shecme string
|
||||||
@ -47,10 +44,3 @@ func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
|||||||
host, port, err = net.SplitHostPort(temp)
|
host, port, err = net.SplitHostPort(temp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func TCPKeepAlive(c net.Conn) {
|
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
|
||||||
_ = tcp.SetKeepAlive(true)
|
|
||||||
_ = tcp.SetKeepAlivePeriod(KeepAliveInterval)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
||||||
if certificate == "" && privateKey == "" {
|
if certificate == "" || privateKey == "" {
|
||||||
return newRandomTLSKeyPair()
|
return newRandomTLSKeyPair()
|
||||||
}
|
}
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
||||||
|
@ -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()
|
||||||
}
|
}
|
||||||
|
@ -47,7 +47,6 @@ func (p *Picker[T]) Wait() T {
|
|||||||
p.wg.Wait()
|
p.wg.Wait()
|
||||||
if p.cancel != nil {
|
if p.cancel != nil {
|
||||||
p.cancel()
|
p.cancel()
|
||||||
p.cancel = nil
|
|
||||||
}
|
}
|
||||||
return p.result
|
return p.result
|
||||||
}
|
}
|
||||||
@ -70,7 +69,6 @@ func (p *Picker[T]) Go(f func() (T, error)) {
|
|||||||
p.result = ret
|
p.result = ret
|
||||||
if p.cancel != nil {
|
if p.cancel != nil {
|
||||||
p.cancel()
|
p.cancel()
|
||||||
p.cancel = nil
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
@ -80,13 +78,3 @@ func (p *Picker[T]) Go(f func() (T, error)) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close cancels the picker context and releases resources associated with it.
|
|
||||||
// If Wait has been called, then there is no need to call Close.
|
|
||||||
func (p *Picker[T]) Close() error {
|
|
||||||
if p.cancel != nil {
|
|
||||||
p.cancel()
|
|
||||||
p.cancel = nil
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
@ -5,7 +5,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -16,7 +15,7 @@ func sleepAndSend[T any](ctx context.Context, delay int, input T) func() (T, err
|
|||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
return input, nil
|
return input, nil
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return lo.Empty[T](), ctx.Err()
|
return getZero[T](), ctx.Err()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -36,6 +35,11 @@ func TestPicker_Timeout(t *testing.T) {
|
|||||||
picker.Go(sleepAndSend(ctx, 20, 1))
|
picker.Go(sleepAndSend(ctx, 20, 1))
|
||||||
|
|
||||||
number := picker.Wait()
|
number := picker.Wait()
|
||||||
assert.Equal(t, number, lo.Empty[int]())
|
assert.Equal(t, number, getZero[int]())
|
||||||
assert.NotNil(t, picker.Error())
|
assert.NotNil(t, picker.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
@ -32,32 +32,23 @@ func NewAllocator() *Allocator {
|
|||||||
|
|
||||||
// Get a []byte from pool with most appropriate cap
|
// Get a []byte from pool with most appropriate cap
|
||||||
func (alloc *Allocator) Get(size int) []byte {
|
func (alloc *Allocator) Get(size int) []byte {
|
||||||
switch {
|
if size <= 0 || size > 65536 {
|
||||||
case size < 0:
|
|
||||||
panic("alloc.Get: len out of range")
|
|
||||||
case size == 0:
|
|
||||||
return nil
|
return nil
|
||||||
case size > 65536:
|
}
|
||||||
return make([]byte, size)
|
|
||||||
default:
|
|
||||||
bits := msb(size)
|
bits := msb(size)
|
||||||
if size == 1<<bits {
|
if size == 1<<bits {
|
||||||
return alloc.buffers[bits].Get().([]byte)[:size]
|
return alloc.buffers[bits].Get().([]byte)[:size]
|
||||||
}
|
}
|
||||||
|
|
||||||
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
return alloc.buffers[bits+1].Get().([]byte)[:size]
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Put returns a []byte to pool for future use,
|
// Put returns a []byte to pool for future use,
|
||||||
// which the cap must be exactly 2^n
|
// which the cap must be exactly 2^n
|
||||||
func (alloc *Allocator) Put(buf []byte) error {
|
func (alloc *Allocator) Put(buf []byte) error {
|
||||||
if cap(buf) == 0 || cap(buf) > 65536 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
bits := msb(cap(buf))
|
bits := msb(cap(buf))
|
||||||
if cap(buf) != 1<<bits {
|
if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1<<bits {
|
||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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) {
|
||||||
@ -19,17 +19,17 @@ func TestAllocGet(t *testing.T) {
|
|||||||
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
assert.Equal(t, 1024, cap(alloc.Get(1023)))
|
||||||
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
assert.Equal(t, 1024, len(alloc.Get(1024)))
|
||||||
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
assert.Equal(t, 65536, len(alloc.Get(65536)))
|
||||||
assert.Equal(t, 65537, len(alloc.Get(65537)))
|
assert.Nil(t, alloc.Get(65537))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAllocPut(t *testing.T) {
|
func TestAllocPut(t *testing.T) {
|
||||||
alloc := NewAllocator()
|
alloc := NewAllocator()
|
||||||
assert.Nil(t, alloc.Put(nil), "put nil misbehavior")
|
assert.NotNil(t, alloc.Put(nil), "put nil misbehavior")
|
||||||
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
|
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
|
||||||
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
|
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
|
||||||
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
|
||||||
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
|
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
|
||||||
assert.Nil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
assert.NotNil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAllocPutThenGet(t *testing.T) {
|
func TestAllocPutThenGet(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)
|
||||||
}
|
}
|
||||||
|
@ -2,8 +2,6 @@ package queue
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/samber/lo"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Queue is a simple concurrent safe queue
|
// Queue is a simple concurrent safe queue
|
||||||
@ -26,7 +24,7 @@ func (q *Queue[T]) Put(items ...T) {
|
|||||||
// Pop returns the head of items.
|
// Pop returns the head of items.
|
||||||
func (q *Queue[T]) Pop() T {
|
func (q *Queue[T]) Pop() T {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return lo.Empty[T]()
|
return GetZero[T]()
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.Lock()
|
q.lock.Lock()
|
||||||
@ -39,7 +37,7 @@ func (q *Queue[T]) Pop() T {
|
|||||||
// Last returns the last of item.
|
// Last returns the last of item.
|
||||||
func (q *Queue[T]) Last() T {
|
func (q *Queue[T]) Last() T {
|
||||||
if len(q.items) == 0 {
|
if len(q.items) == 0 {
|
||||||
return lo.Empty[T]()
|
return GetZero[T]()
|
||||||
}
|
}
|
||||||
|
|
||||||
q.lock.RLock()
|
q.lock.RLock()
|
||||||
@ -71,3 +69,8 @@ func New[T any](hint int64) *Queue[T] {
|
|||||||
items: make([]T, 0, hint),
|
items: make([]T, 0, hint),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetZero[T any]() T {
|
||||||
|
var result T
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
@ -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()
|
||||||
}()
|
}()
|
||||||
|
@ -96,11 +96,6 @@ func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
|||||||
return d.decodeFloat(name, data, val)
|
return d.decodeFloat(name, data, val)
|
||||||
}
|
}
|
||||||
switch kind {
|
switch kind {
|
||||||
case reflect.Pointer:
|
|
||||||
if val.IsNil() {
|
|
||||||
val.Set(reflect.New(val.Type().Elem()))
|
|
||||||
}
|
|
||||||
return d.decode(name, data, val.Elem())
|
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
return d.decodeString(name, data, val)
|
return d.decodeString(name, data, val)
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
@ -287,9 +282,6 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
valSlice := val
|
valSlice := val
|
||||||
// make a new slice with cap(val)==cap(dataVal)
|
|
||||||
// the caller can determine whether the original configuration contains this item by judging whether the value is nil.
|
|
||||||
valSlice = reflect.MakeSlice(valType, 0, dataVal.Len())
|
|
||||||
for i := 0; i < dataVal.Len(); i++ {
|
for i := 0; i < dataVal.Len(); i++ {
|
||||||
currentData := dataVal.Index(i).Interface()
|
currentData := dataVal.Index(i).Interface()
|
||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
|
@ -1,17 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"hash/maphash"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
var globalSeed = maphash.MakeSeed()
|
|
||||||
|
|
||||||
func GlobalID(material string) (id [8]byte) {
|
|
||||||
*(*uint64)(unsafe.Pointer(&id[0])) = maphash.String(globalSeed, material)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func MapHash(material string) uint64 {
|
|
||||||
return maphash.String(globalSeed, material)
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
func MustOK[T any](result T, ok bool) T {
|
|
||||||
if ok {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
panic("operation failed")
|
|
||||||
}
|
|
@ -9,36 +9,36 @@ type Range[T constraints.Ordered] struct {
|
|||||||
end T
|
end T
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRange[T constraints.Ordered](start, end T) Range[T] {
|
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
||||||
if start > end {
|
if start > end {
|
||||||
return Range[T]{
|
return &Range[T]{
|
||||||
start: end,
|
start: end,
|
||||||
end: start,
|
end: start,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Range[T]{
|
return &Range[T]{
|
||||||
start: start,
|
start: start,
|
||||||
end: end,
|
end: end,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Range[T]) Contains(t T) bool {
|
func (r *Range[T]) Contains(t T) bool {
|
||||||
return t >= r.start && t <= r.end
|
return t >= r.start && t <= r.end
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Range[T]) LeftContains(t T) bool {
|
func (r *Range[T]) LeftContains(t T) bool {
|
||||||
return t >= r.start && t < r.end
|
return t >= r.start && t < r.end
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Range[T]) RightContains(t T) bool {
|
func (r *Range[T]) RightContains(t T) bool {
|
||||||
return t > r.start && t <= r.end
|
return t > r.start && t <= r.end
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Range[T]) Start() T {
|
func (r *Range[T]) Start() T {
|
||||||
return r.start
|
return r.start
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Range[T]) End() T {
|
func (r *Range[T]) End() T {
|
||||||
return r.end
|
return r.end
|
||||||
}
|
}
|
||||||
|
@ -1,77 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"golang.org/x/exp/constraints"
|
|
||||||
)
|
|
||||||
|
|
||||||
type IntRanges[T constraints.Integer] []Range[T]
|
|
||||||
|
|
||||||
var errIntRanges = errors.New("intRanges error")
|
|
||||||
|
|
||||||
func NewIntRanges[T constraints.Integer](expected string) (IntRanges[T], error) {
|
|
||||||
// example: 200 or 200/302 or 200-400 or 200/204/401-429/501-503
|
|
||||||
expected = strings.TrimSpace(expected)
|
|
||||||
if len(expected) == 0 || expected == "*" {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
list := strings.Split(expected, "/")
|
|
||||||
if len(list) > 28 {
|
|
||||||
return nil, fmt.Errorf("%w, too many ranges to use, maximum support 28 ranges", errIntRanges)
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewIntRangesFromList[T](list)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewIntRangesFromList[T constraints.Integer](list []string) (IntRanges[T], error) {
|
|
||||||
var ranges IntRanges[T]
|
|
||||||
for _, s := range list {
|
|
||||||
if s == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
status := strings.Split(s, "-")
|
|
||||||
statusLen := len(status)
|
|
||||||
if statusLen > 2 {
|
|
||||||
return nil, errIntRanges
|
|
||||||
}
|
|
||||||
|
|
||||||
start, err := strconv.ParseInt(strings.Trim(status[0], "[ ]"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errIntRanges
|
|
||||||
}
|
|
||||||
|
|
||||||
switch statusLen {
|
|
||||||
case 1:
|
|
||||||
ranges = append(ranges, NewRange(T(start), T(start)))
|
|
||||||
case 2:
|
|
||||||
end, err := strconv.ParseUint(strings.Trim(status[1], "[ ]"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errIntRanges
|
|
||||||
}
|
|
||||||
|
|
||||||
ranges = append(ranges, NewRange(T(start), T(end)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ranges, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ranges IntRanges[T]) Check(status T) bool {
|
|
||||||
if len(ranges) == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, segment := range ranges {
|
|
||||||
if segment.Contains(status) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
@ -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,21 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import "unsafe"
|
|
||||||
|
|
||||||
// ImmutableBytesFromString is equivalent to []byte(s), except that it uses the
|
|
||||||
// same memory backing s instead of making a heap-allocated copy. This is only
|
|
||||||
// valid if the returned slice is never mutated.
|
|
||||||
func ImmutableBytesFromString(s string) []byte {
|
|
||||||
b := unsafe.StringData(s)
|
|
||||||
return unsafe.Slice(b, len(s))
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringFromImmutableBytes is equivalent to string(bs), except that it uses
|
|
||||||
// the same memory backing bs instead of making a heap-allocated copy. This is
|
|
||||||
// only valid if bs is never mutated after StringFromImmutableBytes returns.
|
|
||||||
func StringFromImmutableBytes(bs []byte) string {
|
|
||||||
if len(bs) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return unsafe.String(&bs[0], len(bs))
|
|
||||||
}
|
|
@ -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,7 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/puzpuzpuz/xsync/v2"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Authenticator interface {
|
type Authenticator interface {
|
||||||
@ -15,7 +15,7 @@ type AuthUser struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type inMemoryAuthenticator struct {
|
type inMemoryAuthenticator struct {
|
||||||
storage *xsync.MapOf[string, string]
|
storage *sync.Map
|
||||||
usernames []string
|
usernames []string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -31,13 +31,13 @@ func NewAuthenticator(users []AuthUser) Authenticator {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
au := &inMemoryAuthenticator{storage: xsync.NewMapOf[string]()}
|
au := &inMemoryAuthenticator{storage: &sync.Map{}}
|
||||||
for _, user := range users {
|
for _, user := range users {
|
||||||
au.storage.Store(user.User, user.Pass)
|
au.storage.Store(user.User, user.Pass)
|
||||||
}
|
}
|
||||||
usernames := make([]string, 0, len(users))
|
usernames := make([]string, 0, len(users))
|
||||||
au.storage.Range(func(key string, value string) bool {
|
au.storage.Range(func(key, value any) bool {
|
||||||
usernames = append(usernames, key)
|
usernames = append(usernames, key.(string))
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
au.usernames = usernames
|
au.usernames = usernames
|
||||||
|
@ -1,143 +0,0 @@
|
|||||||
package ca
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
var trustCerts []*x509.Certificate
|
|
||||||
var globalCertPool *x509.CertPool
|
|
||||||
var mutex sync.RWMutex
|
|
||||||
var errNotMatch = errors.New("certificate fingerprints do not match")
|
|
||||||
|
|
||||||
func AddCertificate(certificate string) error {
|
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
if certificate == "" {
|
|
||||||
return fmt.Errorf("certificate is empty")
|
|
||||||
}
|
|
||||||
if cert, err := x509.ParseCertificate([]byte(certificate)); err == nil {
|
|
||||||
trustCerts = append(trustCerts, cert)
|
|
||||||
return nil
|
|
||||||
} else {
|
|
||||||
return fmt.Errorf("add certificate failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func initializeCertPool() {
|
|
||||||
var err error
|
|
||||||
globalCertPool, err = x509.SystemCertPool()
|
|
||||||
if err != nil {
|
|
||||||
globalCertPool = x509.NewCertPool()
|
|
||||||
}
|
|
||||||
for _, cert := range trustCerts {
|
|
||||||
globalCertPool.AddCert(cert)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResetCertificate() {
|
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
trustCerts = nil
|
|
||||||
initializeCertPool()
|
|
||||||
}
|
|
||||||
|
|
||||||
func getCertPool() *x509.CertPool {
|
|
||||||
if len(trustCerts) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if globalCertPool == nil {
|
|
||||||
mutex.Lock()
|
|
||||||
defer mutex.Unlock()
|
|
||||||
if globalCertPool != nil {
|
|
||||||
return globalCertPool
|
|
||||||
}
|
|
||||||
initializeCertPool()
|
|
||||||
}
|
|
||||||
return globalCertPool
|
|
||||||
}
|
|
||||||
|
|
||||||
func verifyFingerprint(fingerprint *[32]byte) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
|
||||||
return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
|
||||||
// ssl pining
|
|
||||||
for i := range rawCerts {
|
|
||||||
rawCert := rawCerts[i]
|
|
||||||
cert, err := x509.ParseCertificate(rawCert)
|
|
||||||
if err == nil {
|
|
||||||
hash := sha256.Sum256(cert.Raw)
|
|
||||||
if bytes.Equal(fingerprint[:], hash[:]) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return errNotMatch
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertFingerprint(fingerprint string) (*[32]byte, error) {
|
|
||||||
fingerprint = strings.TrimSpace(strings.Replace(fingerprint, ":", "", -1))
|
|
||||||
fpByte, err := hex.DecodeString(fingerprint)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(fpByte) != 32 {
|
|
||||||
return nil, fmt.Errorf("fingerprint string length error,need sha256 fingerprint")
|
|
||||||
}
|
|
||||||
return (*[32]byte)(fpByte), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTLSConfig specified fingerprint, customCA and customCAString
|
|
||||||
func GetTLSConfig(tlsConfig *tls.Config, fingerprint string, customCA string, customCAString string) (*tls.Config, error) {
|
|
||||||
if tlsConfig == nil {
|
|
||||||
tlsConfig = &tls.Config{}
|
|
||||||
}
|
|
||||||
var certificate []byte
|
|
||||||
var err error
|
|
||||||
if len(customCA) > 0 {
|
|
||||||
certificate, err = os.ReadFile(customCA)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("load ca error: %w", err)
|
|
||||||
}
|
|
||||||
} else if customCAString != "" {
|
|
||||||
certificate = []byte(customCAString)
|
|
||||||
}
|
|
||||||
if len(certificate) > 0 {
|
|
||||||
certPool := x509.NewCertPool()
|
|
||||||
if !certPool.AppendCertsFromPEM(certificate) {
|
|
||||||
return nil, fmt.Errorf("failed to parse certificate:\n\n %s", certificate)
|
|
||||||
}
|
|
||||||
tlsConfig.RootCAs = certPool
|
|
||||||
} else {
|
|
||||||
tlsConfig.RootCAs = getCertPool()
|
|
||||||
}
|
|
||||||
if len(fingerprint) > 0 {
|
|
||||||
var fingerprintBytes *[32]byte
|
|
||||||
fingerprintBytes, err = convertFingerprint(fingerprint)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
tlsConfig = GetGlobalTLSConfig(tlsConfig)
|
|
||||||
tlsConfig.VerifyPeerCertificate = verifyFingerprint(fingerprintBytes)
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
}
|
|
||||||
return tlsConfig, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSpecifiedFingerprintTLSConfig specified fingerprint
|
|
||||||
func GetSpecifiedFingerprintTLSConfig(tlsConfig *tls.Config, fingerprint string) (*tls.Config, error) {
|
|
||||||
return GetTLSConfig(tlsConfig, fingerprint, "", "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetGlobalTLSConfig(tlsConfig *tls.Config) *tls.Config {
|
|
||||||
tlsConfig, _ = GetTLSConfig(tlsConfig, "", "", "")
|
|
||||||
return tlsConfig
|
|
||||||
}
|
|
@ -1,51 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/iface"
|
|
||||||
)
|
|
||||||
|
|
||||||
func LookupLocalAddrFromIfaceName(ifaceName string, network string, destination netip.Addr, port int) (net.Addr, error) {
|
|
||||||
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var addr *netip.Prefix
|
|
||||||
switch network {
|
|
||||||
case "udp4", "tcp4":
|
|
||||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
|
||||||
default:
|
|
||||||
if destination.IsValid() {
|
|
||||||
if destination.Is4() || destination.Is4In6() {
|
|
||||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
|
||||||
} else {
|
|
||||||
addr, err = ifaceObj.PickIPv6Addr(destination)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
addr, err = ifaceObj.PickIPv4Addr(destination)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(network, "tcp") {
|
|
||||||
return &net.TCPAddr{
|
|
||||||
IP: addr.Addr().AsSlice(),
|
|
||||||
Port: port,
|
|
||||||
}, nil
|
|
||||||
} else if strings.HasPrefix(network, "udp") {
|
|
||||||
return &net.UDPAddr{
|
|
||||||
IP: addr.Addr().AsSlice(),
|
|
||||||
Port: port,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, iface.ErrAddrNotFound
|
|
||||||
}
|
|
@ -7,8 +7,52 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/iface"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func lookupLocalAddr(ifaceName string, network string, destination netip.Addr, port int) (net.Addr, error) {
|
||||||
|
ifaceObj, err := iface.ResolveInterface(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var addr *netip.Prefix
|
||||||
|
switch network {
|
||||||
|
case "udp4", "tcp4":
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
case "tcp6", "udp6":
|
||||||
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
|
default:
|
||||||
|
if destination.IsValid() {
|
||||||
|
if destination.Is4() {
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
} else {
|
||||||
|
addr, err = ifaceObj.PickIPv6Addr(destination)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addr, err = ifaceObj.PickIPv4Addr(destination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(network, "tcp") {
|
||||||
|
return &net.TCPAddr{
|
||||||
|
IP: addr.Addr().AsSlice(),
|
||||||
|
Port: port,
|
||||||
|
}, nil
|
||||||
|
} else if strings.HasPrefix(network, "udp") {
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: addr.Addr().AsSlice(),
|
||||||
|
Port: port,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, iface.ErrAddrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination netip.Addr) error {
|
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination netip.Addr) error {
|
||||||
if !destination.IsGlobalUnicast() {
|
if !destination.IsGlobalUnicast() {
|
||||||
return nil
|
return nil
|
||||||
@ -22,7 +66,7 @@ func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, des
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := LookupLocalAddrFromIfaceName(ifaceName, network, destination, int(local))
|
addr, err := lookupLocalAddr(ifaceName, network, destination, int(local))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -40,7 +84,7 @@ func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, add
|
|||||||
|
|
||||||
local, _ := strconv.ParseUint(port, 10, 16)
|
local, _ := strconv.ParseUint(port, 10, 16)
|
||||||
|
|
||||||
addr, err := LookupLocalAddrFromIfaceName(ifaceName, network, netip.Addr{}, int(local))
|
addr, err := lookupLocalAddr(ifaceName, network, netip.Addr{}, int(local))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user