Compare commits
115 Commits
Author | SHA1 | Date | |
---|---|---|---|
3610d3dd84 | |||
663017a775 | |||
05f0c1060b | |||
e03f1d0565 | |||
c1821e28d3 | |||
763929997b | |||
c8e2b30540 | |||
dd95d335d9 | |||
bf9eb000d2 | |||
0563abae13 | |||
3dbba5d8d2 | |||
a4d135ed21 | |||
af5bd0f65e | |||
8ed868b0f5 | |||
e7b8c9b9db | |||
ea8a5409ad | |||
39d524dc18 | |||
0be8fc387a | |||
985dc99b5d | |||
67905bcf7e | |||
b37e1fb2b9 | |||
22449da5d3 | |||
6ad2cde909 | |||
68cf94a866 | |||
5b49414b49 | |||
fe44a762c2 | |||
ce1014eae3 | |||
622b10d34d | |||
88b5741ad8 | |||
d11d28c358 | |||
03499fcea6 | |||
f788411154 | |||
3d2b4b1f3a | |||
5642d9c98e | |||
7a406b991e | |||
178c70a320 | |||
34eeb58bfa | |||
3d25f16b3b | |||
891a56fd99 | |||
ffbdcfcbfd | |||
72b9b829e9 | |||
8b3e42bf19 | |||
e92bea8401 | |||
53c83118bc | |||
6fe19944ad | |||
9f00907647 | |||
ace84ff548 | |||
160e630f03 | |||
13d19ff101 | |||
934babca85 | |||
95db646b3b | |||
f23d1d5d7c | |||
4334b45e82 | |||
ad1e09db55 | |||
2eb7f3ad2f | |||
9ffcc9e352 | |||
fe69ec7d6c | |||
045b67524c | |||
392572d684 | |||
3c07ba6b56 | |||
8c84c8b193 | |||
0321ddbb90 | |||
d74dd69329 | |||
7e85d5a954 | |||
da92601902 | |||
22458ad0be | |||
c8bc4386dd | |||
1e7cbd6358 | |||
30025c0241 | |||
7c50c068f5 | |||
ca4961a146 | |||
85f14f1c63 | |||
7115f7e61b | |||
62bc75af8a | |||
d763900b14 | |||
6acba9ab8f | |||
ca9f3bf8a9 | |||
c812363090 | |||
0a2701eef0 | |||
0d004bf6f3 | |||
450c608c83 | |||
053366c3e1 | |||
567fe74f10 | |||
cd62daccb0 | |||
29c775331a | |||
33d23dad6c | |||
42cf42fd8b | |||
46f7c5e565 | |||
6327cf7434 | |||
ca76e5cf0e | |||
9d72bf2a36 | |||
a3a50f9c7b | |||
abc8ed4df0 | |||
643f1ae970 | |||
21a56ea36b | |||
a98749eb16 | |||
571c34f140 | |||
008ee613ab | |||
5999b6262d | |||
05b4a326de | |||
f036e06f6f | |||
5a27ebd1b3 | |||
a8646082a3 | |||
400be9a905 | |||
0582c608b3 | |||
92d9d03f99 | |||
b6653dd9b5 | |||
d77ef6a525 | |||
4d9d8b28ec | |||
7973491625 | |||
edbc8ed972 | |||
bd123dddc6 | |||
ae493f1084 | |||
711b2bcf87 | |||
a45354fa08 |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
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: "
|
||||||
|
如果你可以自己 debug 并解决的话,提交 PR 吧
|
||||||
|
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||||
|
I have searched on the [issue tracker](……/) for a related issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经使用 dev 分支版本测试过,问题依旧存在
|
||||||
|
I have tested using the dev branch, and the issue still exists.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) 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
|
||||||
|
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 below.
|
||||||
|
"
|
||||||
|
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
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
6
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
|
||||||
|
contact_links:
|
||||||
|
- name: Get help in GitHub Discussions
|
||||||
|
url: https://github.com/Dreamacro/clash/discussions
|
||||||
|
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
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://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) 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
|
||||||
|
"
|
26
.github/release.sh
vendored
26
.github/release.sh
vendored
@ -1,26 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
FILENAMES=$(ls)
|
|
||||||
for FILENAME in $FILENAMES
|
|
||||||
do
|
|
||||||
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
|
||||||
gzip -S ".gz" $FILENAME
|
|
||||||
elif [[ $FILENAME =~ ".exe" ]];then
|
|
||||||
zip -m ${FILENAME%.*}.zip $FILENAME
|
|
||||||
else echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
FILENAMES=$(ls)
|
|
||||||
for FILENAME in $FILENAMES
|
|
||||||
do
|
|
||||||
if [[ $FILENAME =~ ".zip" ]];then
|
|
||||||
echo "rename $FILENAME"
|
|
||||||
mv $FILENAME ${FILENAME%.*}-${VERSION}.zip
|
|
||||||
elif [[ $FILENAME =~ ".gz" ]];then
|
|
||||||
echo "rename $FILENAME"
|
|
||||||
mv $FILENAME ${FILENAME%.*}-${VERSION}.gz
|
|
||||||
else
|
|
||||||
echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
35
.github/rename-cgo.sh
vendored
35
.github/rename-cgo.sh
vendored
@ -1,35 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
FILENAMES=$(ls)
|
|
||||||
for FILENAME in $FILENAMES
|
|
||||||
do
|
|
||||||
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
|
||||||
echo "rename darwin-10.16-arm64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-darwin-arm64-cgo
|
|
||||||
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
|
||||||
echo "rename darwin-10.16-amd64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-darwin-amd64-cgo
|
|
||||||
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
|
||||||
echo "rename windows 386 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-windows-386-cgo.exe
|
|
||||||
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
|
||||||
echo "rename windows amd64 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-windows-amd64-cgo.exe
|
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-5" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-5 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv5-cgo
|
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-6" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-6 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv6-cgo
|
|
||||||
elif [[ $FILENAME =~ "clash.meta-linux-arm-7" ]];then
|
|
||||||
echo "rename clash.meta-linux-arm-7 $FILENAME"
|
|
||||||
mv $FILENAME clash.meta-linux-armv7-cgo
|
|
||||||
elif [[ $FILENAME =~ "linux" ]];then
|
|
||||||
echo "rename linux $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
elif [[ $FILENAME =~ "android" ]];then
|
|
||||||
echo "rename android $FILENAME"
|
|
||||||
mv $FILENAME $FILENAME-cgo
|
|
||||||
else echo "skip $FILENAME"
|
|
||||||
fi
|
|
||||||
done
|
|
142
.github/workflows/build-windows-amd.yml
vendored
Normal file
142
.github/workflows/build-windows-amd.yml
vendored
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
name: Build-Windows
|
||||||
|
on: [push]
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: 1.18.x
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Go cache paths
|
||||||
|
id: go-cache-paths
|
||||||
|
run: |
|
||||||
|
echo "::set-output name=go-build::$(go env GOCACHE)"
|
||||||
|
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
||||||
|
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
${{ steps.go-cache-paths.outputs.go-mod }}
|
||||||
|
${{ steps.go-cache-paths.outputs.go-build }}
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v3
|
||||||
|
with:
|
||||||
|
python-version: '3.9'
|
||||||
|
architecture: 'x64'
|
||||||
|
|
||||||
|
- name: Get dependencies, run test
|
||||||
|
id: test
|
||||||
|
run: |
|
||||||
|
cmd /c mklink /J D:\python-amd64 $env:pythonLocation
|
||||||
|
|
||||||
|
echo "::set-output name=file_sha::$(git describe --tags --always)"
|
||||||
|
echo "::set-output name=file_date::$(Get-Date -Format 'yyyyMMdd')"
|
||||||
|
|
||||||
|
((Get-Content -path constant/version.go -Raw) -replace 'unknown version',$(Get-Date -Format 'yyyy.MM.dd')) | Set-Content -Path constant/version.go
|
||||||
|
((Get-Content -path constant/version.go -Raw) -replace 'unknown time',$(Get-Date)) | Set-Content -Path constant/version.go
|
||||||
|
|
||||||
|
# go test
|
||||||
|
go test -tags build_actions ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
#if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
run: |
|
||||||
|
$env:CGO_ENABLED=1; go build -tags build_actions -trimpath -ldflags '-w -s -buildid=' -o bin/clash-plus-pro-windows-amd64.exe
|
||||||
|
$env:GOAMD64="v3"; $env:CGO_ENABLED=1; go build -tags build_actions -trimpath -ldflags '-w -s -buildid=' -o bin/clash-plus-pro-windows-amd64-v3.exe
|
||||||
|
|
||||||
|
$version = Get-Date -Format 'yyyy.MM.dd'
|
||||||
|
|
||||||
|
cd bin/
|
||||||
|
Compress-Archive -Path clash-plus-pro-windows-amd64.exe -DestinationPath clash-plus-pro-windows-amd64-$version.zip
|
||||||
|
Compress-Archive -Path clash-plus-pro-windows-amd64-v3.exe -DestinationPath clash-plus-pro-windows-amd64-v3-$version.zip
|
||||||
|
Remove-Item -Force clash-plus-pro-windows-amd64.exe
|
||||||
|
Remove-Item -Force clash-plus-pro-windows-amd64-v3.exe
|
||||||
|
"$version" | Out-File version.txt -NoNewLine
|
||||||
|
|
||||||
|
- name: Upload files to tag
|
||||||
|
if: startsWith(github.ref, 'refs/tags/') == false
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
$version = Get-Date -Format 'yyyy.MM.dd'
|
||||||
|
|
||||||
|
$plus_pro = curl `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
https://api.github.com/repos/yaling888/clash/releases/tags/plus_pro | ConvertFrom-Json
|
||||||
|
|
||||||
|
$plus_pro_url = $plus_pro.url
|
||||||
|
$upload_url = $plus_pro.upload_url
|
||||||
|
$plus_pro_upload_url = $upload_url.Substring(0,$upload_url.Length-13)
|
||||||
|
|
||||||
|
curl `
|
||||||
|
-X PATCH `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
"$plus_pro_url" `
|
||||||
|
-d "{`"name`":`"Plus Pro $version`",`"draft`":true}" | Out-Null
|
||||||
|
|
||||||
|
foreach ($asset in $plus_pro.assets)
|
||||||
|
{
|
||||||
|
curl `
|
||||||
|
-X DELETE `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
"$($asset.url)" | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
curl `
|
||||||
|
-X POST `
|
||||||
|
-H "Content-Type: application/zip" `
|
||||||
|
-T "bin/clash-plus-pro-windows-amd64-$version.zip" `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
"$plus_pro_upload_url?name=clash-plus-pro-windows-amd64-$version.zip" | Out-Null
|
||||||
|
|
||||||
|
curl `
|
||||||
|
-X POST `
|
||||||
|
-H "Content-Type: application/zip" `
|
||||||
|
-T "bin/clash-plus-pro-windows-amd64-v3-$version.zip" `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
"$plus_pro_upload_url?name=clash-plus-pro-windows-amd64-v3-$version.zip" | Out-Null
|
||||||
|
|
||||||
|
curl `
|
||||||
|
-X POST `
|
||||||
|
-H "Content-Type: text/plain" `
|
||||||
|
-T "bin/version.txt" `
|
||||||
|
-H "Accept: application/vnd.github.v3+json" `
|
||||||
|
-H "Authorization: token $env:GITHUB_TOKEN" `
|
||||||
|
"$plus_pro_upload_url?name=version.txt" | Out-Null
|
||||||
|
|
||||||
|
#- name: Upload files to Artifacts
|
||||||
|
# uses: actions/upload-artifact@v2
|
||||||
|
# with:
|
||||||
|
# name: clash-windows-amd64-${{ steps.test.outputs.file_sha }}-${{ steps.test.outputs.file_date }}
|
||||||
|
# path: |
|
||||||
|
# bin/*
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
||||||
|
prerelease: false
|
||||||
|
generate_release_notes: false
|
||||||
|
|
||||||
|
#- name: Delete workflow runs
|
||||||
|
# uses: GitRML/delete-workflow-runs@main
|
||||||
|
# with:
|
||||||
|
# retain_days: 1
|
||||||
|
# keep_minimum_runs: 2
|
369
.github/workflows/build.yml
vendored
369
.github/workflows/build.yml
vendored
@ -1,369 +0,0 @@
|
|||||||
name: Build
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
push:
|
|
||||||
paths-ignore:
|
|
||||||
- "docs/**"
|
|
||||||
- "README.md"
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
- Meta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
- Meta
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.ref }}-${{ github.workflow }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
permissions: write-all
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
job:
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-amd64 linux-amd64-compatible",
|
|
||||||
id: "1",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-armv5 linux-armv6 linux-armv7",
|
|
||||||
id: "2",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-arm64 linux-mips64 linux-mips64le",
|
|
||||||
id: "3",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "linux-mips-softfloat linux-mips-hardfloat linux-mipsle-softfloat linux-mipsle-hardfloat",
|
|
||||||
id: "4",
|
|
||||||
}
|
|
||||||
- { type: "WithoutCGO", target: "linux-386 linux-riscv64", id: "5" }
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "freebsd-386 freebsd-amd64 freebsd-arm64",
|
|
||||||
id: "6",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-amd64-compatible windows-amd64 windows-386",
|
|
||||||
id: "7",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "windows-arm64 windows-arm32v7",
|
|
||||||
id: "8",
|
|
||||||
}
|
|
||||||
- {
|
|
||||||
type: "WithoutCGO",
|
|
||||||
target: "darwin-amd64 darwin-arm64 android-arm64",
|
|
||||||
id: "9",
|
|
||||||
}
|
|
||||||
- { type: "WithCGO", target: "windows/*", id: "1" }
|
|
||||||
- { type: "WithCGO", target: "linux/386", id: "2" }
|
|
||||||
- { type: "WithCGO", target: "linux/amd64", id: "3" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm64,linux/riscv64", id: "4" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm,", id: "5" }
|
|
||||||
- { type: "WithCGO", target: "linux/arm-6,linux/arm-7", id: "6" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips,linux/mipsle", id: "7" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64", id: "8" }
|
|
||||||
- { type: "WithCGO", target: "linux/mips64le", id: "9" }
|
|
||||||
- { type: "WithCGO", target: "darwin-10.16/*", id: "10" }
|
|
||||||
- { type: "WithCGO", target: "android", id: "11" }
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
run: echo "VERSION=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Alpha'}}
|
|
||||||
run: echo "VERSION=alpha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: echo "VERSION=beta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='Meta'}}
|
|
||||||
run: echo "VERSION=meta-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set variables
|
|
||||||
if: ${{github.ref_name=='' || github.ref_type=='tag'}}
|
|
||||||
run: echo "VERSION=$(git describe --tags)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
sudo timedatectl set-timezone "Asia/Shanghai"
|
|
||||||
echo "NAME=clash.meta" >> $GITHUB_ENV
|
|
||||||
echo "REPO=${{ github.repository }}" >> $GITHUB_ENV
|
|
||||||
echo "ShortSHA=$(git rev-parse --short ${{ github.sha }})" >> $GITHUB_ENV
|
|
||||||
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
|
||||||
echo "BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Set ENV
|
|
||||||
run: |
|
|
||||||
echo "TAGS=with_gvisor,with_lwip" >> $GITHUB_ENV
|
|
||||||
echo "LDFLAGS=-X 'github.com/Dreamacro/clash/constant.Version=${VERSION}' -X 'github.com/Dreamacro/clash/constant.BuildTime=${BUILDTIME}' -w -s -buildid=" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: "1.20"
|
|
||||||
check-latest: true
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{ matrix.job.id=='1' && matrix.job.type=='WithoutCGO' }}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build WithoutCGO
|
|
||||||
if: ${{ matrix.job.type=='WithoutCGO' }}
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
|
||||||
|
|
||||||
- uses: nttld/setup-ndk@v1
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
|
||||||
id: setup-ndk
|
|
||||||
with:
|
|
||||||
ndk-version: r25b
|
|
||||||
add-to-path: false
|
|
||||||
local-cache: true
|
|
||||||
|
|
||||||
- name: Build Android
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target=='android' }}
|
|
||||||
env:
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
run: |
|
|
||||||
mkdir bin
|
|
||||||
CC=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android33-clang
|
|
||||||
CGO_ENABLED=1 CC=${CC} GOARCH=arm64 GOOS=android go build -tags ${TAGS} -trimpath -ldflags "${LDFLAGS}" -o bin/${NAME}-android-arm64
|
|
||||||
|
|
||||||
- name: Set up xgo
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
|
||||||
run: |
|
|
||||||
docker pull techknowlogick/xgo:latest
|
|
||||||
go install src.techknowlogick.com/xgo@latest
|
|
||||||
|
|
||||||
- name: Build by xgo
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' && matrix.job.target!='android' }}
|
|
||||||
env:
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
run: |
|
|
||||||
mkdir bin
|
|
||||||
xgo --targets="${{ matrix.job.target }}" --tags="${TAGS}" -ldflags="${LDFLAGS}" --out bin/${NAME} ./
|
|
||||||
|
|
||||||
- name: Rename
|
|
||||||
if: ${{ matrix.job.type=='WithCGO' }}
|
|
||||||
run: |
|
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
cp ../.github/rename-cgo.sh ./
|
|
||||||
bash ./rename-cgo.sh
|
|
||||||
rm ./rename-cgo.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Zip
|
|
||||||
if: ${{ success() }}
|
|
||||||
run: |
|
|
||||||
cd bin
|
|
||||||
ls -la
|
|
||||||
chmod +x *
|
|
||||||
cp ../.github/release.sh ./
|
|
||||||
bash ./release.sh
|
|
||||||
rm ./release.sh
|
|
||||||
ls -la
|
|
||||||
cd ..
|
|
||||||
|
|
||||||
- name: Save version
|
|
||||||
run: echo ${VERSION} > bin/version.txt
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
Upload-Prerelease:
|
|
||||||
permissions: write-all
|
|
||||||
if: ${{ github.ref_type=='branch' }}
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Set Env
|
|
||||||
run: |
|
|
||||||
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1.0.6
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- run: |
|
|
||||||
cat > release.txt << 'EOF'
|
|
||||||
Release created at ${{ env.BUILDTIME }}
|
|
||||||
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
|
||||||
<br>
|
|
||||||
### release version
|
|
||||||
`default(not specified in file name)`: compiled with GOAMD64=v3
|
|
||||||
`cgo`: support lwip tun stack, compiled with GOAMD64=v1
|
|
||||||
`compatible`: compiled with GOAMD64=v1
|
|
||||||
Check details between different architectural levels [here](https://github.com/golang/go/wiki/MinimumRequirements#amd64).
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload Prerelease
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref_name }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: |
|
|
||||||
bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
body_path: release.txt
|
|
||||||
|
|
||||||
- name: Git push assets to "release" branch
|
|
||||||
run: |
|
|
||||||
cd bin || exit 1
|
|
||||||
git init
|
|
||||||
git config --local user.name "github-actions[bot]"
|
|
||||||
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
|
||||||
git checkout -b release
|
|
||||||
git add .
|
|
||||||
git commit -m "${{ env.BUILDTIME }}"
|
|
||||||
git remote add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"
|
|
||||||
git push -f -u origin release
|
|
||||||
|
|
||||||
Upload-Release:
|
|
||||||
permissions: write-all
|
|
||||||
if: ${{ github.ref_type=='tag' }}
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref_name }}
|
|
||||||
tag_name: ${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
Docker:
|
|
||||||
permissions: write-all
|
|
||||||
needs: [Build]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: artifact
|
|
||||||
path: bin/
|
|
||||||
|
|
||||||
- name: Display structure of downloaded files
|
|
||||||
run: ls -R
|
|
||||||
working-directory: bin
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
- name: Show files
|
|
||||||
run: |
|
|
||||||
ls .
|
|
||||||
ls bin/
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
linux/arm/v7
|
|
||||||
# linux/riscv64
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
29
.github/workflows/codeql-analysis.yml
vendored
Normal file
29
.github/workflows/codeql-analysis.yml
vendored
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
name: CodeQL
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ rm ]
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: ['go']
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v1
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
|
||||||
|
- name: Autobuild
|
||||||
|
uses: github/codeql-action/autobuild@v1
|
||||||
|
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v1
|
79
.github/workflows/docker.yml
vendored
Normal file
79
.github/workflows/docker.yml
vendored
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
name: Publish Docker Image
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- rm
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v1
|
||||||
|
with:
|
||||||
|
platforms: all
|
||||||
|
|
||||||
|
- name: Set up docker buildx
|
||||||
|
id: buildx
|
||||||
|
uses: docker/setup-buildx-action@v1
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
- name: Login to DockerHub
|
||||||
|
uses: docker/login-action@v1
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Login to Github Package
|
||||||
|
uses: docker/login-action@v1
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: Dreamacro
|
||||||
|
password: ${{ secrets.PACKAGE_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build dev branch and push
|
||||||
|
if: github.ref == 'refs/heads/dev'
|
||||||
|
uses: docker/build-push-action@v2
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
- name: Get all docker tags
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
id: tags
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
|
||||||
|
const tags = [
|
||||||
|
'dreamacro/clash:latest',
|
||||||
|
`dreamacro/clash:${ref}`,
|
||||||
|
'ghcr.io/dreamacro/clash:latest',
|
||||||
|
`ghcr.io/dreamacro/clash:${ref}`
|
||||||
|
]
|
||||||
|
return tags.join(',')
|
||||||
|
result-encoding: string
|
||||||
|
|
||||||
|
- name: Build release and push
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
uses: docker/build-push-action@v2
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: ${{steps.tags.outputs.result}}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
23
.github/workflows/linter.yml
vendored
Normal file
23
.github/workflows/linter.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
name: Linter
|
||||||
|
on: [push, pull_request]
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v3
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
args: --build-tags=build_local
|
120
.github/workflows/release.yml
vendored
Normal file
120
.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
name: Release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- rm
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Get latest go version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
|
|
||||||
|
- name: Check out code into the Go module directory
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Go cache paths
|
||||||
|
id: go-cache-paths
|
||||||
|
run: |
|
||||||
|
echo "::set-output name=go-build::$(go env GOCACHE)"
|
||||||
|
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
||||||
|
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v2
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
${{ steps.go-cache-paths.outputs.go-mod }}
|
||||||
|
${{ steps.go-cache-paths.outputs.go-build }}
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: '3.9'
|
||||||
|
|
||||||
|
- name: Get dependencies, run test
|
||||||
|
run: |
|
||||||
|
# fetch python cross compile source files
|
||||||
|
mkdir -p bin/python/
|
||||||
|
cd bin/python/
|
||||||
|
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-amd64.tar.xz
|
||||||
|
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-arm64.tar.xz
|
||||||
|
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-amd64.tar.xz
|
||||||
|
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-386.tar.xz
|
||||||
|
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-amd64.tar.xz
|
||||||
|
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-arm64.tar.xz
|
||||||
|
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-386.tar.xz
|
||||||
|
tar -Jxf python-3.9.7-darwin-amd64.tar.xz
|
||||||
|
tar -Jxf python-3.9.7-darwin-arm64.tar.xz
|
||||||
|
tar -Jxf python-3.9.7-windows-amd64.tar.xz
|
||||||
|
tar -Jxf python-3.9.7-windows-386.tar.xz
|
||||||
|
#tar -Jxf python-3.9.7-linux-amd64.tar.xz
|
||||||
|
#tar -Jxf python-3.9.7-linux-arm64.tar.xz
|
||||||
|
#tar -Jxf python-3.9.7-linux-386.tar.xz
|
||||||
|
rm python-3.9.7-*.tar.xz
|
||||||
|
cd ../../
|
||||||
|
|
||||||
|
# go test
|
||||||
|
go test -tags build_local ./...
|
||||||
|
|
||||||
|
# init xgo
|
||||||
|
docker pull techknowlogick/xgo:latest
|
||||||
|
go install src.techknowlogick.com/xgo@latest
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
#if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
NAME: clash
|
||||||
|
BINDIR: bin
|
||||||
|
run: |
|
||||||
|
make -j releases
|
||||||
|
#ls -lahF bin/python/
|
||||||
|
|
||||||
|
- name: Prepare upload
|
||||||
|
if: startsWith(github.ref, 'refs/tags/') == false
|
||||||
|
run: |
|
||||||
|
rm -rf bin/python/
|
||||||
|
echo "FILE_DATE=_$(date +"%Y%m%d%H%M")" >> $GITHUB_ENV
|
||||||
|
echo "FILE_SHA=$(git describe --tags --always 2>/dev/null)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Upload files to Artifacts
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
if: startsWith(github.ref, 'refs/tags/') == false
|
||||||
|
with:
|
||||||
|
name: clash_${{ env.FILE_SHA }}${{ env.FILE_DATE }}
|
||||||
|
path: |
|
||||||
|
bin/*
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
||||||
|
|
||||||
|
#- name: Delete workflow runs
|
||||||
|
# uses: GitRML/delete-workflow-runs@main
|
||||||
|
# with:
|
||||||
|
# retain_days: 1
|
||||||
|
# keep_minimum_runs: 2
|
||||||
|
|
||||||
|
- name: Remove old Releases
|
||||||
|
uses: dev-drprasad/delete-older-releases@v0.2.0
|
||||||
|
if: startsWith(github.ref, 'refs/tags/') && !cancelled()
|
||||||
|
with:
|
||||||
|
keep_latest: 1
|
||||||
|
delete_tags: true
|
||||||
|
delete_tag_pattern: plus-pro
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
19
.github/workflows/stale.yml
vendored
Normal file
19
.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
|
||||||
|
name: Mark stale issues and pull requests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- rm
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
stale:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/stale@v5
|
||||||
|
with:
|
||||||
|
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
||||||
|
days-before-stale: 60
|
||||||
|
days-before-close: 5
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -23,6 +23,3 @@ vendor
|
|||||||
|
|
||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
|
||||||
.vscode/
|
|
||||||
.fleet/
|
|
@ -8,10 +8,9 @@ linters:
|
|||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
gci:
|
gci:
|
||||||
custom-order: true
|
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/Dreamacro/clash)
|
- prefix(github.com/Dreamacro/clash)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.19'
|
go: '1.18'
|
||||||
|
37
Dockerfile
37
Dockerfile
@ -1,27 +1,18 @@
|
|||||||
FROM alpine:latest as builder
|
FROM golang:alpine as builder
|
||||||
ARG TARGETPLATFORM
|
|
||||||
RUN echo "I'm building for $TARGETPLATFORM"
|
|
||||||
|
|
||||||
RUN apk add --no-cache gzip && \
|
RUN apk add --no-cache make git && \
|
||||||
mkdir /clash-config && \
|
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
||||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
WORKDIR /clash-src
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
COPY --from=tonistiigi/xx:golang / /
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
COPY . /clash-src
|
||||||
|
RUN go mod download && \
|
||||||
|
make docker && \
|
||||||
|
mv ./bin/clash-docker /clash
|
||||||
|
|
||||||
COPY docker/file-name.sh /clash/file-name.sh
|
|
||||||
WORKDIR /clash
|
|
||||||
COPY bin/ bin/
|
|
||||||
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
|
||||||
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.*"|awk NR==1` && echo $FILE_NAME && \
|
|
||||||
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/Dreamacro/clash"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata iptables
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
|
COPY --from=builder /Country.mmdb /root/.config/clash/
|
||||||
VOLUME ["/root/.config/clash/"]
|
COPY --from=builder /clash /
|
||||||
|
ENTRYPOINT ["/clash"]
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
|
||||||
COPY --from=builder /clash/clash /clash
|
|
||||||
RUN chmod +x /clash
|
|
||||||
ENTRYPOINT [ "/clash" ]
|
|
||||||
|
166
Makefile
166
Makefile
@ -1,135 +1,70 @@
|
|||||||
NAME=clash.meta
|
GOCMD=go
|
||||||
BINDIR=bin
|
XGOCMD=xgo -go=go-1.18.x
|
||||||
BRANCH=$(shell git branch --show-current)
|
GOBUILD=CGO_ENABLED=1 $(GOCMD) build -trimpath
|
||||||
ifeq ($(BRANCH),Alpha)
|
GOCLEAN=$(GOCMD) clean
|
||||||
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
NAME=clash
|
||||||
else ifeq ($(BRANCH),Beta)
|
BINDIR=$(shell pwd)/bin
|
||||||
VERSION=beta-$(shell git rev-parse --short HEAD)
|
VERSION=$(shell git describe --tags --always 2>/dev/null || date +%F)
|
||||||
else ifeq ($(BRANCH),)
|
|
||||||
VERSION=$(shell git describe --tags)
|
|
||||||
else
|
|
||||||
VERSION=$(shell git rev-parse --short HEAD)
|
|
||||||
endif
|
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
BUILD_PACKAGE=.
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
RELEASE_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-w -s -buildid='
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
|
-w -s -buildid='
|
||||||
|
STATIC_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
|
-extldflags "-static" \
|
||||||
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64-compatible \
|
linux-amd64
|
||||||
linux-amd64 \
|
# linux-arm64
|
||||||
linux-armv5 \
|
# linux-386
|
||||||
linux-armv6 \
|
|
||||||
linux-armv7 \
|
|
||||||
linux-arm64 \
|
|
||||||
linux-mips64 \
|
|
||||||
linux-mips64le \
|
|
||||||
linux-mips-softfloat \
|
|
||||||
linux-mips-hardfloat \
|
|
||||||
linux-mipsle-softfloat \
|
|
||||||
linux-mipsle-hardfloat \
|
|
||||||
android-arm64 \
|
|
||||||
freebsd-386 \
|
|
||||||
freebsd-amd64 \
|
|
||||||
freebsd-arm64
|
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
|
||||||
windows-amd64-compatible \
|
|
||||||
windows-amd64 \
|
windows-amd64 \
|
||||||
windows-arm64 \
|
windows-386
|
||||||
windows-arm32v7
|
# windows-arm64
|
||||||
|
|
||||||
all:linux-amd64 linux-arm64\
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
darwin-amd64 darwin-arm64\
|
|
||||||
windows-amd64 windows-arm64\
|
|
||||||
|
|
||||||
|
local:
|
||||||
|
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-all: darwin-amd64 darwin-arm64
|
local-v3:
|
||||||
|
GOAMD64=v3 $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
||||||
docker:
|
|
||||||
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-10.12/amd64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-darwin-10.12-amd64 $(BINDIR)/$(NAME)-darwin-amd64
|
||||||
darwin-amd64-compatible:
|
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-11.1/arm64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-darwin-11.1-arm64 $(BINDIR)/$(NAME)-darwin-arm64
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/386 $(BUILD_PACKAGE)
|
||||||
|
|
||||||
linux-amd64:
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
#GOARCH=amd64 GOOS=linux $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -o $(BINDIR)/$(NAME)-$@
|
||||||
linux-amd64-compatible:
|
#$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/amd64 $(BUILD_PACKAGE)
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/arm64 $(BUILD_PACKAGE)
|
||||||
|
|
||||||
linux-armv5:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-armv6:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-armv7:
|
|
||||||
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mips-softfloat:
|
|
||||||
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mips-hardfloat:
|
|
||||||
GOARCH=mips GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mipsle-softfloat:
|
|
||||||
GOARCH=mipsle GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mipsle-hardfloat:
|
|
||||||
GOARCH=mipsle GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mips64:
|
|
||||||
GOARCH=mips64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-mips64le:
|
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-riscv64:
|
|
||||||
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
android-arm64:
|
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
freebsd-386:
|
|
||||||
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
freebsd-amd64:
|
|
||||||
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
freebsd-arm64:
|
|
||||||
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/386 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-windows-6.0-386.exe $(BINDIR)/$(NAME)-windows-386.exe
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/amd64 $(BUILD_PACKAGE) && \
|
||||||
|
mv $(BINDIR)/$(NAME)-windows-6.0-amd64.exe $(BINDIR)/$(NAME)-windows-amd64.exe
|
||||||
|
|
||||||
windows-amd64-compatible:
|
#windows-arm64:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
# $(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows/arm64 $(BUILD_PACKAGE)
|
||||||
|
# mv $(NAME)-windows-4.0-arm64.exe $(NAME)-windows-arm64.exe
|
||||||
windows-arm64:
|
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
|
||||||
|
|
||||||
windows-arm32v7:
|
|
||||||
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
|
||||||
|
|
||||||
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||||
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||||
@ -146,18 +81,17 @@ all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
|||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
vet:
|
vet:
|
||||||
go test ./...
|
$(GOCMD) test -tags build_local ./...
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
golangci-lint run ./...
|
golangci-lint run --build-tags=build_local ./...
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm -rf $(BINDIR)/
|
||||||
|
mkdir -p $(BINDIR)
|
||||||
|
|
||||||
CLANG ?= clang-14
|
cleancache:
|
||||||
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
# go build cache may need to cleanup if changing C source code
|
||||||
|
$(GOCLEAN) -cache
|
||||||
ebpf: export BPF_CLANG := $(CLANG)
|
rm -rf $(BINDIR)/
|
||||||
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
mkdir -p $(BINDIR)
|
||||||
ebpf:
|
|
||||||
cd component/ebpf/ && go generate ./...
|
|
597
README.md
597
README.md
@ -1,20 +1,23 @@
|
|||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
<img src="Meta.png" alt="Meta Kennel" width="200">
|
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
||||||
<br>Meta Kernel<br>
|
<br>Clash<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h3 align="center">Another Clash Kernel.</h3>
|
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
<a href="https://github.com/Dreamacro/clash/releases">
|
||||||
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
|
||||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@ -29,121 +32,198 @@
|
|||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Wiki
|
## Getting Started
|
||||||
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
Documentation and configuring examples are available on [Clash.Meta Wiki](https://clash-meta.wiki).
|
## Advanced usage for this branch
|
||||||
|
### Build
|
||||||
|
This branch requires cgo and Python3.9, so make sure you set up Python3.9 before building.
|
||||||
|
|
||||||
## Build
|
For example, build on macOS:
|
||||||
|
```sh
|
||||||
|
brew update
|
||||||
|
brew install python@3.9
|
||||||
|
|
||||||
You should install [golang](https://go.dev) first.
|
export PKG_CONFIG_PATH=$(find /usr/local/Cellar -name 'pkgconfig' -type d | grep lib/pkgconfig | tr '\n' ':' | sed s/.$//)
|
||||||
|
|
||||||
Then get the source code of Clash.Meta:
|
git clone -b plus-pro https://github.com/yaling888/clash.git
|
||||||
|
cd clash
|
||||||
|
|
||||||
```shell
|
# build
|
||||||
git clone https://github.com/MetaCubeX/Clash.Meta.git
|
make local
|
||||||
cd Clash.Meta && go mod download
|
# or make local-v3
|
||||||
|
|
||||||
|
ls bin/
|
||||||
|
|
||||||
|
# run
|
||||||
|
sudo bin/clash-local
|
||||||
```
|
```
|
||||||
|
|
||||||
If you can't visit github,you should set proxy first:
|
### General configuration
|
||||||
|
```yaml
|
||||||
|
sniffing: true # Sniff TLS SNI
|
||||||
|
|
||||||
```shell
|
force-cert-verify: true # force verify TLS Certificate, prevent machine-in-the-middle attacks
|
||||||
go env -w GOPROXY=https://goproxy.io,direct
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you can build it:
|
### MITM configuration
|
||||||
|
A root CA certificate is required, the
|
||||||
|
MITM proxy server will generate a CA certificate file and a CA private key file in your Clash home directory, you can use your own certificate replace it.
|
||||||
|
|
||||||
```shell
|
Need to install and trust the CA certificate on the client device, open this URL [http://mitm.clash/cert.crt](http://mitm.clash/cert.crt) by the web browser to install the CA certificate, the host name 'mitm.clash' was always been hijacked.
|
||||||
go build
|
|
||||||
|
NOTE: this feature cannot work on tls pinning
|
||||||
|
|
||||||
|
WARNING: DO NOT USE THIS FEATURE TO BREAK LOCAL LAWS
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Port of MITM proxy server on the local end
|
||||||
|
mitm-port: 7894
|
||||||
|
|
||||||
|
# Man-In-The-Middle attack
|
||||||
|
mitm:
|
||||||
|
hosts: # use for others proxy type. E.g: TUN, socks
|
||||||
|
- +.example.com
|
||||||
|
rules: # rewrite rules
|
||||||
|
- '^https?://www\.example\.com/1 url reject' # The "reject" returns HTTP status code 404 with no content.
|
||||||
|
- '^https?://www\.example\.com/2 url reject-200' # The "reject-200" returns HTTP status code 200 with no content.
|
||||||
|
- '^https?://www\.example\.com/3 url reject-img' # The "reject-img" returns HTTP status code 200 with content of 1px png.
|
||||||
|
- '^https?://www\.example\.com/4 url reject-dict' # The "reject-dict" returns HTTP status code 200 with content of empty json object.
|
||||||
|
- '^https?://www\.example\.com/5 url reject-array' # The "reject-array" returns HTTP status code 200 with content of empty json array.
|
||||||
|
- '^https?://www\.example\.com/(6) url 302 https://www.example.com/new-$1'
|
||||||
|
- '^https?://www\.(example)\.com/7 url 307 https://www.$1.com/new-7'
|
||||||
|
- '^https?://www\.example\.com/8 url request-header (\r\n)User-Agent:.+(\r\n) request-header $1User-Agent: haha-wriohoh$2' # The "request-header" works for all the http headers not just one single header, so you can match two or more headers including CRLF in one regular expression.
|
||||||
|
- '^https?://www\.example\.com/9 url request-body "pos_2":\[.*\],"pos_3" request-body "pos_2":[{"xx": "xx"}],"pos_3"'
|
||||||
|
- '^https?://www\.example\.com/10 url response-header (\r\n)Tracecode:.+(\r\n) response-header $1Tracecode: 88888888888$2'
|
||||||
|
- '^https?://www\.example\.com/11 url response-body "errmsg":"ok" response-body "errmsg":"not-ok"'
|
||||||
```
|
```
|
||||||
|
|
||||||
If you need gvisor for tun stack, build with:
|
### DNS configuration
|
||||||
|
Support resolve ip with a proxy tunnel or interface.
|
||||||
```shell
|
|
||||||
go build -tags with_gvisor
|
|
||||||
```
|
|
||||||
|
|
||||||
<!-- ## Advanced usage of this fork -->
|
|
||||||
|
|
||||||
<!-- ### DNS configuration
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
Restore `Redir remote resolution`.
|
Use `curl -X POST controllerip:port/cache/fakeip/flush` to flush persistence fakeip
|
||||||
|
```yaml
|
||||||
Support resolve ip with a `Proxy Tunnel`.
|
dns:
|
||||||
|
enable: true
|
||||||
```yaml
|
use-hosts: true
|
||||||
proxy-groups:
|
ipv6: false
|
||||||
- name: DNS
|
enhanced-mode: fake-ip
|
||||||
type: url-test
|
fake-ip-range: 198.18.0.1/16
|
||||||
use:
|
listen: 127.0.0.1:6868
|
||||||
- HK
|
default-nameserver:
|
||||||
url: http://cp.cloudflare.com
|
- 119.29.29.29
|
||||||
interval: 180
|
- 114.114.114.114
|
||||||
lazy: true
|
nameserver:
|
||||||
```
|
- https://doh.pub/dns-query
|
||||||
|
- tls://223.5.5.5:853
|
||||||
```yaml
|
fallback:
|
||||||
dns:
|
- 'tls://8.8.4.4:853#proxy or interface'
|
||||||
enable: true
|
- 'https://1.0.0.1/dns-query#Proxy' # append the proxy adapter name to the end of DNS URL with '#' prefix.
|
||||||
use-hosts: true
|
fallback-filter:
|
||||||
ipv6: false
|
geoip: false
|
||||||
enhanced-mode: redir-host
|
geosite:
|
||||||
fake-ip-range: 198.18.0.1/16
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to untrusted DNS providers.
|
||||||
listen: 127.0.0.1:6868
|
domain:
|
||||||
default-nameserver:
|
- +.example.com
|
||||||
- 119.29.29.29
|
ipcidr:
|
||||||
- 114.114.114.114
|
- 0.0.0.0/32
|
||||||
nameserver:
|
```
|
||||||
- https://doh.pub/dns-query
|
|
||||||
- tls://223.5.5.5:853
|
|
||||||
fallback:
|
|
||||||
- "https://1.0.0.1/dns-query#DNS" # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
|
||||||
- "tls://8.8.4.4:853#DNS"
|
|
||||||
fallback-filter:
|
|
||||||
geoip: false
|
|
||||||
geosite:
|
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
|
||||||
domain:
|
|
||||||
- +.example.com
|
|
||||||
ipcidr:
|
|
||||||
- 0.0.0.0/32
|
|
||||||
```
|
|
||||||
|
|
||||||
### TUN configuration
|
### TUN configuration
|
||||||
|
Simply add the following to the main configuration:
|
||||||
|
|
||||||
Supports macOS, Linux and Windows.
|
#### NOTE:
|
||||||
|
> auto-route and auto-detect-interface only available on macOS, Windows and Linux, receive IPv4 traffic
|
||||||
Built-in [Wintun](https://www.wintun.net) driver.
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TUN listener
|
|
||||||
tun:
|
tun:
|
||||||
enable: true
|
enable: true
|
||||||
stack: system # system/gvisor
|
stack: system # or gvisor
|
||||||
dns-hijack:
|
# device: tun://utun8 # or fd://xxx, it's optional
|
||||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
# dns-hijack:
|
||||||
|
# - 8.8.8.8:53
|
||||||
|
# - tcp://8.8.8.8:53
|
||||||
|
# - any:53
|
||||||
|
# - tcp://any:53
|
||||||
|
auto-route: true # auto set global route
|
||||||
|
auto-detect-interface: true # conflict with interface-name
|
||||||
|
```
|
||||||
|
or
|
||||||
|
```yaml
|
||||||
|
interface-name: en0
|
||||||
|
|
||||||
|
tun:
|
||||||
|
enable: true
|
||||||
|
stack: system # or gvisor
|
||||||
|
# dns-hijack:
|
||||||
|
# - 8.8.8.8:53
|
||||||
|
# - tcp://8.8.8.8:53
|
||||||
auto-route: true # auto set global route
|
auto-route: true # auto set global route
|
||||||
```
|
```
|
||||||
|
It's recommended to use fake-ip mode for the DNS server.
|
||||||
|
|
||||||
|
Clash needs elevated permission to create TUN device:
|
||||||
|
```sh
|
||||||
|
$ sudo ./clash
|
||||||
|
```
|
||||||
|
Then manually create the default route and DNS server. If your device already has some TUN device, Clash TUN might not work. In this case, fake-ip-filter may helpful.
|
||||||
|
|
||||||
|
Enjoy! :)
|
||||||
|
|
||||||
|
#### For Windows:
|
||||||
|
```yaml
|
||||||
|
tun:
|
||||||
|
enable: true
|
||||||
|
stack: gvisor # or system
|
||||||
|
dns-hijack:
|
||||||
|
- 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
|
||||||
|
auto-route: true # auto set global route for Windows
|
||||||
|
# It is recommended to use `interface-name`
|
||||||
|
auto-detect-interface: true # auto detect interface, conflict with `interface-name`
|
||||||
|
```
|
||||||
|
Finally, open the Clash
|
||||||
|
|
||||||
### Rules configuration
|
### Rules configuration
|
||||||
|
|
||||||
- Support rule `GEOSITE`.
|
- Support rule `GEOSITE`.
|
||||||
- Support rule-providers `RULE-SET`.
|
- Support rule `USER-AGENT`.
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
- Support `network` condition for all rules.
|
- Support `network` condition for all rules.
|
||||||
|
- Support `process` condition for all rules.
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
|
||||||
|
|
||||||
|
The `GEOIP` databases via [https://github.com/Loyalsoldier/geoip](https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb).
|
||||||
|
|
||||||
|
The `GEOSITE` databases via [https://github.com/Loyalsoldier/v2ray-rules-dat](https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat).
|
||||||
```yaml
|
```yaml
|
||||||
|
mode: rule
|
||||||
|
|
||||||
|
script:
|
||||||
|
shortcuts:
|
||||||
|
quic: 'network == "udp" and dst_port == 443'
|
||||||
|
privacy: '"analytics" in host or "adservice" in host or "firebase" in host or "safebrowsing" in host or "doubleclick" in host'
|
||||||
|
BilibiliUdp: |
|
||||||
|
network == "udp" and match_provider("geosite:bilibili")
|
||||||
rules:
|
rules:
|
||||||
# network(tcp/udp) condition for all rules
|
# rule SCRIPT shortcuts
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
- SCRIPT,quic,REJECT # Disable QUIC, same as rule "DST-PORT,443,REJECT,udp"
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
- SCRIPT,privacy,REJECT
|
||||||
|
- SCRIPT,BilibiliUdp,REJECT # same as rule "GEOSITE,bilibili,REJECT,udp"
|
||||||
|
|
||||||
|
# network condition for all rules
|
||||||
|
- DOMAIN-SUFFIX,example.com,DIRECT,tcp
|
||||||
|
- DOMAIN-SUFFIX,example.com,REJECT,udp
|
||||||
|
|
||||||
|
# process condition for all rules (add 'P:' prefix)
|
||||||
|
- DOMAIN-SUFFIX,example.com,REJECT,P:Google Chrome Helper
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
|
# USER-AGENT payload cannot include the comma character, '*' meaning any character.
|
||||||
|
- USER-AGENT,*example*,PROXY
|
||||||
|
|
||||||
# rule GEOSITE
|
# rule GEOSITE
|
||||||
- GEOSITE,category-ads-all,REJECT
|
- GEOSITE,category-ads-all,REJECT
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
@ -157,129 +237,184 @@ rules:
|
|||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
# source IPCIDR condition for all rules in gateway proxy
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
- GEOIP,private,DIRECT,no-resolve
|
- GEOIP,lan,DIRECT,no-resolve
|
||||||
- GEOIP,cn,DIRECT
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
### Proxies configuration
|
### Script configuration
|
||||||
|
Script enables users to programmatically select a policy for the packets with more flexibility.
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
|
||||||
|
|
||||||
Support `Policy Group Filter`
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy-groups:
|
mode: script
|
||||||
- name: 🚀 HK Group
|
|
||||||
type: select
|
|
||||||
use:
|
|
||||||
- ALL
|
|
||||||
filter: "HK"
|
|
||||||
|
|
||||||
- name: 🚀 US Group
|
script:
|
||||||
type: select
|
# path: ./script.star
|
||||||
|
code: |
|
||||||
|
def main(ctx, metadata):
|
||||||
|
if metadata["process_name"] == 'apsd':
|
||||||
|
return "DIRECT"
|
||||||
|
|
||||||
|
if metadata["network"] == 'udp' and metadata["dst_port"] == 443:
|
||||||
|
return "REJECT"
|
||||||
|
|
||||||
|
host = metadata["host"]
|
||||||
|
for kw in ['analytics', 'adservice', 'firebase', 'bugly', 'safebrowsing', 'doubleclick']:
|
||||||
|
if kw in host:
|
||||||
|
return "REJECT"
|
||||||
|
|
||||||
|
now = time.now()
|
||||||
|
if (now.hour < 8 or now.hour > 17) and metadata["src_ip"] == '192.168.1.99':
|
||||||
|
return "REJECT"
|
||||||
|
|
||||||
|
if ctx.rule_providers["geosite:category-ads-all"].match(metadata):
|
||||||
|
return "REJECT"
|
||||||
|
|
||||||
|
if ctx.rule_providers["geosite:youtube"].match(metadata):
|
||||||
|
ctx.log('[Script] domain %s matched youtube' % host)
|
||||||
|
return "Proxy"
|
||||||
|
|
||||||
|
if ctx.rule_providers["geosite:geolocation-cn"].match(metadata):
|
||||||
|
ctx.log('[Script] domain %s matched geolocation-cn' % host)
|
||||||
|
return "DIRECT"
|
||||||
|
|
||||||
|
ip = metadata["dst_ip"]
|
||||||
|
if host != "":
|
||||||
|
ip = ctx.resolve_ip(host)
|
||||||
|
if ip == "":
|
||||||
|
return "Proxy"
|
||||||
|
|
||||||
|
code = ctx.geoip(ip)
|
||||||
|
if code == "LAN" or code == "CN":
|
||||||
|
return "DIRECT"
|
||||||
|
|
||||||
|
return "Proxy" # default policy for requests which are not matched by any other script
|
||||||
|
```
|
||||||
|
the context and metadata
|
||||||
|
```ts
|
||||||
|
interface Metadata {
|
||||||
|
type: string // socks5、http
|
||||||
|
network: string // tcp
|
||||||
|
host: string
|
||||||
|
process_name: string
|
||||||
|
process_path: string
|
||||||
|
src_ip: string
|
||||||
|
src_port: int
|
||||||
|
dst_ip: string
|
||||||
|
dst_port: int
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Context {
|
||||||
|
resolve_ip: (host: string) => string // ip string
|
||||||
|
geoip: (ip: string) => string // country code
|
||||||
|
log: (log: string) => void
|
||||||
|
rule_providers: Record<string, { match: (metadata: Metadata) => boolean }>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Proxies configuration
|
||||||
|
Support outbound protocol `VLESS`.
|
||||||
|
|
||||||
|
Support `Trojan` with XTLS.
|
||||||
|
|
||||||
|
Support relay `UDP` traffic.
|
||||||
|
|
||||||
|
Support filtering proxy providers in proxy groups.
|
||||||
|
|
||||||
|
Support custom http request header, prefix name and V2Ray subscription URL in proxy providers.
|
||||||
|
```yaml
|
||||||
|
proxies:
|
||||||
|
# VLESS
|
||||||
|
- name: "vless-tls"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
network: tcp
|
||||||
|
servername: example.com
|
||||||
|
udp: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
- name: "vless-xtls"
|
||||||
|
type: vless
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
uuid: uuid
|
||||||
|
network: tcp
|
||||||
|
servername: example.com
|
||||||
|
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||||
|
# flow-show: true # print the XTLS direction log
|
||||||
|
# udp: true
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
# Trojan
|
||||||
|
- name: "trojan-xtls"
|
||||||
|
type: trojan
|
||||||
|
server: server
|
||||||
|
port: 443
|
||||||
|
password: yourpsk
|
||||||
|
network: tcp
|
||||||
|
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||||
|
# flow-show: true # print the XTLS direction log
|
||||||
|
# udp: true
|
||||||
|
# sni: example.com # aka server name
|
||||||
|
# skip-cert-verify: true
|
||||||
|
|
||||||
|
proxy-groups:
|
||||||
|
# Relay chains the proxies. proxies shall not contain a relay.
|
||||||
|
# Support relay UDP traffic.
|
||||||
|
# Traffic: clash <-> ss1 <-> trojan <-> vmess <-> ss2 <-> Internet
|
||||||
|
- name: "relay-udp-over-tcp"
|
||||||
|
type: relay
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- trojan
|
||||||
|
- vmess
|
||||||
|
- ss2
|
||||||
|
|
||||||
|
- name: "relay-raw-udp"
|
||||||
|
type: relay
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- ss3
|
||||||
|
|
||||||
|
- name: "filtering-proxy-providers"
|
||||||
|
type: url-test
|
||||||
|
url: "http://www.gstatic.com/generate_204"
|
||||||
|
interval: 300
|
||||||
|
tolerance: 200
|
||||||
|
# lazy: true
|
||||||
|
filter: "XXX" # a regular expression
|
||||||
use:
|
use:
|
||||||
- ALL
|
- provider1
|
||||||
filter: "US"
|
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
ALL:
|
provider1:
|
||||||
type: http
|
type: http
|
||||||
url: "xxxxx"
|
url: "url" # support V2Ray subscription URL
|
||||||
interval: 3600
|
interval: 3600
|
||||||
path: "xxxxx"
|
path: ./providers/provider1.yaml
|
||||||
|
# filter: "xxx"
|
||||||
|
# prefix-name: "XXX-"
|
||||||
|
header: # custom http request header
|
||||||
|
User-Agent:
|
||||||
|
- "Clash/v1.10.6"
|
||||||
|
# Accept:
|
||||||
|
# - 'application/vnd.github.v3.raw'
|
||||||
|
# Authorization:
|
||||||
|
# - ' token xxxxxxxxxxx'
|
||||||
health-check:
|
health-check:
|
||||||
enable: true
|
enable: false
|
||||||
interval: 600
|
interval: 1200
|
||||||
|
# lazy: false # default value is true
|
||||||
url: http://www.gstatic.com/generate_204
|
url: http://www.gstatic.com/generate_204
|
||||||
```
|
```
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "vless"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
servername: example.com # AKA SNI
|
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
- name: "vless-ws"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: ws
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
ws-opts:
|
|
||||||
path: /path
|
|
||||||
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
|
||||||
|
|
||||||
- name: "vless-grpc"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: grpc
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
grpc-opts:
|
|
||||||
grpc-service-name: grpcname
|
|
||||||
```
|
|
||||||
|
|
||||||
Support outbound transport protocol `Wireguard`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "wg"
|
|
||||||
type: wireguard
|
|
||||||
server: 162.159.192.1
|
|
||||||
port: 2480
|
|
||||||
ip: 172.16.0.2
|
|
||||||
ipv6: fd01:5ca1:ab1e:80fa:ab85:6eea:213f:f4a5
|
|
||||||
private-key: eCtXsJZ27+4PbhDkHnB923tkUn2Gj59wZw5wFA75MnU=
|
|
||||||
public-key: Cr8hWlKvtDt7nrvf+f0brNQQzabAqrjfBvas9pmowjo=
|
|
||||||
udp: true
|
|
||||||
```
|
|
||||||
|
|
||||||
Support outbound transport protocol `Tuic`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "tuic"
|
|
||||||
server: www.example.com
|
|
||||||
port: 10443
|
|
||||||
type: tuic
|
|
||||||
token: TOKEN
|
|
||||||
# ip: 127.0.0.1 # for overwriting the DNS lookup result of the server address set in option 'server'
|
|
||||||
# heartbeat-interval: 10000
|
|
||||||
# alpn: [h3]
|
|
||||||
# disable-sni: true
|
|
||||||
reduce-rtt: true
|
|
||||||
# request-timeout: 8000
|
|
||||||
udp-relay-mode: native # Available: "native", "quic". Default: "native"
|
|
||||||
# congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic"
|
|
||||||
# max-udp-relay-packet-size: 1500
|
|
||||||
# fast-open: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
``` -->
|
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
|
Work on Linux OS who's supported `iptables`
|
||||||
Work on Linux OS which supported `iptables`
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@ -289,81 +424,61 @@ iptables:
|
|||||||
enable: true # default is false
|
enable: true # default is false
|
||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
Run Clash as a daemon.
|
||||||
|
|
||||||
### General installation guide for Linux
|
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
||||||
|
```sh
|
||||||
- Create user given name `clash-meta`
|
|
||||||
|
|
||||||
- Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
|
||||||
|
|
||||||
- Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
|
||||||
|
|
||||||
- Create folder `/etc/Clash-Meta/` as working directory
|
|
||||||
|
|
||||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
|
||||||
|
|
||||||
Create the systemd configuration file at `/etc/systemd/system/Clash-Meta.service`:
|
|
||||||
|
|
||||||
```
|
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Clash-Meta Daemon, Another Clash Kernel.
|
Description=Clash daemon, A rule-based proxy in Go.
|
||||||
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
After=network.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=clash-meta
|
CapabilityBoundingSet=cap_net_admin
|
||||||
Group=clash-meta
|
|
||||||
LimitNPROC=500
|
|
||||||
LimitNOFILE=1000000
|
|
||||||
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
|
||||||
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
|
||||||
Restart=always
|
Restart=always
|
||||||
ExecStartPre=/usr/bin/sleep 1s
|
ExecStart=/usr/local/bin/clash -d /etc/clash
|
||||||
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
|
```sh
|
||||||
```shell
|
$ systemctl enable clash
|
||||||
$ systemctl enable Clash-Meta
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
|
```sh
|
||||||
```shell
|
$ systemctl start clash
|
||||||
$ systemctl start Clash-Meta
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Display Process name
|
### Display Process name
|
||||||
|
To display process name online by click [http://yacd.clash-plus.cf](http://yacd.clash-plus.cf) for local API by Safari or [https://yacd.clash-plus.cf](https://yacd.clash-plus.cf) for local API by Chrome.
|
||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
You can download the [Dashboard](https://github.com/yaling888/yacd/archive/gh-pages.zip) into Clash home directory:
|
||||||
|
```sh
|
||||||
|
$ cd ~/.config/clash
|
||||||
|
$ curl -LJ https://github.com/yaling888/yacd/archive/gh-pages.zip -o yacd-gh-pages.zip
|
||||||
|
$ unzip yacd-gh-pages.zip
|
||||||
|
$ mv yacd-gh-pages dashboard
|
||||||
|
```
|
||||||
|
|
||||||
To display process name in GUI please use [Razord-meta](https://github.com/MetaCubeX/Razord-meta).
|
Add to config file:
|
||||||
|
```yaml
|
||||||
|
external-controller: 127.0.0.1:9090
|
||||||
|
external-ui: dashboard
|
||||||
|
```
|
||||||
|
Open [http://127.0.0.1:9090/ui/](http://127.0.0.1:9090/ui/) by web browser.
|
||||||
|
|
||||||
### Dashboard
|
## Plus Pro Release
|
||||||
|
[Release](https://github.com/yaling888/clash/releases/tag/plus_pro)
|
||||||
We also made a custom fork of yacd provide better support for this project, check it out at [Yacd-meta](https://github.com/MetaCubeX/Yacd-meta)
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
If you want to build an application that uses clash as a library, check out the the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
||||||
If you want to build an application that uses clash as a library, check out the
|
|
||||||
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
|
||||||
|
|
||||||
## Debugging
|
|
||||||
Check [wiki](https://github.com/MetaCubeX/Clash.Meta/wiki/How-to-use-debug-api) to get an instruction on using debug API.
|
|
||||||
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
|
||||||
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
|
||||||
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -4,20 +4,19 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
@ -39,6 +38,7 @@ func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
|
p.alive.Store(err == nil)
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,6 +52,7 @@ func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
|
p.alive.Store(err == nil)
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,8 +93,6 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
mapping["xudp"] = p.SupportXUDP()
|
|
||||||
mapping["tfo"] = p.SupportTFO()
|
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -112,8 +111,6 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
|
||||||
|
|
||||||
addr, err := urlToMetadata(url)
|
addr, err := urlToMetadata(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -146,32 +143,18 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
Timeout: 30 * time.Second,
|
|
||||||
Transport: transport,
|
Transport: transport,
|
||||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
defer client.CloseIdleConnections()
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = resp.Body.Close()
|
_ = resp.Body.Close()
|
||||||
|
|
||||||
if unifiedDelay {
|
|
||||||
second := time.Now()
|
|
||||||
resp, err = client.Do(req)
|
|
||||||
if err == nil {
|
|
||||||
_ = resp.Body.Close()
|
|
||||||
start = second
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -200,9 +183,10 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
Host: u.Hostname(),
|
AddrType: C.AtypDomainName,
|
||||||
DstIP: netip.Addr{},
|
Host: u.Hostname(),
|
||||||
DstPort: port,
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -1,29 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Addition func(metadata *C.Metadata)
|
|
||||||
|
|
||||||
func (a Addition) Apply(metadata *C.Metadata) {
|
|
||||||
a(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithInName(name string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.InName = name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSpecialRules(specialRules string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.SpecialRules = specialRules
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithSpecialProxy(specialProxy string) Addition {
|
|
||||||
return func(metadata *C.Metadata) {
|
|
||||||
metadata.SpecialProxy = specialProxy
|
|
||||||
}
|
|
||||||
}
|
|
@ -9,20 +9,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn, additions ...Addition) *context.ConnContext {
|
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(source); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -9,19 +9,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) *context.ConnContext {
|
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPS
|
metadata.Type = C.HTTPCONNECT
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -1,26 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/tfo-go"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
lc = tfo.ListenConfig{
|
|
||||||
DisableTFO: true,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetTfo(open bool) {
|
|
||||||
lc.DisableTFO = !open
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
|
||||||
return lc.Listen(ctx, network, address)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Listen(network, address string) (net.Listener, error) {
|
|
||||||
return ListenContext(context.Background(), network, address)
|
|
||||||
}
|
|
22
adapter/inbound/mitm.go
Normal file
22
adapter/inbound/mitm.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/context"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewMitm receive mitm request and return MitmContext
|
||||||
|
func NewMitm(target socks5.Addr, source net.Addr, userAgent string, conn net.Conn) *context.ConnContext {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = C.TCP
|
||||||
|
metadata.Type = C.MITM
|
||||||
|
metadata.UserAgent = userAgent
|
||||||
|
if ip, port, err := parseAddr(source.String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
return context.NewConnContext(conn, metadata)
|
||||||
|
}
|
@ -17,26 +17,17 @@ func (s *PacketAdapter) Metadata() *C.Metadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) C.PacketAdapter {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
|
||||||
if ip, port, err := parseAddr(p.InAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &PacketAdapter{
|
return &PacketAdapter{
|
||||||
packet,
|
UDPPacket: packet,
|
||||||
metadata,
|
metadata: metadata,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,6 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -10,41 +9,14 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) *context.ConnContext {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
for _, addition := range additions {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
addition.Apply(metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
}
|
}
|
||||||
if ip, port, err := parseAddr(conn.LocalAddr()); err == nil {
|
|
||||||
metadata.InIP = ip
|
|
||||||
metadata.InPort = port
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|
||||||
metadata := &C.Metadata{}
|
|
||||||
metadata.NetWork = C.TCP
|
|
||||||
metadata.Type = C.INNER
|
|
||||||
metadata.DNSMode = C.DNSNormal
|
|
||||||
metadata.Host = host
|
|
||||||
metadata.Process = C.ClashName
|
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
|
||||||
metadata.DstPort = port
|
|
||||||
if host == "" {
|
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@ -14,7 +13,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{}
|
metadata := &C.Metadata{
|
||||||
|
AddrType: int(target[0]),
|
||||||
|
}
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -25,8 +26,7 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
||||||
metadata.DstPort = strconv.Itoa((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])
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv6len]))
|
||||||
metadata.DstIP = ip6.Unmap()
|
|
||||||
metadata.DstPort = strconv.Itoa((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]))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,33 +44,29 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
host = strings.TrimRight(host, ".")
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Host: host,
|
AddrType: C.AtypDomainName,
|
||||||
DstIP: netip.Addr{},
|
Host: host,
|
||||||
DstPort: port,
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
ip, err := netip.ParseAddr(host)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
switch {
|
||||||
|
case ip.Is6():
|
||||||
|
metadata.AddrType = C.AtypIPv6
|
||||||
|
default:
|
||||||
|
metadata.AddrType = C.AtypIPv4
|
||||||
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
|
func parseAddr(addr string) (netip.Addr, string, error) {
|
||||||
// Filter when net.Addr interface is nil
|
host, port, err := net.SplitHostPort(addr)
|
||||||
if addr == nil {
|
|
||||||
return netip.Addr{}, "", errors.New("nil addr")
|
|
||||||
}
|
|
||||||
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
|
|
||||||
ip, port, err := parseAddr(rawAddr.RawAddr())
|
|
||||||
if err == nil {
|
|
||||||
return ip, port, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addrStr := addr.String()
|
|
||||||
host, port, err := net.SplitHostPort(addrStr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return netip.Addr{}, "", err
|
return netip.Addr{}, "", err
|
||||||
}
|
}
|
||||||
|
@ -4,26 +4,20 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
name string
|
name string
|
||||||
addr string
|
addr string
|
||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
xudp bool
|
rmark int
|
||||||
tfo bool
|
|
||||||
rmark int
|
|
||||||
id string
|
|
||||||
prefer C.DNSPrefer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@ -31,74 +25,35 @@ func (b *Base) Name() string {
|
|||||||
return b.name
|
return b.name
|
||||||
}
|
}
|
||||||
|
|
||||||
// Id implements C.ProxyAdapter
|
|
||||||
func (b *Base) Id() string {
|
|
||||||
if b.id == "" {
|
|
||||||
b.id = utils.NewUUIDV6().String()
|
|
||||||
}
|
|
||||||
|
|
||||||
return b.id
|
|
||||||
}
|
|
||||||
|
|
||||||
// Type implements C.ProxyAdapter
|
// Type implements C.ProxyAdapter
|
||||||
func (b *Base) Type() C.AdapterType {
|
func (b *Base) Type() C.AdapterType {
|
||||||
return b.tp
|
return b.tp
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (b *Base) StreamConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
||||||
return c, errors.New("no support")
|
return c, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
return nil, errors.New("no support")
|
func (b *Base) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
||||||
}
|
return c, errors.New("no support")
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (b *Base) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(_ context.Context, _ *C.Metadata, _ ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (b *Base) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportWithDialer() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportUOT() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (b *Base) SupportUDP() bool {
|
func (b *Base) SupportUDP() bool {
|
||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportXUDP implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportXUDP() bool {
|
|
||||||
return b.xudp
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportTFO implements C.ProxyAdapter
|
|
||||||
func (b *Base) SupportTFO() bool {
|
|
||||||
return b.tfo
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
"type": b.Type().String(),
|
"type": b.Type().String(),
|
||||||
"id": b.Id(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,7 +63,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (b *Base) Unwrap(_ *C.Metadata) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,30 +77,12 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
||||||
}
|
}
|
||||||
|
|
||||||
switch b.prefer {
|
|
||||||
case C.IPv4Only:
|
|
||||||
opts = append(opts, dialer.WithOnlySingleStack(true))
|
|
||||||
case C.IPv6Only:
|
|
||||||
opts = append(opts, dialer.WithOnlySingleStack(false))
|
|
||||||
case C.IPv4Prefer:
|
|
||||||
opts = append(opts, dialer.WithPreferIPv4())
|
|
||||||
case C.IPv6Prefer:
|
|
||||||
opts = append(opts, dialer.WithPreferIPv6())
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
if b.tfo {
|
|
||||||
opts = append(opts, dialer.WithTFO(true))
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
TFO bool `proxy:"tfo,omitempty" group:"tfo,omitempty"`
|
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@ -153,35 +90,24 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
XUDP bool
|
|
||||||
TFO bool
|
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
Prefer C.DNSPrefer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBase(opt BaseOption) *Base {
|
func NewBase(opt BaseOption) *Base {
|
||||||
return &Base{
|
return &Base{
|
||||||
name: opt.Name,
|
name: opt.Name,
|
||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
xudp: opt.XUDP,
|
iface: opt.Interface,
|
||||||
tfo: opt.TFO,
|
rmark: opt.RoutingMark,
|
||||||
iface: opt.Interface,
|
|
||||||
rmark: opt.RoutingMark,
|
|
||||||
prefer: opt.Prefer,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
N.ExtendedConn
|
net.Conn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
actualRemoteDestination string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *conn) RemoteDestination() string {
|
|
||||||
return c.actualRemoteDestination
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -194,24 +120,13 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *conn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{N.NewExtendedConn(c), []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
return &conn{c, []string{a.Name()}}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
adapterName string
|
|
||||||
connID string
|
|
||||||
actualRemoteDestination string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) RemoteDestination() string {
|
|
||||||
return c.actualRemoteDestination
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -224,23 +139,40 @@ 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 {
|
func NewPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
lAddr := c.PacketConn.LocalAddr()
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
type wrapConn struct {
|
||||||
return &packetConn{pc, []string{a.Name()}, a.Name(), utils.NewUUIDV4().String(), parseRemoteDestination(a.Addr())}
|
net.PacketConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
func (*wrapConn) Read([]byte) (int, error) {
|
||||||
if dst, _, err := net.SplitHostPort(addr); err == nil {
|
return 0, io.EOF
|
||||||
return dst
|
}
|
||||||
} else {
|
|
||||||
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
func (*wrapConn) Write([]byte) (int, error) {
|
||||||
return dst
|
return 0, io.EOF
|
||||||
} else {
|
}
|
||||||
return ""
|
|
||||||
}
|
func (*wrapConn) RemoteAddr() net.Addr {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func WrapConn(packetConn net.PacketConn) net.Conn {
|
||||||
|
return &wrapConn{
|
||||||
|
PacketConn: packetConn,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IsPacketConn(c net.Conn) bool {
|
||||||
|
if _, ok := c.(net.PacketConn); !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
|
||||||
|
return ua.Net == "unixgram"
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
@ -3,9 +3,9 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -15,23 +15,31 @@ type Direct struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithDirect())
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
if !metadata.DstIP.IsValid() && c.RemoteAddr() != nil {
|
||||||
|
if h, _, err := net.SplitHostPort(c.RemoteAddr().String()); err == nil {
|
||||||
|
metadata.DstIP = netip.MustParseAddr(h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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, _ *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.WithResolver(resolver.DefaultResolver))
|
opts = append(opts, dialer.WithDirect())
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", metadata.DstIP), "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(&directPacketConn{pc}, d), nil
|
return NewPacketConn(&directPacketConn{pc}, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type directPacketConn struct {
|
type directPacketConn struct {
|
||||||
@ -41,21 +49,9 @@ type directPacketConn struct {
|
|||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "DIRECT",
|
name: "DIRECT",
|
||||||
tp: C.Direct,
|
tp: C.Direct,
|
||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCompatible() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "COMPATIBLE",
|
|
||||||
tp: C.Compatible,
|
|
||||||
udp: true,
|
|
||||||
prefer: C.DualStack,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -23,30 +22,25 @@ type Http struct {
|
|||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
option *HttpOption
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HttpOption struct {
|
type HttpOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UserName string `proxy:"username,omitempty"`
|
UserName string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
err := cc.Handshake()
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
@ -61,20 +55,13 @@ func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return h.DialContextWithDialer(ctx, dialer.NewDialer(h.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -84,11 +71,6 @@ func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metad
|
|||||||
return NewConn(c, h), nil
|
return NewConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (h *Http) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
req := &http.Request{
|
req := &http.Request{
|
||||||
@ -102,18 +84,15 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
//增加headers
|
|
||||||
if len(h.option.Headers) != 0 {
|
|
||||||
for key, value := range h.option.Headers {
|
|
||||||
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
|
||||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if metadata.Type == C.MITM {
|
||||||
|
req.Header.Set("Origin-Request-Source-Address", metadata.SourceAddress())
|
||||||
|
}
|
||||||
|
|
||||||
if err := req.Write(rw); err != nil {
|
if err := req.Write(rw); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -142,42 +121,29 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHttp(option HttpOption) (*Http, error) {
|
func NewHttp(option HttpOption) *Http {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
sni := option.Server
|
sni := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
if len(option.Fingerprint) == 0 {
|
tlsConfig = &tls.Config{
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(&tls.Config{
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
ServerName: sni,
|
||||||
ServerName: sni,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
ServerName: sni,
|
|
||||||
}, option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
return &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
option: &option,
|
}
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
@ -1,344 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/quic-go"
|
|
||||||
"github.com/metacubex/quic-go/congestion"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/core"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
|
||||||
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
mbpsToBps = 125000
|
|
||||||
|
|
||||||
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
|
||||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
|
||||||
|
|
||||||
DefaultALPN = "hysteria"
|
|
||||||
DefaultProtocol = "udp"
|
|
||||||
DefaultHopInterval = 10
|
|
||||||
)
|
|
||||||
|
|
||||||
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
|
||||||
|
|
||||||
type Hysteria struct {
|
|
||||||
*Base
|
|
||||||
|
|
||||||
client *core.Client
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
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 {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(tcpConn, h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
|
||||||
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)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
udpConn, err := h.client.DialUDP(&hdc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type HysteriaOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port,omitempty"`
|
|
||||||
Ports string `proxy:"ports,omitempty"`
|
|
||||||
Protocol string `proxy:"protocol,omitempty"`
|
|
||||||
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
|
||||||
Up string `proxy:"up"`
|
|
||||||
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
|
||||||
Down string `proxy:"down"`
|
|
||||||
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
|
||||||
Auth string `proxy:"auth,omitempty"`
|
|
||||||
AuthString string `proxy:"auth-str,omitempty"`
|
|
||||||
Obfs string `proxy:"obfs,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"`
|
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
|
||||||
HopInterval int `proxy:"hop-interval,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
|
||||||
var up, down uint64
|
|
||||||
up = stringToBps(c.Up)
|
|
||||||
if up == 0 {
|
|
||||||
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
|
||||||
}
|
|
||||||
|
|
||||||
down = stringToBps(c.Down)
|
|
||||||
if down == 0 {
|
|
||||||
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
|
||||||
}
|
|
||||||
|
|
||||||
return up, down, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
|
||||||
clientTransport := &transport.ClientTransport{
|
|
||||||
Dialer: &net.Dialer{
|
|
||||||
Timeout: 8 * time.Second,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
ports := option.Ports
|
|
||||||
|
|
||||||
serverName := option.Server
|
|
||||||
if option.SNI != "" {
|
|
||||||
serverName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
|
|
||||||
var bs []byte
|
|
||||||
var err error
|
|
||||||
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 {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
tlsConfig.NextProtos = option.ALPN
|
|
||||||
} else {
|
|
||||||
tlsConfig.NextProtos = []string{DefaultALPN}
|
|
||||||
}
|
|
||||||
quicConfig := &quic.Config{
|
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
KeepAlivePeriod: 10 * time.Second,
|
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
|
||||||
EnableDatagrams: true,
|
|
||||||
}
|
|
||||||
if option.ObfsProtocol != "" {
|
|
||||||
option.Protocol = option.ObfsProtocol
|
|
||||||
}
|
|
||||||
if option.Protocol == "" {
|
|
||||||
option.Protocol = DefaultProtocol
|
|
||||||
}
|
|
||||||
if option.HopInterval == 0 {
|
|
||||||
option.HopInterval = DefaultHopInterval
|
|
||||||
}
|
|
||||||
hopInterval := time.Duration(int64(option.HopInterval)) * time.Second
|
|
||||||
if option.ReceiveWindow == 0 {
|
|
||||||
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
|
||||||
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
|
||||||
}
|
|
||||||
if option.ReceiveWindow == 0 {
|
|
||||||
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow / 10
|
|
||||||
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
|
||||||
}
|
|
||||||
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
|
||||||
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
|
||||||
}
|
|
||||||
|
|
||||||
var auth = []byte(option.AuthString)
|
|
||||||
if option.Auth != "" {
|
|
||||||
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var obfuscator obfs.Obfuscator
|
|
||||||
if len(option.Obfs) > 0 {
|
|
||||||
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
|
||||||
}
|
|
||||||
|
|
||||||
up, down, err := option.Speed()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if option.UpSpeed != 0 {
|
|
||||||
up = uint64(option.UpSpeed * mbpsToBps)
|
|
||||||
}
|
|
||||||
if option.DownSpeed != 0 {
|
|
||||||
down = uint64(option.DownSpeed * mbpsToBps)
|
|
||||||
}
|
|
||||||
client, err := core.NewClient(
|
|
||||||
addr, ports, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
|
||||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
|
||||||
}, obfuscator, hopInterval, option.FastOpen,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
|
||||||
}
|
|
||||||
return &Hysteria{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Hysteria,
|
|
||||||
udp: true,
|
|
||||||
tfo: option.FastOpen,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
client: client,
|
|
||||||
}, 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 {
|
|
||||||
core.UDPConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
b, addrStr, err := c.UDPConn.ReadFrom()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n = copy(p, b)
|
|
||||||
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n = len(p)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type hyDialerWithContext struct {
|
|
||||||
hyDialer func(network string) (net.PacketConn, error)
|
|
||||||
ctx context.Context
|
|
||||||
remoteAddr func(host string) (net.Addr, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, error) {
|
|
||||||
network := "udp"
|
|
||||||
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
|
||||||
network = dialer.ParseNetwork(network, addrPort.Addr())
|
|
||||||
}
|
|
||||||
return h.hyDialer(network)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *hyDialerWithContext) Context() context.Context {
|
|
||||||
return h.ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *hyDialerWithContext) RemoteAddr(host string) (net.Addr, error) {
|
|
||||||
return h.remoteAddr(host)
|
|
||||||
}
|
|
49
adapter/outbound/mitm.go
Normal file
49
adapter/outbound/mitm.go
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Mitm struct {
|
||||||
|
*Base
|
||||||
|
serverAddr *net.TCPAddr
|
||||||
|
httpProxyClient *Http
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (m *Mitm) DialContext(_ context.Context, metadata *C.Metadata, _ ...dialer.Option) (C.Conn, error) {
|
||||||
|
c, err := net.DialTCP("tcp", nil, m.serverAddr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = c.SetKeepAlive(true)
|
||||||
|
_ = c.SetKeepAlivePeriod(60 * time.Second)
|
||||||
|
|
||||||
|
metadata.Type = C.MITM
|
||||||
|
|
||||||
|
hc, err := m.httpProxyClient.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
_ = c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(hc, m), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMitm(serverAddr string) *Mitm {
|
||||||
|
tcpAddr, _ := net.ResolveTCPAddr("tcp", serverAddr)
|
||||||
|
return &Mitm{
|
||||||
|
Base: &Base{
|
||||||
|
name: "Mitm",
|
||||||
|
tp: C.Mitm,
|
||||||
|
},
|
||||||
|
serverAddr: tcpAddr,
|
||||||
|
httpProxyClient: NewHttp(HttpOption{}),
|
||||||
|
}
|
||||||
|
}
|
@ -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,80 +6,84 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
rejectCountLimit = 50
|
||||||
|
rejectDelay = time.Second * 35
|
||||||
|
)
|
||||||
|
|
||||||
|
var rejectCounter = cache.NewLRUCache[string, int](cache.WithAge[string, int](15), cache.WithStale[string, int](false), cache.WithSize[string, int](512))
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
key := metadata.RemoteAddress()
|
||||||
|
|
||||||
|
count, existed := rejectCounter.Get(key)
|
||||||
|
if !existed {
|
||||||
|
count = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
count = count + 1
|
||||||
|
|
||||||
|
rejectCounter.Set(key, count)
|
||||||
|
|
||||||
|
if count > rejectCountLimit {
|
||||||
|
c, _ := net.Pipe()
|
||||||
|
|
||||||
|
_ = c.SetDeadline(time.Now().Add(rejectDelay))
|
||||||
|
|
||||||
|
return NewConn(c, 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 {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "REJECT",
|
name: "REJECT",
|
||||||
tp: C.Reject,
|
tp: C.Reject,
|
||||||
udp: true,
|
udp: true,
|
||||||
prefer: C.DualStack,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPass() *Reject {
|
|
||||||
return &Reject{
|
|
||||||
Base: &Base{
|
|
||||||
name: "PASS",
|
|
||||||
tp: C.Pass,
|
|
||||||
udp: true,
|
|
||||||
prefer: C.DualStack,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw nopConn) Read(b []byte) (int, error) {
|
func (rw *nopConn) Read(b []byte) (int, error) {
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error {
|
func (rw *nopConn) Write(b []byte) (int, error) {
|
||||||
return io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw nopConn) Write(b []byte) (int, error) {
|
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error {
|
func (rw *nopConn) Close() error { return nil }
|
||||||
return io.EOF
|
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
||||||
}
|
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) Close() error { return nil }
|
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
||||||
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
||||||
func (npc nopPacketConn) Close() error { return nil }
|
func (npc *nopPacketConn) Close() error { return nil }
|
||||||
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
||||||
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
@ -6,52 +6,36 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/restls"
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
shadowtls "github.com/Dreamacro/clash/transport/sing-shadowtls"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
|
||||||
restlsC "github.com/3andne/restls-client-go"
|
|
||||||
shadowsocks "github.com/metacubex/sing-shadowsocks"
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
"github.com/sagernet/sing/common/uot"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
method shadowsocks.Method
|
cipher core.Cipher
|
||||||
|
|
||||||
option *ShadowSocksOption
|
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
shadowTLSOption *shadowtls.ShadowTLSOption
|
|
||||||
restlsConfig *restlsC.Config
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
|
||||||
UDPOverTCPVersion int `proxy:"udp-over-tcp-version,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -64,37 +48,13 @@ type v2rayObfsOption struct {
|
|||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
Path string `obfs:"path,omitempty"`
|
Path string `obfs:"path,omitempty"`
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type shadowTLSOption struct {
|
|
||||||
Password string `obfs:"password"`
|
|
||||||
Host string `obfs:"host"`
|
|
||||||
Fingerprint string `obfs:"fingerprint,omitempty"`
|
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
|
||||||
Version int `obfs:"version,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type restlsOption struct {
|
|
||||||
Password string `obfs:"password"`
|
|
||||||
Host string `obfs:"host"`
|
|
||||||
VersionHint string `obfs:"version-hint"`
|
|
||||||
RestlsScript string `obfs:"restls-script,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
// fix tls handshake not timeout
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return ss.StreamConnContext(ctx, c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
useEarly := false
|
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@ -107,124 +67,68 @@ func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metada
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
case shadowtls.Mode:
|
|
||||||
var err error
|
|
||||||
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
useEarly = true
|
|
||||||
case restls.Mode:
|
|
||||||
var err error
|
|
||||||
c, err = restls.NewRestls(ctx, c, ss.restlsConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
|
|
||||||
}
|
|
||||||
useEarly = true
|
|
||||||
}
|
}
|
||||||
useEarly = useEarly || N.NeedHandshake(c)
|
c = ss.cipher.StreamConn(c)
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
_, err := c.Write(serializesSocksAddr(metadata))
|
||||||
uotDestination := uot.RequestDestination(uint8(ss.option.UDPOverTCPVersion))
|
return c, err
|
||||||
if useEarly {
|
}
|
||||||
return ss.method.DialEarlyConn(c, uotDestination), nil
|
|
||||||
} else {
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
return ss.method.DialConn(c, uotDestination)
|
func (ss *ShadowSocks) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
||||||
}
|
if !IsPacketConn(c) {
|
||||||
|
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ss.addr)
|
||||||
}
|
}
|
||||||
if useEarly {
|
|
||||||
return ss.method.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
} else {
|
if err != nil {
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pc := ss.cipher.PacketConn(c.(net.PacketConn))
|
||||||
|
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = ss.StreamConnContext(ctx, c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return ss.ListenPacketWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if ss.option.UDPOverTCP {
|
|
||||||
tcpConn, err := ss.DialContextWithDialer(ctx, dialer, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
destination := M.ParseSocksaddr(metadata.RemoteAddress())
|
|
||||||
if ss.option.UDPOverTCPVersion == 1 {
|
|
||||||
return newPacketConn(uot.NewConn(tcpConn, uot.Request{Destination: destination}), ss), nil
|
|
||||||
} else {
|
|
||||||
return newPacketConn(uot.NewLazyConn(tcpConn, uot.Request{Destination: destination}), ss), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ss.addr, ss.prefer)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
c, err := ss.StreamPacketConn(WrapConn(pc), metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
_ = pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
|
||||||
return newPacketConn(pc, ss), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
return NewPacketConn(c.(net.PacketConn), ss), nil
|
||||||
func (ss *ShadowSocks) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if ss.option.UDPOverTCP {
|
|
||||||
destination := M.ParseSocksaddr(metadata.RemoteAddress())
|
|
||||||
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
|
||||||
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), ss), nil
|
|
||||||
} else {
|
|
||||||
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), ss), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) SupportUOT() bool {
|
|
||||||
return ss.option.UDPOverTCP
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
method, err := shadowimpl.FetchMethod(option.Cipher, option.Password, time.Now)
|
cipher := option.Cipher
|
||||||
|
password := option.Password
|
||||||
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
|
||||||
var restlsConfig *restlsC.Config
|
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@ -260,64 +164,22 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
v2rayOption.TLS = true
|
v2rayOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
}
|
}
|
||||||
} else if option.Plugin == shadowtls.Mode {
|
|
||||||
obfsMode = shadowtls.Mode
|
|
||||||
opt := &shadowTLSOption{
|
|
||||||
Version: 2,
|
|
||||||
}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, opt); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
|
||||||
Password: opt.Password,
|
|
||||||
Host: opt.Host,
|
|
||||||
Fingerprint: opt.Fingerprint,
|
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
|
||||||
SkipCertVerify: opt.SkipCertVerify,
|
|
||||||
Version: opt.Version,
|
|
||||||
}
|
|
||||||
} else if option.Plugin == restls.Mode {
|
|
||||||
obfsMode = restls.Mode
|
|
||||||
restlsOpt := &restlsOption{}
|
|
||||||
if err := decoder.Decode(option.PluginOpts, restlsOpt); err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
restlsConfig, err = restlsC.NewRestlsConfig(restlsOpt.Host, restlsOpt.Password, restlsOpt.VersionHint, restlsOpt.RestlsScript, option.ClientFingerprint)
|
|
||||||
restlsConfig.SessionTicketsDisabled = true
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
switch option.UDPOverTCPVersion {
|
|
||||||
case uot.Version, uot.LegacyVersion:
|
|
||||||
case 0:
|
|
||||||
option.UDPOverTCPVersion = uot.Version
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
method: method,
|
cipher: ciph,
|
||||||
|
|
||||||
option: &option,
|
obfsMode: obfsMode,
|
||||||
obfsMode: obfsMode,
|
v2rayOption: v2rayOption,
|
||||||
v2rayOption: v2rayOption,
|
obfsOption: obfsOption,
|
||||||
obfsOption: obfsOption,
|
|
||||||
shadowTLSOption: shadowTLSOpt,
|
|
||||||
restlsConfig: restlsConfig,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -58,22 +58,31 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
||||||
return ssr.DialContextWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
if !IsPacketConn(c) {
|
||||||
|
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ssr.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ssr.addr)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := ssr.cipher.PacketConn(c.(net.PacketConn))
|
||||||
|
pc = ssr.protocol.PacketConn(pc)
|
||||||
|
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConn(c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
@ -81,29 +90,18 @@ func (ssr *ShadowSocksR) DialContextWithDialer(ctx context.Context, dialer C.Dia
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return ssr.ListenPacketWithDialer(ctx, dialer.NewDialer(ssr.Base.DialOptions(opts...)...), metadata)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
addr, err := resolveUDPAddrWithPrefer(ctx, "udp", ssr.addr, ssr.prefer)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
c, err := ssr.StreamPacketConn(WrapConn(pc), metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
_ = pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc = ssr.cipher.PacketConn(pc)
|
return NewPacketConn(c.(net.PacketConn), ssr), nil
|
||||||
pc = ssr.protocol.PacketConn(pc)
|
|
||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
@ -159,14 +157,12 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
|
|
||||||
return &ShadowSocksR{
|
return &ShadowSocksR{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -53,15 +53,23 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConn(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 {
|
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
func (s *Snell) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
|
err := snell.WriteUDPHeader(c, s.version)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return WrapConn(snell.PacketConn(c)), nil
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
if s.version == snell.Version2 && len(opts) == 0 {
|
if s.version == snell.Version2 && len(opts) == 0 {
|
||||||
@ -72,26 +80,19 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
||||||
c.Close()
|
_ = c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.DialContextWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConn(c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
@ -99,35 +100,19 @@ func (s *Snell) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return s.ListenPacketWithDialer(ctx, dialer.NewDialer(s.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (s *Snell) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
|
||||||
|
|
||||||
err = snell.WriteUDPHeader(c, s.version)
|
pc, err := s.StreamPacketConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
_ = c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := snell.PacketConn(c)
|
return NewPacketConn(pc.(net.PacketConn), s), nil
|
||||||
return newPacketConn(pc, s), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (s *Snell) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (s *Snell) SupportUOT() bool {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
@ -163,14 +148,12 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
|
|
||||||
s := &Snell{
|
s := &Snell{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -10,7 +10,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -34,19 +33,63 @@ type Socks5Option struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
c, _, err = ss.streamConn(c, metadata)
|
||||||
|
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) StreamSocks5PacketConn(c net.Conn, pc net.PacketConn, metadata *C.Metadata) (net.PacketConn, error) {
|
||||||
|
if c == nil {
|
||||||
|
return pc, fmt.Errorf("%s connect error: parameter net.Conn is nil", ss.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if pc == nil {
|
||||||
|
return pc, fmt.Errorf("%s connect error: parameter net.PacketConn is nil", ss.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
cc, bindAddr, err := ss.streamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c = cc
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_, _ = io.Copy(io.Discard, c)
|
||||||
|
_ = c.Close()
|
||||||
|
// A UDP association terminates when the TCP connection that the UDP
|
||||||
|
// ASSOCIATE request arrived on terminates. RFC1928
|
||||||
|
_ = pc.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Support unspecified UDP bind address.
|
||||||
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
return pc, errors.New("invalid UDP bind address")
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return pc, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
return &socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) streamConn(c net.Conn, metadata *C.Metadata) (_ net.Conn, bindAddr socks5.Addr, err error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
err := cc.Handshake()
|
||||||
defer cancel()
|
|
||||||
err := cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return c, nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,28 +100,25 @@ func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
Password: ss.pass,
|
Password: ss.pass,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
|
||||||
return nil, err
|
if metadata.NetWork == C.UDP {
|
||||||
|
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
|
} else {
|
||||||
|
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user)
|
||||||
}
|
}
|
||||||
return c, nil
|
|
||||||
|
return c, bindAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
return ss.DialContextWithDialer(ctx, dialer.NewDialer(ss.Base.DialOptions(opts...)...), metadata)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -88,111 +128,54 @@ func (ss *Socks5) DialContextWithDialer(ctx context.Context, dialer C.Dialer, me
|
|||||||
return NewConn(c, ss), nil
|
return NewConn(c, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (ss *Socks5) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ss.tls {
|
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
|
||||||
defer cancel()
|
|
||||||
err = cc.HandshakeContext(ctx)
|
|
||||||
c = cc
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
|
||||||
if ss.user != "" {
|
|
||||||
user = &socks5.User{
|
|
||||||
Username: ss.user,
|
|
||||||
Password: ss.pass,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
pc, err = ss.StreamSocks5PacketConn(c, pc, metadata)
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("client hanshake error: %w", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
err = errors.New("invalid UDP bind address")
|
|
||||||
return
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr(ctx, "udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, dialer.ParseNetwork("udp", bindUDPAddr.AddrPort().Addr()), "", ss.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
return NewPacketConn(pc, ss), nil
|
||||||
io.Copy(io.Discard, c)
|
|
||||||
c.Close()
|
|
||||||
// A UDP association terminates when the TCP connection that the UDP
|
|
||||||
// ASSOCIATE request arrived on terminates. RFC1928
|
|
||||||
pc.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
func NewSocks5(option Socks5Option) *Socks5 {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
skipCertVerify: option.SkipCertVerify,
|
skipCertVerify: option.SkipCertVerify,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}, nil
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type socksPacketConn struct {
|
type socksPacketConn struct {
|
||||||
@ -230,6 +213,6 @@ func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (uc *socksPacketConn) Close() error {
|
func (uc *socksPacketConn) Close() error {
|
||||||
uc.tcpConn.Close()
|
_ = uc.tcpConn.Close()
|
||||||
return uc.PacketConn.Close()
|
return uc.PacketConn.Close()
|
||||||
}
|
}
|
||||||
|
@ -8,13 +8,13 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
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"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@ -25,29 +25,24 @@ type Trojan struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *http2.Transport
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
@ -77,16 +72,10 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
return t.instance.StreamConn(c)
|
return t.instance.StreamConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
func (t *Trojan) trojanStream(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && len(t.option.ClientFingerprint) == 0 {
|
|
||||||
t.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
if t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig, t.realityConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
} else {
|
} else {
|
||||||
c, err = t.plainStream(c)
|
c, err = t.plainStream(c)
|
||||||
}
|
}
|
||||||
@ -95,55 +84,69 @@ func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
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)
|
c, err = t.instance.PrepareXTLSConn(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return c, 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 N.NewExtendedConn(c), err
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
return t.trojanStream(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
var err error
|
||||||
|
c, err = t.trojanStream(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return WrapConn(pc), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
|
var c net.Conn
|
||||||
|
|
||||||
// gun transport
|
// gun transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = t.instance.PresetXTLSConn(c)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.instance.PrepareXTLSConn(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Close()
|
|
||||||
return nil, err
|
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()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, t), nil
|
return NewConn(c, t), nil
|
||||||
}
|
}
|
||||||
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
c, err = t.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -157,89 +160,64 @@ func (t *Trojan) DialContextWithDialer(ctx context.Context, dialer C.Dialer, met
|
|||||||
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
|
|
||||||
// grpc transport
|
// gun transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.instance.PrepareXTLSConn(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
pc := t.instance.PacketConn(c)
|
||||||
return newPacketConn(pc, t), err
|
|
||||||
}
|
|
||||||
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
return NewPacketConn(pc, t), nil
|
||||||
func (t *Trojan) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
}
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr)
|
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
c, err = t.plainStream(c)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.StreamPacketConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
return NewPacketConn(c.(net.PacketConn), t), nil
|
||||||
return newPacketConn(pc, t), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
return newPacketConn(pc, t), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) SupportUOT() bool {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
tOption := &trojan.Option{
|
||||||
Password: option.Password,
|
Password: option.Password,
|
||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
|
||||||
ClientFingerprint: option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
case "", "tcp":
|
option.Flow = option.Flow[:16]
|
||||||
if len(option.Flow) >= 16 {
|
switch option.Flow {
|
||||||
option.Flow = option.Flow[:16]
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
switch option.Flow {
|
tOption.Flow = option.Flow
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
default:
|
||||||
tOption.Flow = option.Flow
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,26 +227,17 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
|
|
||||||
t := &Trojan{
|
t := &Trojan{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
tfo: option.TFO,
|
iface: option.Interface,
|
||||||
iface: option.Interface,
|
rmark: option.RoutingMark,
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
|
||||||
t.realityConfig, err = option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
tOption.Reality = t.realityConfig
|
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
||||||
@ -286,17 +255,12 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
if t.option.Flow != "" {
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
var err error
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig, tOption.ClientFingerprint, t.realityConfig)
|
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
|
@ -1,262 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/metacubex/quic-go"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/tuic"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Tuic struct {
|
|
||||||
*Base
|
|
||||||
client *tuic.PoolClient
|
|
||||||
}
|
|
||||||
|
|
||||||
type TuicOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Token string `proxy:"token"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
|
||||||
ReduceRtt bool `proxy:"reduce-rtt,omitempty"`
|
|
||||||
RequestTimeout int `proxy:"request-timeout,omitempty"`
|
|
||||||
UdpRelayMode string `proxy:"udp-relay-mode,omitempty"`
|
|
||||||
CongestionController string `proxy:"congestion-controller,omitempty"`
|
|
||||||
DisableSni bool `proxy:"disable-sni,omitempty"`
|
|
||||||
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
|
||||||
|
|
||||||
FastOpen bool `proxy:"fast-open,omitempty"`
|
|
||||||
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
CustomCA string `proxy:"ca,omitempty"`
|
|
||||||
CustomCAString string `proxy:"ca-str,omitempty"`
|
|
||||||
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
|
||||||
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
|
||||||
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
|
||||||
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
|
|
||||||
SNI string `proxy:"sni,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
return t.DialContextWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
conn, err := t.client.DialContextWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return NewConn(conn, t), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
return t.ListenPacketWithDialer(ctx, dialer.NewDialer(t.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
pc, err := t.client.ListenPacketWithDialer(ctx, metadata, dialer, t.dialWithDialer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(pc, t), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
|
||||||
func (t *Tuic) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tuic) dial(ctx context.Context, opts ...dialer.Option) (pc net.PacketConn, addr net.Addr, err error) {
|
|
||||||
return t.dialWithDialer(ctx, dialer.NewDialer(opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Tuic) dialWithDialer(ctx context.Context, dialer C.Dialer) (pc net.PacketConn, addr net.Addr, err error) {
|
|
||||||
udpAddr, err := resolveUDPAddrWithPrefer(ctx, "udp", t.addr, t.prefer)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
addr = udpAddr
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTuic(option TuicOption) (*Tuic, error) {
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
|
||||||
serverName := option.Server
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
ServerName: serverName,
|
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
|
||||||
MinVersion: tls.VersionTLS13,
|
|
||||||
}
|
|
||||||
if option.SNI != "" {
|
|
||||||
tlsConfig.ServerName = option.SNI
|
|
||||||
}
|
|
||||||
|
|
||||||
var bs []byte
|
|
||||||
var err error
|
|
||||||
if len(option.CustomCA) > 0 {
|
|
||||||
bs, err = os.ReadFile(option.CustomCA)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("tuic %s load ca error: %w", addr, err)
|
|
||||||
}
|
|
||||||
} else if option.CustomCAString != "" {
|
|
||||||
bs = []byte(option.CustomCAString)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(bs) > 0 {
|
|
||||||
block, _ := pem.Decode(bs)
|
|
||||||
if block == nil {
|
|
||||||
return nil, fmt.Errorf("CA cert is not PEM")
|
|
||||||
}
|
|
||||||
|
|
||||||
fpBytes := sha256.Sum256(block.Bytes)
|
|
||||||
if len(option.Fingerprint) == 0 {
|
|
||||||
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.Fingerprint) != 0 {
|
|
||||||
var err error
|
|
||||||
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.ALPN) > 0 {
|
|
||||||
tlsConfig.NextProtos = option.ALPN
|
|
||||||
} else {
|
|
||||||
tlsConfig.NextProtos = []string{"h3"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.RequestTimeout == 0 {
|
|
||||||
option.RequestTimeout = 8000
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.HeartbeatInterval <= 0 {
|
|
||||||
option.HeartbeatInterval = 10000
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.UdpRelayMode != "quic" {
|
|
||||||
option.UdpRelayMode = "native"
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxUdpRelayPacketSize == 0 {
|
|
||||||
option.MaxUdpRelayPacketSize = 1252
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxOpenStreams == 0 {
|
|
||||||
option.MaxOpenStreams = 100
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize == 0 {
|
|
||||||
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + tuic.PacketOverHead
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.MaxDatagramFrameSize > 1400 {
|
|
||||||
option.MaxDatagramFrameSize = 1400
|
|
||||||
}
|
|
||||||
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - tuic.PacketOverHead
|
|
||||||
|
|
||||||
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
|
||||||
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
|
||||||
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
|
||||||
quicConfig := &quic.Config{
|
|
||||||
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
|
||||||
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
|
||||||
MaxIncomingStreams: quicMaxOpenStreams,
|
|
||||||
MaxIncomingUniStreams: quicMaxOpenStreams,
|
|
||||||
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
|
||||||
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
|
||||||
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
|
|
||||||
EnableDatagrams: true,
|
|
||||||
}
|
|
||||||
if option.ReceiveWindowConn == 0 {
|
|
||||||
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
|
|
||||||
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
|
|
||||||
}
|
|
||||||
if option.ReceiveWindow == 0 {
|
|
||||||
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
|
|
||||||
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(option.Ip) > 0 {
|
|
||||||
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
|
||||||
}
|
|
||||||
host := option.Server
|
|
||||||
if option.DisableSni {
|
|
||||||
host = ""
|
|
||||||
tlsConfig.ServerName = ""
|
|
||||||
}
|
|
||||||
tkn := tuic.GenTKN(option.Token)
|
|
||||||
|
|
||||||
t := &Tuic{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: addr,
|
|
||||||
tp: C.Tuic,
|
|
||||||
udp: true,
|
|
||||||
tfo: option.FastOpen,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
|
||||||
|
|
||||||
// to avoid tuic's "too many open streams", decrease to 0.9x
|
|
||||||
if clientMaxOpenStreams == 100 {
|
|
||||||
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
if clientMaxOpenStreams < 1 {
|
|
||||||
clientMaxOpenStreams = 1
|
|
||||||
}
|
|
||||||
clientOption := &tuic.ClientOption{
|
|
||||||
TlsConfig: tlsConfig,
|
|
||||||
QuicConfig: quicConfig,
|
|
||||||
Host: host,
|
|
||||||
Token: tkn,
|
|
||||||
UdpRelayMode: option.UdpRelayMode,
|
|
||||||
CongestionController: option.CongestionController,
|
|
||||||
ReduceRtt: option.ReduceRtt,
|
|
||||||
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
|
||||||
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
|
||||||
FastOpen: option.FastOpen,
|
|
||||||
MaxOpenStreams: clientMaxOpenStreams,
|
|
||||||
}
|
|
||||||
|
|
||||||
t.client = tuic.NewPoolClient(clientOption)
|
|
||||||
|
|
||||||
return t, nil
|
|
||||||
}
|
|
@ -2,13 +2,8 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
xtls "github.com/xtls/go"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
@ -16,12 +11,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
globalClientSessionCache tls.ClientSessionCache
|
|
||||||
globalClientXSessionCache xtls.ClientSessionCache
|
|
||||||
once sync.Once
|
|
||||||
)
|
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
@ -29,27 +18,12 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getClientSessionCache() tls.ClientSessionCache {
|
|
||||||
once.Do(func() {
|
|
||||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
|
||||||
})
|
|
||||||
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()
|
aType := uint8(metadata.AddrType)
|
||||||
aType := uint8(addrType)
|
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch addrType {
|
switch metadata.AddrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
lenM := uint8(len(metadata.Host))
|
lenM := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
@ -64,69 +38,13 @@ func serializesSocksAddr(metadata *C.Metadata) []byte {
|
|||||||
return bytes.Join(buf, nil)
|
return bytes.Join(buf, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddr(ctx context.Context, network, address string) (*net.UDPAddr, error) {
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveProxyServerHost(ctx, host)
|
ip, err := resolver.ResolveProxyServerHost(host)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolveUDPAddrWithPrefer(ctx context.Context, network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var ip netip.Addr
|
|
||||||
var fallback netip.Addr
|
|
||||||
switch prefer {
|
|
||||||
case C.IPv4Only:
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(ctx, host)
|
|
||||||
case C.IPv6Only:
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(ctx, host)
|
|
||||||
case C.IPv6Prefer:
|
|
||||||
var ips []netip.Addr
|
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
|
||||||
if err == nil {
|
|
||||||
for _, addr := range ips {
|
|
||||||
if addr.Is6() {
|
|
||||||
ip = addr
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if !fallback.IsValid() {
|
|
||||||
fallback = addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// C.IPv4Prefer, C.DualStack and other
|
|
||||||
var ips []netip.Addr
|
|
||||||
ips, err = resolver.LookupIPProxyServerHost(ctx, host)
|
|
||||||
if err == nil {
|
|
||||||
for _, addr := range ips {
|
|
||||||
if addr.Is4() {
|
|
||||||
ip = addr
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if !fallback.IsValid() {
|
|
||||||
fallback = addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !ip.IsValid() && fallback.IsValid() {
|
|
||||||
ip = fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -12,20 +12,14 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmessSing "github.com/sagernet/sing-vmess"
|
"golang.org/x/net/http2"
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -41,47 +35,41 @@ type Vless struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *http2.Transport
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && len(v.option.ClientFingerprint) == 0 {
|
|
||||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
|
if v.option.WSOpts.Path == "" {
|
||||||
|
v.option.WSOpts.Path = v.option.WSPath
|
||||||
|
}
|
||||||
|
if len(v.option.WSOpts.Headers) == 0 {
|
||||||
|
v.option.WSOpts.Headers = v.option.WSHeaders
|
||||||
|
}
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -89,44 +77,29 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
wsOpts.Headers.Add(key, value)
|
header.Add(key, value)
|
||||||
}
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
}
|
}
|
||||||
if v.option.TLS {
|
|
||||||
wsOpts.TLS = true
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
MinVersion: tls.VersionTLS12,
|
|
||||||
ServerName: host,
|
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
wsOpts.TLS = true
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
wsOpts.TLSConfig = &tls.Config{
|
||||||
} else {
|
MinVersion: tls.VersionTLS12,
|
||||||
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
ServerName: host,
|
||||||
if err != nil {
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
return nil, err
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = host
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if host := wsOpts.Headers.Get("Host"); host == "" {
|
|
||||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(wsOpts.Headers)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
|
wsOpts.TLSConfig.ServerName = host
|
||||||
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamWebsocketConn(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
|
||||||
@ -157,7 +130,11 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = vmess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig, v.realityConfig)
|
if v.isXTLSEnabled() {
|
||||||
|
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS And XTLS
|
// handle TLS And XTLS
|
||||||
@ -168,17 +145,40 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
func (v *Vless) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return WrapConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
if v.isLegacyXTLSEnabled() && !isH2 {
|
if v.isXTLSEnabled() {
|
||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
Fingerprint: v.option.Fingerprint,
|
}
|
||||||
|
|
||||||
|
if isH2 {
|
||||||
|
xtlsOpts.NextProtos = []string{"h2"}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
@ -187,13 +187,10 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||||
|
|
||||||
} else if v.option.TLS {
|
} else {
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -206,12 +203,10 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isLegacyXTLSEnabled() bool {
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
return v.client.Addons != nil && v.client.Addons.Flow != vless.XRV
|
return v.client.Addons != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -222,158 +217,88 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vless) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve 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 {
|
||||||
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
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))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return NewPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vless) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
// vless use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err = v.StreamPacketConn(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(c, metadata)
|
return NewPacketConn(c.(net.PacketConn), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
func (v *Vless) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if v.option.XUDP {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: vmessSing.NewXUDPConn(c, M.ParseSocksaddr(metadata.RemoteAddress())),
|
|
||||||
}, v), nil
|
|
||||||
} else if v.option.PacketAddr {
|
|
||||||
return newPacketConn(&threadSafePacketConn{
|
|
||||||
PacketConn: packetaddr.NewConn(&vlessPacketConn{
|
|
||||||
Conn: c, rAddr: metadata.UDPAddr(),
|
|
||||||
}, M.ParseSocksaddr(metadata.RemoteAddress())),
|
|
||||||
}, v), nil
|
|
||||||
}
|
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (v *Vless) SupportUOT() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType() {
|
switch metadata.AddrType {
|
||||||
case socks5.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = vless.AtypIPv4
|
addrType = byte(vless.AtypIPv4)
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case socks5.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
addrType = vless.AtypIPv6
|
addrType = byte(vless.AtypIPv6)
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case socks5.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
addrType = vless.AtypDomainName
|
addrType = byte(vless.AtypDomainName)
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
copy(addr[1:], metadata.Host)
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
@ -381,48 +306,36 @@ func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
|||||||
UDP: metadata.NetWork == C.UDP,
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: uint16(port),
|
Port: uint(port),
|
||||||
Mux: metadata.NetWork == C.UDP && xudp,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type vlessPacketConn struct {
|
type vlessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
|
cache [2]byte
|
||||||
remain int
|
remain int
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
cache [2]byte
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
func (vc *vlessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||||
binary.BigEndian.PutUint16(c.cache[:], uint16(len(payload)))
|
|
||||||
|
|
||||||
if _, err := c.Conn.Write(c.cache[:]); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Conn.Write(payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
total := len(b)
|
total := len(b)
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if total <= maxLength {
|
if total < maxLength {
|
||||||
return c.writePacket(b)
|
return vc.writePacket(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
offset := 0
|
offset := 0
|
||||||
|
for {
|
||||||
for offset < total {
|
|
||||||
cursor := offset + maxLength
|
cursor := offset + maxLength
|
||||||
if cursor > total {
|
if cursor > total {
|
||||||
cursor = total
|
cursor = total
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := c.writePacket(b[offset:cursor])
|
n, err := vc.writePacket(b[offset:cursor])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return offset + n, err
|
return offset + n, err
|
||||||
}
|
}
|
||||||
@ -436,32 +349,33 @@ func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|||||||
return total, nil
|
return total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
c.mux.Lock()
|
vc.mux.Lock()
|
||||||
defer c.mux.Unlock()
|
defer vc.mux.Unlock()
|
||||||
|
|
||||||
if c.remain > 0 {
|
if vc.remain != 0 {
|
||||||
length := len(b)
|
length := len(b)
|
||||||
if c.remain < length {
|
if length > vc.remain {
|
||||||
length = c.remain
|
length = vc.remain
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
n, err := vc.Conn.Read(b[:length])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, c.rAddr, err
|
return 0, vc.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c.remain -= n
|
vc.remain -= n
|
||||||
return n, c.rAddr, nil
|
|
||||||
|
return n, vc.rAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := c.Conn.Read(b[:2]); err != nil {
|
if _, err := vc.Conn.Read(b[:2]); err != nil {
|
||||||
return 0, c.rAddr, err
|
return 0, vc.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
total := int(binary.BigEndian.Uint16(b[:2]))
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, c.rAddr, nil
|
return 0, vc.rAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
length := len(b)
|
length := len(b)
|
||||||
@ -469,13 +383,23 @@ func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
length = total
|
length = total
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
if _, err := io.ReadFull(vc.Conn, b[:length]); err != nil {
|
||||||
return 0, c.rAddr, errors.New("read packet error")
|
return 0, vc.rAddr, errors.New("read packet error")
|
||||||
}
|
}
|
||||||
|
|
||||||
c.remain = total - length
|
vc.remain = total - length
|
||||||
|
|
||||||
return length, c.rAddr, nil
|
return length, vc.rAddr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
||||||
|
binary.BigEndian.PutUint16(vc.cache[:], uint16(len(payload)))
|
||||||
|
|
||||||
|
if _, err := vc.Conn.Write(vc.cache[:]); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return vc.Conn.Write(payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
func NewVless(option VlessOption) (*Vless, error) {
|
||||||
@ -483,9 +407,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
switch option.Flow {
|
||||||
case vless.XRV:
|
|
||||||
log.Warnln("To use %s, ensure your server is upgrade to Xray-core v1.8.0+", vless.XRV)
|
|
||||||
fallthrough
|
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
case vless.XRO, vless.XRD, vless.XRS:
|
||||||
addons = &vless.Addons{
|
addons = &vless.Addons{
|
||||||
Flow: option.Flow,
|
Flow: option.Flow,
|
||||||
@ -495,16 +416,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
|
||||||
case "packetaddr", "packet":
|
|
||||||
option.PacketAddr = true
|
|
||||||
option.XUDP = false
|
|
||||||
default: // https://github.com/XTLS/Xray-core/pull/1567#issuecomment-1407305458
|
|
||||||
if !option.PacketAddr {
|
|
||||||
option.XUDP = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -512,25 +423,16 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
|
|
||||||
v := &Vless{
|
v := &Vless{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
iface: option.Interface,
|
||||||
tfo: option.TFO,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2":
|
case "h2":
|
||||||
if len(option.HTTP2Opts.Host) == 0 {
|
if len(option.HTTP2Opts.Host) == 0 {
|
||||||
@ -547,14 +449,13 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
tlsConfig := tlsC.GetGlobalTLSConfig(&tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
})
|
}
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
if v.option.ServerName == "" {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
@ -564,8 +465,11 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
if v.isXTLSEnabled() {
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
|
} else {
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
@ -3,29 +3,22 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
"golang.org/x/net/http2"
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
|
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
*Base
|
*Base
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
@ -34,36 +27,30 @@ type Vmess struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *gun.TransportWrap
|
transport *http2.Transport
|
||||||
|
|
||||||
realityConfig *tlsC.RealityConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
Fingerprint string `proxy:"fingerprint,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
// TODO: compatible with VMESS WS older version configurations
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
|
||||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
|
||||||
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -91,152 +78,147 @@ type WSOptions struct {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if tlsC.HaveGlobalFingerprint() && (len(v.option.ClientFingerprint) == 0) {
|
|
||||||
v.option.ClientFingerprint = tlsC.GetGlobalFingerprint()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
|
if v.option.WSOpts.Path == "" {
|
||||||
|
v.option.WSOpts.Path = v.option.WSPath
|
||||||
|
}
|
||||||
|
if len(v.option.WSOpts.Headers) == 0 {
|
||||||
|
v.option.WSOpts.Headers = v.option.WSHeaders
|
||||||
|
}
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &clashVMess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Headers: http.Header{},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
|
header := http.Header{}
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
wsOpts.Headers.Add(key, value)
|
header.Add(key, value)
|
||||||
}
|
}
|
||||||
|
wsOpts.Headers = header
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
tlsConfig := &tls.Config{
|
wsOpts.TLSConfig = &tls.Config{
|
||||||
ServerName: host,
|
ServerName: host,
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.Fingerprint) == 0 {
|
|
||||||
wsOpts.TLSConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||||
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamWebsocketConn(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
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
|
||||||
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
http.Header(v.option.HTTPOpts.Headers).Set("Host", convert.RandHost())
|
||||||
|
convert.SetUserAgent(v.option.HTTPOpts.Headers)
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &clashVMess.HTTPConfig{
|
httpOpts := &vmess.HTTPConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Method: v.option.HTTPOpts.Method,
|
Method: v.option.HTTPOpts.Method,
|
||||||
Path: v.option.HTTPOpts.Path,
|
Path: v.option.HTTPOpts.Path,
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
}
|
}
|
||||||
|
|
||||||
c = clashVMess.StreamHTTPConn(c, httpOpts)
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := clashVMess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &clashVMess.H2Config{
|
h2Opts := &vmess.H2Config{
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.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:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &clashVMess.TLSConfig{
|
tlsOpts := &vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
Reality: v.realityConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP {
|
|
||||||
if v.option.XUDP {
|
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
if N.NeedHandshake(c) {
|
}
|
||||||
return v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
func (v *Vmess) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
}
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
} else {
|
if !metadata.Resolved() {
|
||||||
if N.NeedHandshake(c) {
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
return v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
if err != nil {
|
||||||
} else {
|
return c, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
return v.client.DialEarlyConn(c, M.ParseSocksaddr(metadata.RemoteAddress())), nil
|
|
||||||
} else {
|
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
c, err = v.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return c, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return WrapConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -247,30 +229,22 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
return NewConn(c, v), nil
|
||||||
}
|
}
|
||||||
return v.DialContextWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContextWithDialer implements C.ProxyAdapter
|
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConn(c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
@ -278,144 +252,77 @@ func (v *Vmess) DialContextWithDialer(ctx context.Context, dialer C.Dialer, meta
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
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.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 {
|
||||||
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer func(c net.Conn) {
|
defer safeConnClose(c, err)
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
if v.option.XUDP {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = v.client.DialEarlyXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = v.client.DialEarlyPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
return v.ListenPacketWithDialer(ctx, dialer.NewDialer(v.Base.DialOptions(opts...)...), metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketWithDialer implements C.ProxyAdapter
|
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
func (v *Vmess) ListenPacketWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we need a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr)
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer func(c net.Conn) {
|
|
||||||
safeConnClose(c, err)
|
|
||||||
}(c)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = v.StreamPacketConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportWithDialer implements C.ProxyAdapter
|
return NewPacketConn(c.(net.PacketConn), v), nil
|
||||||
func (v *Vmess) SupportWithDialer() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindConn(c)}, v), nil
|
|
||||||
} else if pc, ok := c.(net.PacketConn); ok {
|
|
||||||
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
|
||||||
}
|
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (v *Vmess) SupportUOT() bool {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
var options []vmess.ClientOption
|
client, err := vmess.NewClient(vmess.Config{
|
||||||
if option.GlobalPadding {
|
UUID: option.UUID,
|
||||||
options = append(options, vmess.ClientWithGlobalPadding())
|
AlterID: uint16(option.AlterID),
|
||||||
}
|
Security: security,
|
||||||
if option.AuthenticatedLength {
|
HostName: option.Server,
|
||||||
options = append(options, vmess.ClientWithAuthenticatedLength())
|
Port: strconv.Itoa(option.Port),
|
||||||
}
|
IsAead: option.AlterID == 0,
|
||||||
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.PacketEncoding {
|
|
||||||
case "packetaddr", "packet":
|
|
||||||
option.PacketAddr = true
|
|
||||||
case "xudp":
|
|
||||||
option.XUDP = true
|
|
||||||
}
|
|
||||||
if option.XUDP {
|
|
||||||
option.PacketAddr = false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2", "grpc":
|
case "h2", "grpc":
|
||||||
if !option.TLS {
|
if !option.TLS {
|
||||||
option.TLS = true
|
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
v := &Vmess{
|
v := &Vmess{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
xudp: option.XUDP,
|
iface: option.Interface,
|
||||||
tfo: option.TFO,
|
rmark: option.RoutingMark,
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -437,9 +344,8 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
ClientFingerprint: v.option.ClientFingerprint,
|
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
@ -454,45 +360,46 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
v.gunTLSConfig = tlsConfig
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig, v.option.ClientFingerprint, v.realityConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
v.realityConfig, err = v.option.RealityOpts.Parse()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type threadSafePacketConn struct {
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
net.PacketConn
|
var addrType byte
|
||||||
access sync.Mutex
|
var addr []byte
|
||||||
}
|
switch metadata.AddrType {
|
||||||
|
case C.AtypIPv4:
|
||||||
|
addrType = byte(vmess.AtypIPv4)
|
||||||
|
addr = make([]byte, net.IPv4len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypIPv6:
|
||||||
|
addrType = byte(vmess.AtypIPv6)
|
||||||
|
addr = make([]byte, net.IPv6len)
|
||||||
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
|
case C.AtypDomainName:
|
||||||
|
addrType = byte(vmess.AtypDomainName)
|
||||||
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
|
addr[0] = byte(len(metadata.Host))
|
||||||
|
copy(addr[1:], []byte(metadata.Host))
|
||||||
|
}
|
||||||
|
|
||||||
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
c.access.Lock()
|
return &vmess.DstAddr{
|
||||||
defer c.access.Unlock()
|
UDP: metadata.NetWork == C.UDP,
|
||||||
return c.PacketConn.WriteTo(b, addr)
|
AddrType: addrType,
|
||||||
|
Addr: addr,
|
||||||
|
Port: uint(port),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
access sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteTo implments C.PacketConn.WriteTo
|
func (uc *vmessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||||
// 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) {
|
|
||||||
allowedAddr := uc.rAddr.(*net.UDPAddr)
|
|
||||||
destAddr := addr.(*net.UDPAddr)
|
|
||||||
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
|
|
||||||
return 0, ErrUDPRemoteAddrMismatch
|
|
||||||
}
|
|
||||||
uc.access.Lock()
|
|
||||||
defer uc.access.Unlock()
|
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,269 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
CN "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
wireguard "github.com/metacubex/sing-wireguard"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/debug"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
"github.com/sagernet/wireguard-go/device"
|
|
||||||
)
|
|
||||||
|
|
||||||
type WireGuard struct {
|
|
||||||
*Base
|
|
||||||
bind *wireguard.ClientBind
|
|
||||||
device *device.Device
|
|
||||||
tunDevice wireguard.Device
|
|
||||||
dialer *wgSingDialer
|
|
||||||
startOnce sync.Once
|
|
||||||
startErr error
|
|
||||||
}
|
|
||||||
|
|
||||||
type WireGuardOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
Ip string `proxy:"ip,omitempty"`
|
|
||||||
Ipv6 string `proxy:"ipv6,omitempty"`
|
|
||||||
PrivateKey string `proxy:"private-key"`
|
|
||||||
PublicKey string `proxy:"public-key"`
|
|
||||||
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
|
||||||
Reserved []uint8 `proxy:"reserved,omitempty"`
|
|
||||||
Workers int `proxy:"workers,omitempty"`
|
|
||||||
MTU int `proxy:"mtu,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgSingDialer struct {
|
|
||||||
dialer dialer.Dialer
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ N.Dialer = &wgSingDialer{}
|
|
||||||
|
|
||||||
func (d *wgSingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
|
||||||
return d.dialer.DialContext(ctx, network, destination.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *wgSingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
|
||||||
return d.dialer.ListenPacket(ctx, "udp", "", destination.AddrPort())
|
|
||||||
}
|
|
||||||
|
|
||||||
type wgNetDialer struct {
|
|
||||||
tunDevice wireguard.Device
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ dialer.NetDialer = &wgNetDialer{}
|
|
||||||
|
|
||||||
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
|
||||||
outbound := &WireGuard{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
tp: C.WireGuard,
|
|
||||||
udp: option.UDP,
|
|
||||||
iface: option.Interface,
|
|
||||||
rmark: option.RoutingMark,
|
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
|
||||||
dialer: &wgSingDialer{dialer: dialer.NewDialer()},
|
|
||||||
}
|
|
||||||
runtime.SetFinalizer(outbound, closeWireGuard)
|
|
||||||
|
|
||||||
var reserved [3]uint8
|
|
||||||
if len(option.Reserved) > 0 {
|
|
||||||
if len(option.Reserved) != 3 {
|
|
||||||
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
|
||||||
}
|
|
||||||
reserved[0] = uint8(option.Reserved[0])
|
|
||||||
reserved[1] = uint8(option.Reserved[1])
|
|
||||||
reserved[2] = uint8(option.Reserved[2])
|
|
||||||
}
|
|
||||||
peerAddr := M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
|
||||||
outbound.bind = wireguard.NewClientBind(context.Background(), outbound.dialer, peerAddr, reserved)
|
|
||||||
localPrefixes := make([]netip.Prefix, 0, 2)
|
|
||||||
if len(option.Ip) > 0 {
|
|
||||||
if !strings.Contains(option.Ip, "/") {
|
|
||||||
option.Ip = option.Ip + "/32"
|
|
||||||
}
|
|
||||||
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
|
||||||
localPrefixes = append(localPrefixes, prefix)
|
|
||||||
} else {
|
|
||||||
return nil, E.Cause(err, "ip address parse error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(option.Ipv6) > 0 {
|
|
||||||
if !strings.Contains(option.Ipv6, "/") {
|
|
||||||
option.Ipv6 = option.Ipv6 + "/128"
|
|
||||||
}
|
|
||||||
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
|
||||||
localPrefixes = append(localPrefixes, prefix)
|
|
||||||
} else {
|
|
||||||
return nil, E.Cause(err, "ipv6 address parse error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(localPrefixes) == 0 {
|
|
||||||
return nil, E.New("missing local address")
|
|
||||||
}
|
|
||||||
var privateKey, peerPublicKey, preSharedKey string
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode private key")
|
|
||||||
}
|
|
||||||
privateKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
{
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode peer public key")
|
|
||||||
}
|
|
||||||
peerPublicKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
if option.PreSharedKey != "" {
|
|
||||||
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode pre shared key")
|
|
||||||
}
|
|
||||||
preSharedKey = hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
ipcConf := "private_key=" + privateKey
|
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
|
||||||
ipcConf += "\nendpoint=" + peerAddr.String()
|
|
||||||
if preSharedKey != "" {
|
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
|
||||||
}
|
|
||||||
var has4, has6 bool
|
|
||||||
for _, address := range localPrefixes {
|
|
||||||
if address.Addr().Is4() {
|
|
||||||
has4 = true
|
|
||||||
} else {
|
|
||||||
has6 = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if has4 {
|
|
||||||
ipcConf += "\nallowed_ip=0.0.0.0/0"
|
|
||||||
}
|
|
||||||
if has6 {
|
|
||||||
ipcConf += "\nallowed_ip=::/0"
|
|
||||||
}
|
|
||||||
if option.PersistentKeepalive != 0 {
|
|
||||||
ipcConf += fmt.Sprintf("\npersistent_keepalive_interval=%d", option.PersistentKeepalive)
|
|
||||||
}
|
|
||||||
mtu := option.MTU
|
|
||||||
if mtu == 0 {
|
|
||||||
mtu = 1408
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
outbound.tunDevice, err = wireguard.NewStackDevice(localPrefixes, uint32(mtu))
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "create WireGuard device")
|
|
||||||
}
|
|
||||||
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, &device.Logger{
|
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
|
||||||
log.SingLogger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
|
||||||
},
|
|
||||||
Errorf: func(format string, args ...interface{}) {
|
|
||||||
log.SingLogger.Error(fmt.Sprintf(strings.ToLower(format), args...))
|
|
||||||
},
|
|
||||||
}, option.Workers)
|
|
||||||
if debug.Enabled {
|
|
||||||
log.SingLogger.Trace("created wireguard ipc conf: \n", ipcConf)
|
|
||||||
}
|
|
||||||
err = outbound.device.IpcSet(ipcConf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "setup wireguard")
|
|
||||||
}
|
|
||||||
//err = outbound.tunDevice.Start()
|
|
||||||
return outbound, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func closeWireGuard(w *WireGuard) {
|
|
||||||
if w.device != nil {
|
|
||||||
w.device.Close()
|
|
||||||
}
|
|
||||||
_ = common.Close(w.tunDevice)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
options := w.Base.DialOptions(opts...)
|
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var conn net.Conn
|
|
||||||
w.startOnce.Do(func() {
|
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
options = append(options, dialer.WithResolver(resolver.DefaultResolver))
|
|
||||||
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
|
||||||
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
|
||||||
} else {
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if conn == nil {
|
|
||||||
return nil, E.New("conn is nil")
|
|
||||||
}
|
|
||||||
return NewConn(CN.NewRefConn(conn, w), w), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
options := w.Base.DialOptions(opts...)
|
|
||||||
w.dialer.dialer = dialer.NewDialer(options...)
|
|
||||||
var pc net.PacketConn
|
|
||||||
w.startOnce.Do(func() {
|
|
||||||
w.startErr = w.tunDevice.Start()
|
|
||||||
})
|
|
||||||
if w.startErr != nil {
|
|
||||||
return nil, w.startErr
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
port, _ := strconv.Atoi(metadata.DstPort)
|
|
||||||
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, uint16(port)).Unwrap())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if pc == nil {
|
|
||||||
return nil, E.New("packetConn is nil")
|
|
||||||
}
|
|
||||||
return newPacketConn(CN.NewRefPacketConn(pc, w), w), nil
|
|
||||||
}
|
|
24
adapter/outboundgroup/common.go
Normal file
24
adapter/outboundgroup/common.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for _, provider := range providers {
|
||||||
|
if touch {
|
||||||
|
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
||||||
|
} else {
|
||||||
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
@ -3,22 +3,19 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*GroupBase
|
*outbound.Base
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
testUrl string
|
single *singledo.Single[[]C.Proxy]
|
||||||
selected string
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -32,23 +29,7 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
} else {
|
|
||||||
f.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
f.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,7 +40,6 @@ func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(f)
|
pc.AppendToChains(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -75,8 +55,8 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range f.GetProxies(false) {
|
for _, proxy := range f.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -87,70 +67,40 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (f *Fallback) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
proxy := f.findAliveProxy(touch)
|
proxy := f.findAliveProxy(true)
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := f.single.Do(func() ([]C.Proxy, error) {
|
||||||
|
return getProvidersProxies(f.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
|
}
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
proxies := f.GetProxies(touch)
|
proxies := f.proxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if len(f.selected) == 0 {
|
if proxy.Alive() {
|
||||||
if proxy.Alive() {
|
return proxy
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if proxy.Name() == f.selected {
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy
|
|
||||||
} else {
|
|
||||||
f.selected = ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Set(name string) error {
|
|
||||||
var p C.Proxy
|
|
||||||
for _, proxy := range f.GetProxies(false) {
|
|
||||||
if proxy.Name() == name {
|
|
||||||
p = proxy
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if p == nil {
|
|
||||||
return errors.New("proxy not exist")
|
|
||||||
}
|
|
||||||
|
|
||||||
f.selected = name
|
|
||||||
if !p.Alive() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
|
||||||
defer cancel()
|
|
||||||
_, _ = p.URLTest(ctx, f.testUrl)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.Fallback,
|
||||||
Type: C.Fallback,
|
Interface: option.Interface,
|
||||||
Interface: option.Interface,
|
RoutingMark: option.RoutingMark,
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
option.Filter,
|
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,293 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GroupBase struct {
|
|
||||||
*outbound.Base
|
|
||||||
filterRegs []*regexp2.Regexp
|
|
||||||
excludeFilterReg *regexp2.Regexp
|
|
||||||
excludeTypeArray []string
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
failedTestMux sync.Mutex
|
|
||||||
failedTimes int
|
|
||||||
failedTime time.Time
|
|
||||||
failedTesting *atomic.Bool
|
|
||||||
proxies [][]C.Proxy
|
|
||||||
versions []atomic.Uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
|
||||||
outbound.BaseOption
|
|
||||||
filter string
|
|
||||||
excludeFilter string
|
|
||||||
excludeType string
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|
||||||
var excludeFilterReg *regexp2.Regexp
|
|
||||||
if opt.excludeFilter != "" {
|
|
||||||
excludeFilterReg = regexp2.MustCompile(opt.excludeFilter, 0)
|
|
||||||
}
|
|
||||||
var excludeTypeArray []string
|
|
||||||
if opt.excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(opt.excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
if opt.filter != "" {
|
|
||||||
for _, filter := range strings.Split(opt.filter, "`") {
|
|
||||||
filterReg := regexp2.MustCompile(filter, 0)
|
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
gb := &GroupBase{
|
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
|
||||||
filterRegs: filterRegs,
|
|
||||||
excludeFilterReg: excludeFilterReg,
|
|
||||||
excludeTypeArray: excludeTypeArray,
|
|
||||||
providers: opt.providers,
|
|
||||||
failedTesting: atomic.NewBool(false),
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
|
||||||
gb.versions = make([]atomic.Uint32, len(opt.providers))
|
|
||||||
|
|
||||||
return gb
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) Touch() {
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
pd.Touch()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
|
||||||
var proxies []C.Proxy
|
|
||||||
if len(gb.filterRegs) == 0 {
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
if touch {
|
|
||||||
pd.Touch()
|
|
||||||
}
|
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for i, pd := range gb.providers {
|
|
||||||
if touch {
|
|
||||||
pd.Touch()
|
|
||||||
}
|
|
||||||
|
|
||||||
if pd.VehicleType() == types.Compatible {
|
|
||||||
gb.versions[i].Store(pd.Version())
|
|
||||||
gb.proxies[i] = pd.Proxies()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
version := gb.versions[i].Load()
|
|
||||||
if version != pd.Version() && gb.versions[i].CompareAndSwap(version, pd.Version()) {
|
|
||||||
var (
|
|
||||||
proxies []C.Proxy
|
|
||||||
newProxies []C.Proxy
|
|
||||||
)
|
|
||||||
|
|
||||||
proxies = pd.Proxies()
|
|
||||||
proxiesSet := map[string]struct{}{}
|
|
||||||
for _, filterReg := range gb.filterRegs {
|
|
||||||
for _, p := range proxies {
|
|
||||||
name := p.Name()
|
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.proxies[i] = newProxies
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, p := range gb.proxies {
|
|
||||||
proxies = append(proxies, p...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
proxiesSet := map[string]struct{}{}
|
|
||||||
for _, filterReg := range gb.filterRegs {
|
|
||||||
for _, p := range proxies {
|
|
||||||
name := p.Name()
|
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat != nil {
|
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, p := range proxies { // add not matched proxies at the end
|
|
||||||
name := p.Name()
|
|
||||||
if _, ok := proxiesSet[name]; !ok {
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
if gb.excludeTypeArray != nil {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
for _, p := range proxies {
|
|
||||||
mType := p.Type().String()
|
|
||||||
flag := false
|
|
||||||
for i := range gb.excludeTypeArray {
|
|
||||||
if strings.EqualFold(mType, gb.excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
if gb.excludeFilterReg != nil {
|
|
||||||
var newProxies []C.Proxy
|
|
||||||
for _, p := range proxies {
|
|
||||||
name := p.Name()
|
|
||||||
if mat, _ := gb.excludeFilterReg.FindStringMatch(name); mat != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
newProxies = append(newProxies, p)
|
|
||||||
}
|
|
||||||
proxies = newProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) URLTest(ctx context.Context, url string) (map[string]uint16, error) {
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
var lock sync.Mutex
|
|
||||||
mp := map[string]uint16{}
|
|
||||||
proxies := gb.GetProxies(false)
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
proxy := proxy
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
delay, err := proxy.URLTest(ctx, url)
|
|
||||||
if err == nil {
|
|
||||||
lock.Lock()
|
|
||||||
mp[proxy.Name()] = delay
|
|
||||||
lock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Done()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
if len(mp) == 0 {
|
|
||||||
return mp, fmt.Errorf("get delay: all proxies timeout")
|
|
||||||
} else {
|
|
||||||
return mp, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error) {
|
|
||||||
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.Contains(err.Error(), "connection refused") {
|
|
||||||
go gb.healthCheck()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
gb.failedTestMux.Lock()
|
|
||||||
defer gb.failedTestMux.Unlock()
|
|
||||||
|
|
||||||
gb.failedTimes++
|
|
||||||
if gb.failedTimes == 1 {
|
|
||||||
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
|
||||||
gb.failedTime = time.Now()
|
|
||||||
} else {
|
|
||||||
if time.Since(gb.failedTime) > gb.failedTimeoutInterval() {
|
|
||||||
gb.failedTimes = 0
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
|
||||||
if gb.failedTimes >= gb.maxFailedTimes() {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
|
||||||
gb.healthCheck()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) healthCheck() {
|
|
||||||
if gb.failedTesting.Load() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.failedTesting.Store(true)
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
for _, proxyProvider := range gb.providers {
|
|
||||||
wg.Add(1)
|
|
||||||
proxyProvider := proxyProvider
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
proxyProvider.HealthCheck()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
gb.failedTesting.Store(false)
|
|
||||||
gb.failedTimes = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedIntervalTime() int64 {
|
|
||||||
return 5 * time.Second.Milliseconds()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) onDialSuccess() {
|
|
||||||
if !gb.failedTesting.Load() {
|
|
||||||
gb.failedTimes = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) maxFailedTimes() int {
|
|
||||||
return 5
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
|
||||||
return 5 * time.Second
|
|
||||||
}
|
|
@ -6,14 +6,10 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/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"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -21,28 +17,28 @@ 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
|
*outbound.Base
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
func parseStrategy(config map[string]any) string {
|
func parseStrategy(config map[string]any) string {
|
||||||
if strategy, ok := config["strategy"].(string); ok {
|
if elm, ok := config["strategy"]; ok {
|
||||||
return strategy
|
if strategy, ok := elm.(string); ok {
|
||||||
|
return strategy
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return "consistent-hashing"
|
return "consistent-hashing"
|
||||||
}
|
}
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
func getKey(metadata *C.Metadata) string {
|
||||||
if metadata == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
if metadata.Host != "" {
|
if metadata.Host != "" {
|
||||||
// ip host
|
// ip host
|
||||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
@ -61,16 +57,6 @@ func getKey(metadata *C.Metadata) string {
|
|||||||
return metadata.DstIP.String()
|
return metadata.DstIP.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func getKeyWithSrcAndDst(metadata *C.Metadata) string {
|
|
||||||
dst := getKey(metadata)
|
|
||||||
src := ""
|
|
||||||
if metadata != nil {
|
|
||||||
src = metadata.SrcIP.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Sprintf("%s%s", src, dst)
|
|
||||||
}
|
|
||||||
|
|
||||||
func jumpHash(key uint64, buckets int32) int32 {
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
var b, j int64
|
var b, j int64
|
||||||
|
|
||||||
@ -85,28 +71,15 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := lb.Unwrap(metadata, true)
|
defer func() {
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(lb)
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,7 +91,7 @@ func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Meta
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata, true)
|
proxy := lb.Unwrap(metadata)
|
||||||
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,25 +102,12 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
func strategyRoundRobin() strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
idxMutex := sync.Mutex{}
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
|
||||||
idxMutex.Lock()
|
|
||||||
defer idxMutex.Unlock()
|
|
||||||
|
|
||||||
i := 0
|
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
if touch {
|
idx = (idx + 1) % length
|
||||||
defer func() {
|
proxy := proxies[idx]
|
||||||
idx = (idx + i) % length
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
for ; i < length; i++ {
|
|
||||||
id := (idx + i) % length
|
|
||||||
proxy := proxies[id]
|
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
i++
|
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -158,7 +118,7 @@ func strategyRoundRobin() strategyFn {
|
|||||||
|
|
||||||
func strategyConsistentHashing() strategyFn {
|
func strategyConsistentHashing() strategyFn {
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(proxies))
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
@ -169,62 +129,28 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// when availability is poor, traverse the entire list to get the available nodes
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies[0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func strategyStickySessions() strategyFn {
|
|
||||||
ttl := time.Minute * 10
|
|
||||||
maxRetry := 5
|
|
||||||
lruCache := cache.New[uint64, int](
|
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
|
||||||
cache.WithSize[uint64, int](1000))
|
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
|
||||||
length := len(proxies)
|
|
||||||
idx, has := lruCache.Get(key)
|
|
||||||
if !has {
|
|
||||||
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
|
||||||
}
|
|
||||||
|
|
||||||
nowIdx := idx
|
|
||||||
for i := 1; i < maxRetry; i++ {
|
|
||||||
proxy := proxies[nowIdx]
|
|
||||||
if proxy.Alive() {
|
|
||||||
if nowIdx != idx {
|
|
||||||
lruCache.Delete(key)
|
|
||||||
lruCache.Set(key, nowIdx)
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxy
|
|
||||||
} else {
|
|
||||||
nowIdx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
lruCache.Delete(key)
|
|
||||||
lruCache.Set(key, 0)
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
proxies := lb.GetProxies(touch)
|
proxies := lb.proxies(true)
|
||||||
return lb.strategyFn(proxies, metadata, touch)
|
return lb.strategyFn(proxies, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := lb.single.Do(func() ([]C.Proxy, error) {
|
||||||
|
return getProvidersProxies(lb.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
var all []string
|
||||||
for _, proxy := range lb.GetProxies(false) {
|
for _, proxy := range lb.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -240,24 +166,18 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
strategyFn = strategyConsistentHashing()
|
strategyFn = strategyConsistentHashing()
|
||||||
case "round-robin":
|
case "round-robin":
|
||||||
strategyFn = strategyRoundRobin()
|
strategyFn = strategyRoundRobin()
|
||||||
case "sticky-sessions":
|
|
||||||
strategyFn = strategyStickySessions()
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
return &LoadBalance{
|
return &LoadBalance{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.LoadBalance,
|
||||||
Type: C.LoadBalance,
|
Interface: option.Interface,
|
||||||
Interface: option.Interface,
|
RoutingMark: option.RoutingMark,
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
option.Filter,
|
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}, nil
|
}, nil
|
||||||
|
@ -3,6 +3,7 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
@ -21,17 +22,15 @@ var (
|
|||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
outbound.BasicOption
|
outbound.BasicOption
|
||||||
Name string `group:"name"`
|
Name string `group:"name"`
|
||||||
Type string `group:"type"`
|
Type string `group:"type"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
Use []string `group:"use,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
Filter string `group:"filter,omitempty"`
|
||||||
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
|
||||||
ExcludeType string `group:"exclude-type,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
@ -40,10 +39,23 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
Lazy: true,
|
Lazy: true,
|
||||||
}
|
}
|
||||||
if err := decoder.Decode(config, groupOption); err != nil {
|
|
||||||
|
var (
|
||||||
|
filterRegx *regexp.Regexp
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
if err = decoder.Decode(config, groupOption); err != nil {
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if groupOption.Filter != "" {
|
||||||
|
filterRegx, err = regexp.Compile(groupOption.Filter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if groupOption.Type == "" || groupOption.Name == "" {
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
@ -77,12 +89,8 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" {
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
groupOption.URL = "https://cp.cloudflare.com/generate_204"
|
return nil, errMissHealthCheck
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.Interval == 0 {
|
|
||||||
groupOption.Interval = 300
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
@ -97,13 +105,11 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
list, err := getProviders(providersMap, groupOption.Use)
|
list, err := getProviders(providersMap, groupOption, filterRegx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
} else {
|
|
||||||
groupOption.Filter = ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
@ -139,8 +145,13 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
func getProviders(mapping map[string]types.ProxyProvider, groupOption *GroupCommonOption, filterRegx *regexp.Regexp) ([]types.ProxyProvider, error) {
|
||||||
var ps []types.ProxyProvider
|
var (
|
||||||
|
ps []types.ProxyProvider
|
||||||
|
list = groupOption.Use
|
||||||
|
groupName = groupOption.Name
|
||||||
|
)
|
||||||
|
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -150,6 +161,27 @@ func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]type
|
|||||||
if p.VehicleType() == types.Compatible {
|
if p.VehicleType() == types.Compatible {
|
||||||
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if filterRegx != nil {
|
||||||
|
var hc *provider.HealthCheck
|
||||||
|
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
||||||
|
hc = provider.NewHealthCheck([]C.Proxy{}, "", 0, true)
|
||||||
|
} else {
|
||||||
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
|
return nil, errMissHealthCheck
|
||||||
|
}
|
||||||
|
hc = provider.NewHealthCheck([]C.Proxy{}, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok = mapping[groupName]; ok {
|
||||||
|
groupName += "->" + p.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := p.(*provider.ProxySetProvider)
|
||||||
|
p = provider.NewProxyFilterProvider(groupName, pd, hc, filterRegx)
|
||||||
|
pd.RegisterProvidersInUse(p)
|
||||||
|
}
|
||||||
|
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
||||||
}
|
}
|
||||||
return ps, nil
|
return ps, nil
|
||||||
|
@ -3,54 +3,33 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*GroupBase
|
*outbound.Base
|
||||||
}
|
single *singledo.Single[[]C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
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)
|
var proxies []C.Proxy
|
||||||
|
for _, proxy := range r.proxies(metadata, true) {
|
||||||
|
if proxy.Type() != C.Direct {
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
switch len(proxies) {
|
switch len(proxies) {
|
||||||
case 0:
|
case 0:
|
||||||
@ -58,88 +37,166 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
case 1:
|
case 1:
|
||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
var d C.Dialer
|
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
c, err := r.streamContext(ctx, proxies, r.Base.DialOptions(opts...)...)
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
|
||||||
d = proxyDialer{
|
|
||||||
proxy: proxy,
|
|
||||||
dialer: d,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
conn, err := last.DialContextWithDialer(ctx, d, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
last := proxies[len(proxies)-1]
|
||||||
conn.AppendToChains(chainProxies[i])
|
c, err = last.StreamConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
conn.AppendToChains(r)
|
return outbound.NewConn(c, r), nil
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
var proxies []C.Proxy
|
||||||
|
for _, proxy := range r.proxies(metadata, true) {
|
||||||
|
if proxy.Type() != C.Direct {
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
switch len(proxies) {
|
length := len(proxies)
|
||||||
|
|
||||||
|
switch length {
|
||||||
case 0:
|
case 0:
|
||||||
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
case 1:
|
case 1:
|
||||||
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
proxy := proxies[0]
|
||||||
|
if !proxy.SupportUDP() {
|
||||||
|
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported", proxy.Addr(), proxy.Name())
|
||||||
|
}
|
||||||
|
return proxy.ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
var d C.Dialer
|
var (
|
||||||
d = dialer.NewDialer(r.Base.DialOptions(opts...)...)
|
firstIndex = 0
|
||||||
for _, proxy := range proxies[:len(proxies)-1] {
|
nextIndex = 1
|
||||||
d = proxyDialer{
|
lastUDPOverTCPIndex = -1
|
||||||
proxy: proxy,
|
rawUDPRelay = false
|
||||||
dialer: d,
|
|
||||||
|
first = proxies[firstIndex]
|
||||||
|
last = proxies[length-1]
|
||||||
|
|
||||||
|
c net.Conn
|
||||||
|
cc net.Conn
|
||||||
|
err error
|
||||||
|
currentMeta *C.Metadata
|
||||||
|
)
|
||||||
|
|
||||||
|
if !last.SupportUDP() {
|
||||||
|
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", last.Addr(), last.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
rawUDPRelay, lastUDPOverTCPIndex = isRawUDPRelay(proxies)
|
||||||
|
|
||||||
|
if first.Type() == C.Socks5 {
|
||||||
|
cc1, err1 := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
|
if err1 != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
cc = cc1
|
||||||
|
tcpKeepAlive(cc)
|
||||||
|
|
||||||
|
var pc net.PacketConn
|
||||||
|
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
||||||
|
c = outbound.WrapConn(pc)
|
||||||
|
} else if rawUDPRelay {
|
||||||
|
var pc net.PacketConn
|
||||||
|
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
||||||
|
c = outbound.WrapConn(pc)
|
||||||
|
} else {
|
||||||
|
firstIndex = lastUDPOverTCPIndex
|
||||||
|
nextIndex = firstIndex + 1
|
||||||
|
first = proxies[firstIndex]
|
||||||
|
c, err = r.streamContext(ctx, proxies[:nextIndex], r.Base.DialOptions(opts...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if nextIndex < length {
|
||||||
|
for i, proxy := range proxies[nextIndex:] { // raw udp in loop
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
currentMeta.NetWork = C.UDP
|
||||||
|
|
||||||
|
if !isRawUDP(first) && !first.SupportUDP() {
|
||||||
|
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", first.Addr(), first.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
if needResolveIP(first, currentMeta) {
|
||||||
|
var ip netip.Addr
|
||||||
|
ip, err = resolver.ResolveProxyServerHost(currentMeta.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
currentMeta.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
if cc != nil { // socks5
|
||||||
|
c, err = streamSocks5PacketConn(first, cc, c, currentMeta)
|
||||||
|
cc = nil
|
||||||
|
} else {
|
||||||
|
c, err = first.StreamPacketConn(c, currentMeta)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if proxy.Type() == C.Socks5 {
|
||||||
|
endIndex := nextIndex + i + 1
|
||||||
|
cc, err = r.streamContext(ctx, proxies[:endIndex], r.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
pc, err := last.ListenPacketWithDialer(ctx, d, metadata)
|
if cc != nil {
|
||||||
|
c, err = streamSocks5PacketConn(last, cc, c, metadata)
|
||||||
|
} else {
|
||||||
|
c, err = last.StreamPacketConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
return outbound.NewPacketConn(c.(net.PacketConn), r), nil
|
||||||
pc.AppendToChains(chainProxies[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
pc.AppendToChains(r)
|
|
||||||
|
|
||||||
return pc, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (r *Relay) SupportUDP() bool {
|
func (r *Relay) SupportUDP() bool {
|
||||||
proxies, _ := r.proxies(nil, false)
|
proxies := r.rawProxies(true)
|
||||||
if len(proxies) == 0 { // C.Direct
|
|
||||||
|
l := len(proxies)
|
||||||
|
|
||||||
|
if l == 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
for i := len(proxies) - 1; i >= 0; i-- {
|
|
||||||
proxy := proxies[i]
|
last := proxies[l-1]
|
||||||
if !proxy.SupportUDP() {
|
|
||||||
return false
|
return isRawUDP(last) || last.SupportUDP()
|
||||||
}
|
|
||||||
if proxy.SupportUOT() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if !proxy.SupportWithDialer() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (r *Relay) MarshalJSON() ([]byte, error) {
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range r.GetProxies(false) {
|
for _, proxy := range r.rawProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -148,51 +205,114 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy) {
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
rawProxies := r.GetProxies(touch)
|
elm, _, _ := r.single.Do(func() ([]C.Proxy, error) {
|
||||||
|
return getProvidersProxies(r.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
var proxies []C.Proxy
|
return elm
|
||||||
var chainProxies []C.Proxy
|
|
||||||
var targetProxies []C.Proxy
|
|
||||||
|
|
||||||
for n, proxy := range rawProxies {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
chainProxies = append(chainProxies, proxy)
|
|
||||||
subproxy := proxy.Unwrap(metadata, touch)
|
|
||||||
for subproxy != nil {
|
|
||||||
chainProxies = append(chainProxies, subproxy)
|
|
||||||
proxies[n] = subproxy
|
|
||||||
subproxy = subproxy.Unwrap(metadata, touch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
|
||||||
targetProxies = append(targetProxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return targetProxies, chainProxies
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) Addr() string {
|
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
||||||
proxies, _ := r.proxies(nil, false)
|
proxies := r.rawProxies(touch)
|
||||||
return proxies[len(proxies)-1].Addr()
|
|
||||||
|
for n, proxy := range proxies {
|
||||||
|
subproxy := proxy.Unwrap(metadata)
|
||||||
|
for subproxy != nil {
|
||||||
|
proxies[n] = subproxy
|
||||||
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Relay) streamContext(ctx context.Context, proxies []C.Proxy, opts ...dialer.Option) (net.Conn, error) {
|
||||||
|
first := proxies[0]
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
if len(proxies) > 1 {
|
||||||
|
var currentMeta *C.Metadata
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func streamSocks5PacketConn(proxy C.Proxy, cc, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
|
pc, err := proxy.(*adapter.Proxy).ProxyAdapter.(*outbound.Socks5).StreamSocks5PacketConn(cc, c.(net.PacketConn), metadata)
|
||||||
|
return outbound.WrapConn(pc), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRawUDPRelay(proxies []C.Proxy) (bool, int) {
|
||||||
|
var (
|
||||||
|
lastIndex = len(proxies) - 1
|
||||||
|
last = proxies[lastIndex]
|
||||||
|
isLastRawUDP = isRawUDP(last)
|
||||||
|
isUDPOverTCP = false
|
||||||
|
lastUDPOverTCPIndex = -1
|
||||||
|
)
|
||||||
|
|
||||||
|
for i := lastIndex; i >= 0; i-- {
|
||||||
|
p := proxies[i]
|
||||||
|
|
||||||
|
isUDPOverTCP = isUDPOverTCP || !isRawUDP(p)
|
||||||
|
|
||||||
|
if isLastRawUDP && isUDPOverTCP && lastUDPOverTCPIndex == -1 {
|
||||||
|
lastUDPOverTCPIndex = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isLastRawUDP {
|
||||||
|
lastUDPOverTCPIndex = lastIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
return !isUDPOverTCP, lastUDPOverTCPIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRawUDP(proxy C.ProxyAdapter) bool {
|
||||||
|
if proxy.Type() == C.Shadowsocks || proxy.Type() == C.ShadowsocksR || proxy.Type() == C.Socks5 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func needResolveIP(proxy C.ProxyAdapter, metadata *C.Metadata) bool {
|
||||||
|
if metadata.Resolved() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if proxy.Type() != C.Vmess && proxy.Type() != C.Vless {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
return &Relay{
|
return &Relay{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.Relay,
|
||||||
Type: C.Relay,
|
Interface: option.Interface,
|
||||||
Interface: option.Interface,
|
RoutingMark: option.RoutingMark,
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,15 +6,18 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
"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"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
*GroupBase
|
*outbound.Base
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
|
single *singledo.Single[C.Proxy]
|
||||||
selected string
|
selected string
|
||||||
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -46,8 +49,8 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range s.GetProxies(false) {
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,9 +66,10 @@ func (s *Selector) Now() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
func (s *Selector) Set(name string) error {
|
||||||
for _, proxy := range s.GetProxies(false) {
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
if proxy.Name() == name {
|
if proxy.Name() == name {
|
||||||
s.selected = name
|
s.selected = name
|
||||||
|
s.single.Reset()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -74,36 +78,37 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return s.selectedProxy(touch)
|
return s.selectedProxy(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
proxies := s.GetProxies(touch)
|
elm, _, _ := s.single.Do(func() (C.Proxy, error) {
|
||||||
for _, proxy := range proxies {
|
proxies := getProvidersProxies(s.providers, touch)
|
||||||
if proxy.Name() == s.selected {
|
for _, proxy := range proxies {
|
||||||
return proxy
|
if proxy.Name() == s.selected {
|
||||||
|
return proxy, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0], nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
||||||
|
selected := providers[0].Proxies()[0].Name()
|
||||||
return &Selector{
|
return &Selector{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.Selector,
|
||||||
Type: C.Selector,
|
Interface: option.Interface,
|
||||||
Interface: option.Interface,
|
RoutingMark: option.RoutingMark,
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
option.Filter,
|
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,8 +6,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/callback"
|
|
||||||
N "github.com/Dreamacro/clash/common/net"
|
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -23,11 +21,13 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*outbound.Base
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
|
single *singledo.Single[[]C.Proxy]
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
@ -36,27 +36,10 @@ func (u *URLTest) Now() string {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := u.fast(true)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
} else {
|
|
||||||
u.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if N.NeedHandshake(c) {
|
|
||||||
c = &callback.FirstWriteCallBackConn{
|
|
||||||
Conn: c,
|
|
||||||
Callback: func(err error) {
|
|
||||||
if err == nil {
|
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
u.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,18 +49,25 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return u.fast(touch)
|
return u.fast(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
||||||
|
elm, _, _ := u.single.Do(func() ([]C.Proxy, error) {
|
||||||
|
return getProvidersProxies(u.providers, touch), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.proxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
@ -105,9 +95,6 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
|
||||||
u.Touch()
|
|
||||||
}
|
|
||||||
|
|
||||||
return elm
|
return elm
|
||||||
}
|
}
|
||||||
@ -123,8 +110,8 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range u.GetProxies(false) {
|
for _, proxy := range u.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -149,20 +136,15 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
|||||||
|
|
||||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.URLTest,
|
||||||
Type: C.URLTest,
|
Interface: option.Interface,
|
||||||
Interface: option.Interface,
|
RoutingMark: option.RoutingMark,
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
|
|
||||||
option.Filter,
|
|
||||||
option.ExcludeFilter,
|
|
||||||
option.ExcludeType,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
|
providers: providers,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -16,19 +16,31 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if ip, err := netip.ParseAddr(host); err != nil {
|
ip, err := netip.ParseAddr(host)
|
||||||
|
if err != nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
Host: host,
|
AddrType: C.AtypDomainName,
|
||||||
DstPort: port,
|
Host: host,
|
||||||
|
DstIP: netip.Addr{},
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
} else {
|
return addr, nil
|
||||||
|
} else if ip.Is4() {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
Host: "",
|
AddrType: C.AtypIPv4,
|
||||||
DstIP: ip.Unmap(),
|
Host: "",
|
||||||
DstPort: port,
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addr = &C.Metadata{
|
||||||
|
AddrType: C.AtypIPv6,
|
||||||
|
Host: "",
|
||||||
|
DstIP: ip,
|
||||||
|
DstPort: port,
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,7 +50,3 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type SelectAble interface {
|
|
||||||
Set(string) error
|
|
||||||
}
|
|
||||||
|
@ -3,15 +3,13 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true, KeyReplacer: structure.DefaultKeyReplacer})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
return nil, fmt.Errorf("missing type")
|
return nil, fmt.Errorf("missing type")
|
||||||
@ -23,7 +21,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
|
||||||
@ -42,34 +40,44 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewSocks5(*socksOption)
|
if forceCertVerify {
|
||||||
|
socksOption.SkipCertVerify = false
|
||||||
|
}
|
||||||
|
proxy = outbound.NewSocks5(*socksOption)
|
||||||
case "http":
|
case "http":
|
||||||
httpOption := &outbound.HttpOption{}
|
httpOption := &outbound.HttpOption{}
|
||||||
err = decoder.Decode(mapping, httpOption)
|
err = decoder.Decode(mapping, httpOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHttp(*httpOption)
|
if forceCertVerify {
|
||||||
|
httpOption.SkipCertVerify = false
|
||||||
|
}
|
||||||
|
proxy = outbound.NewHttp(*httpOption)
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{
|
||||||
HTTPOpts: outbound.HTTPOptions{
|
HTTPOpts: outbound.HTTPOptions{
|
||||||
Method: "GET",
|
Method: "GET",
|
||||||
Path: []string{"/"},
|
Path: []string{"/"},
|
||||||
},
|
},
|
||||||
ClientFingerprint: tlsC.GetGlobalFingerprint(),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if forceCertVerify {
|
||||||
|
vmessOption.SkipCertVerify = false
|
||||||
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
vlessOption := &outbound.VlessOption{}
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if forceCertVerify {
|
||||||
|
vlessOption.SkipCertVerify = false
|
||||||
|
}
|
||||||
proxy, err = outbound.NewVless(*vlessOption)
|
proxy, err = outbound.NewVless(*vlessOption)
|
||||||
case "snell":
|
case "snell":
|
||||||
snellOption := &outbound.SnellOption{}
|
snellOption := &outbound.SnellOption{}
|
||||||
@ -79,33 +87,15 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
}
|
}
|
||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{ClientFingerprint: tlsC.GetGlobalFingerprint()}
|
trojanOption := &outbound.TrojanOption{}
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if forceCertVerify {
|
||||||
|
trojanOption.SkipCertVerify = false
|
||||||
|
}
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
case "hysteria":
|
|
||||||
hyOption := &outbound.HysteriaOption{}
|
|
||||||
err = decoder.Decode(mapping, hyOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
|
||||||
case "wireguard":
|
|
||||||
wgOption := &outbound.WireGuardOption{}
|
|
||||||
err = decoder.Decode(mapping, wgOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewWireGuard(*wgOption)
|
|
||||||
case "tuic":
|
|
||||||
tuicOption := &outbound.TuicOption{}
|
|
||||||
err = decoder.Decode(mapping, tuicOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewTuic(*tuicOption)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package resource
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@ -16,50 +16,38 @@ var (
|
|||||||
dirMode os.FileMode = 0o755
|
dirMode os.FileMode = 0o755
|
||||||
)
|
)
|
||||||
|
|
||||||
type Parser[V any] func([]byte) (V, error)
|
type parser[V any] func([]byte) (V, error)
|
||||||
|
|
||||||
type Fetcher[V any] struct {
|
type fetcher[V any] struct {
|
||||||
resourceType string
|
name string
|
||||||
name string
|
vehicle types.Vehicle
|
||||||
vehicle types.Vehicle
|
updatedAt *time.Time
|
||||||
UpdatedAt *time.Time
|
ticker *time.Ticker
|
||||||
ticker *time.Ticker
|
done chan struct{}
|
||||||
done chan struct{}
|
hash [16]byte
|
||||||
hash [16]byte
|
parser parser[V]
|
||||||
parser Parser[V]
|
onUpdate func(V)
|
||||||
interval time.Duration
|
|
||||||
OnUpdate func(V)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Name() string {
|
func (f *fetcher[V]) Name() string {
|
||||||
return f.name
|
return f.name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Vehicle() types.Vehicle {
|
func (f *fetcher[V]) VehicleType() types.VehicleType {
|
||||||
return f.vehicle
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fetcher[V]) VehicleType() types.VehicleType {
|
|
||||||
return f.vehicle.Type()
|
return f.vehicle.Type()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Initial() (V, error) {
|
func (f *fetcher[V]) Initial() (V, error) {
|
||||||
var (
|
var (
|
||||||
buf []byte
|
buf []byte
|
||||||
err error
|
err error
|
||||||
isLocal bool
|
isLocal bool
|
||||||
forceUpdate bool
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
||||||
buf, err = os.ReadFile(f.vehicle.Path())
|
buf, err = os.ReadFile(f.vehicle.Path())
|
||||||
modTime := stat.ModTime()
|
modTime := stat.ModTime()
|
||||||
f.UpdatedAt = &modTime
|
f.updatedAt = &modTime
|
||||||
isLocal = true
|
isLocal = true
|
||||||
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
|
|
||||||
log.Warnln("[Provider] %s not updated for a long time, force refresh", f.Name())
|
|
||||||
forceUpdate = true
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
buf, err = f.vehicle.Read()
|
buf, err = f.vehicle.Read()
|
||||||
}
|
}
|
||||||
@ -68,21 +56,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
|||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
|
|
||||||
var contents V
|
proxies, err := f.parser(buf)
|
||||||
if forceUpdate {
|
|
||||||
var forceBuf []byte
|
|
||||||
if forceBuf, err = f.vehicle.Read(); err == nil {
|
|
||||||
if contents, err = f.parser(forceBuf); err == nil {
|
|
||||||
isLocal = false
|
|
||||||
buf = forceBuf
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil || !forceUpdate {
|
|
||||||
contents, err = f.parser(buf)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !isLocal {
|
if !isLocal {
|
||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
@ -94,7 +68,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
|||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
|
|
||||||
contents, err = f.parser(buf)
|
proxies, err = f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), err
|
return getZero[V](), err
|
||||||
}
|
}
|
||||||
@ -110,15 +84,15 @@ func (f *Fetcher[V]) Initial() (V, error) {
|
|||||||
|
|
||||||
f.hash = md5.Sum(buf)
|
f.hash = md5.Sum(buf)
|
||||||
|
|
||||||
// pull contents automatically
|
// pull proxies automatically
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
go f.pullLoop()
|
go f.pullLoop()
|
||||||
}
|
}
|
||||||
|
|
||||||
return contents, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Update() (V, bool, error) {
|
func (f *fetcher[V]) Update() (V, bool, error) {
|
||||||
buf, err := f.vehicle.Read()
|
buf, err := f.vehicle.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), false, err
|
return getZero[V](), false, err
|
||||||
@ -127,12 +101,12 @@ func (f *Fetcher[V]) Update() (V, bool, error) {
|
|||||||
now := time.Now()
|
now := time.Now()
|
||||||
hash := md5.Sum(buf)
|
hash := md5.Sum(buf)
|
||||||
if bytes.Equal(f.hash[:], hash[:]) {
|
if bytes.Equal(f.hash[:], hash[:]) {
|
||||||
f.UpdatedAt = &now
|
f.updatedAt = &now
|
||||||
_ = os.Chtimes(f.vehicle.Path(), now, now)
|
_ = os.Chtimes(f.vehicle.Path(), now, now)
|
||||||
return getZero[V](), true, nil
|
return getZero[V](), true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
contents, err := f.parser(buf)
|
proxies, err := f.parser(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return getZero[V](), false, err
|
return getZero[V](), false, err
|
||||||
}
|
}
|
||||||
@ -143,37 +117,37 @@ func (f *Fetcher[V]) Update() (V, bool, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
f.UpdatedAt = &now
|
f.updatedAt = &now
|
||||||
f.hash = hash
|
f.hash = hash
|
||||||
|
|
||||||
return contents, false, nil
|
return proxies, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) Destroy() error {
|
func (f *fetcher[V]) Destroy() error {
|
||||||
if f.ticker != nil {
|
if f.ticker != nil {
|
||||||
f.done <- struct{}{}
|
f.done <- struct{}{}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fetcher[V]) pullLoop() {
|
func (f *fetcher[V]) pullLoop() {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-f.ticker.C:
|
case <-f.ticker.C:
|
||||||
elm, same, err := f.Update()
|
elm, same, err := f.Update()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if same {
|
if same {
|
||||||
log.Debugln("[Provider] %s's content doesn't change", f.Name())
|
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infoln("[Provider] %s's content update", f.Name())
|
log.Infoln("[Provider] %s's proxies update", f.Name())
|
||||||
if f.OnUpdate != nil {
|
if f.onUpdate != nil {
|
||||||
f.OnUpdate(elm)
|
f.onUpdate(elm)
|
||||||
}
|
}
|
||||||
case <-f.done:
|
case <-f.done:
|
||||||
f.ticker.Stop()
|
f.ticker.Stop()
|
||||||
@ -194,20 +168,19 @@ func safeWrite(path string, buf []byte) error {
|
|||||||
return os.WriteFile(path, buf, fileMode)
|
return os.WriteFile(path, buf, fileMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser Parser[V], onUpdate func(V)) *Fetcher[V] {
|
func newFetcher[V any](name string, interval time.Duration, vehicle types.Vehicle, parser parser[V], onUpdate func(V)) *fetcher[V] {
|
||||||
var ticker *time.Ticker
|
var ticker *time.Ticker
|
||||||
if interval != 0 {
|
if interval != 0 {
|
||||||
ticker = time.NewTicker(interval)
|
ticker = time.NewTicker(interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Fetcher[V]{
|
return &fetcher[V]{
|
||||||
name: name,
|
name: name,
|
||||||
ticker: ticker,
|
ticker: ticker,
|
||||||
vehicle: vehicle,
|
vehicle: vehicle,
|
||||||
parser: parser,
|
parser: parser,
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
OnUpdate: onUpdate,
|
onUpdate: onUpdate,
|
||||||
interval: interval,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -5,10 +5,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
@ -29,19 +26,24 @@ type HealthCheck struct {
|
|||||||
lazy bool
|
lazy bool
|
||||||
lastTouch *atomic.Int64
|
lastTouch *atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
singleDo *singledo.Single[struct{}]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
t := time.NewTicker(30 * time.Second)
|
||||||
|
<-t.C
|
||||||
|
t.Stop()
|
||||||
|
hc.check()
|
||||||
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
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()
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
}
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
@ -63,26 +65,22 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
proxies := hc.proxies
|
||||||
id := utils.NewUUIDV4().String()
|
if len(proxies) == 0 {
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
return
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
}
|
||||||
for _, proxy := range hc.proxies {
|
|
||||||
p := proxy
|
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
||||||
defer cancel()
|
|
||||||
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
|
||||||
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
|
||||||
return false, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
b.Wait()
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
log.Debugln("Finish A Health Checking {%s}", id)
|
for _, proxy := range proxies {
|
||||||
return struct{}{}, nil
|
p := proxy
|
||||||
})
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
|
return false, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
b.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
@ -97,6 +95,5 @@ func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *He
|
|||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
lastTouch: atomic.NewInt64(0),
|
lastTouch: atomic.NewInt64(0),
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
singleDo: singledo.NewSingle[struct{}](time.Second),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
@ -21,17 +20,18 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
ExcludeType string `provider:"exclude-type,omitempty"`
|
ForceCertVerify bool `provider:"force-cert-verify,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
PrefixName string `provider:"prefix-name,omitempty"`
|
||||||
|
Header map[string][]string `provider:"header,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify bool) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@ -39,6 +39,11 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
Lazy: true,
|
Lazy: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if forceCertVerify {
|
||||||
|
schema.ForceCertVerify = true
|
||||||
|
}
|
||||||
|
|
||||||
if err := decoder.Decode(mapping, schema); err != nil {
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -54,17 +59,14 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
vehicle = resource.NewFileVehicle(path)
|
vehicle = NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
vehicle = NewHTTPVehicle(schema.URL, path, schema.Header)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
filter := schema.Filter
|
||||||
excludeFilter := schema.ExcludeFilter
|
return NewProxySetProvider(name, interval, filter, vehicle, hc, schema.ForceCertVerify, schema.PrefixName)
|
||||||
excludeType := schema.ExcludeType
|
|
||||||
|
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, excludeType, vehicle, hc)
|
|
||||||
}
|
}
|
||||||
|
@ -1,24 +1,18 @@
|
|||||||
package provider
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
clashHttp "github.com/Dreamacro/clash/component/http"
|
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -36,30 +30,24 @@ type ProxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*resource.Fetcher[[]C.Proxy]
|
*fetcher[[]C.Proxy]
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
version uint32
|
providersInUse []types.ProxyProvider
|
||||||
subscriptionInfo *SubscriptionInfo
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"name": pp.Name(),
|
"name": pp.Name(),
|
||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.updatedAt,
|
||||||
"subscriptionInfo": pp.subscriptionInfo,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Version() uint32 {
|
|
||||||
return pp.version
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) Name() string {
|
func (pp *proxySetProvider) Name() string {
|
||||||
return pp.Fetcher.Name()
|
return pp.name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheck() {
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
@ -67,20 +55,20 @@ func (pp *proxySetProvider) HealthCheck() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
elm, same, err := pp.Fetcher.Update()
|
elm, same, err := pp.fetcher.Update()
|
||||||
if err == nil && !same {
|
if err == nil && !same {
|
||||||
pp.OnUpdate(elm)
|
pp.onUpdate(elm)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Initial() error {
|
func (pp *proxySetProvider) Initial() error {
|
||||||
elm, err := pp.Fetcher.Initial()
|
elm, err := pp.fetcher.Initial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pp.OnUpdate(elm)
|
|
||||||
pp.getSubscriptionInfo()
|
pp.onUpdate(elm)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,74 +80,33 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
|||||||
return pp.proxies
|
return pp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Touch() {
|
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
|
return pp.Proxies()
|
||||||
}
|
}
|
||||||
|
|
||||||
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() {
|
|
||||||
go pp.healthCheck.check()
|
for _, use := range pp.providersInUse {
|
||||||
|
_ = use.Update()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) getSubscriptionInfo() {
|
func (pp *proxySetProvider) RegisterProvidersInUse(providers ...types.ProxyProvider) {
|
||||||
if pp.VehicleType() != types.HTTP {
|
pp.providersInUse = append(pp.providersInUse, providers...)
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
|
|
||||||
defer cancel()
|
|
||||||
resp, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
|
||||||
http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
userInfoStr := strings.TrimSpace(resp.Header.Get("subscription-userinfo"))
|
|
||||||
if userInfoStr == "" {
|
|
||||||
resp2, err := clashHttp.HttpRequest(ctx, pp.Vehicle().(*resource.HTTPVehicle).Url(),
|
|
||||||
http.MethodGet, http.Header{"User-Agent": {"Quantumultx"}}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp2.Body.Close()
|
|
||||||
userInfoStr = strings.TrimSpace(resp2.Header.Get("subscription-userinfo"))
|
|
||||||
if userInfoStr == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pp.subscriptionInfo, err = NewSubscriptionInfo(userInfoStr)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.Fetcher.Destroy()
|
_ = pd.fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, excludeFilter string, excludeType string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck, forceCertVerify bool, prefixName string) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
filterReg, err := regexp.Compile(filter)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
|
||||||
var excludeTypeArray []string
|
|
||||||
if excludeType != "" {
|
|
||||||
excludeTypeArray = strings.Split(excludeType, "|")
|
|
||||||
}
|
|
||||||
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
|
||||||
}
|
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if hc.auto() {
|
if hc.auto() {
|
||||||
@ -171,8 +118,9 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, exc
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, excludeFilter, excludeTypeArray, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg, forceCertVerify, prefixName), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.fetcher = fetcher
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
@ -187,7 +135,6 @@ type compatibleProvider struct {
|
|||||||
name string
|
name string
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
version uint32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -199,10 +146,6 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Version() uint32 {
|
|
||||||
return cp.version
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Name() string {
|
func (cp *compatibleProvider) Name() string {
|
||||||
return cp.name
|
return cp.name
|
||||||
}
|
}
|
||||||
@ -231,8 +174,9 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|||||||
return cp.proxies
|
return cp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Touch() {
|
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
|
return cp.Proxies()
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
@ -259,22 +203,112 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProxyFilterProvider for filter provider
|
||||||
|
type ProxyFilterProvider struct {
|
||||||
|
*proxyFilterProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxyFilterProvider struct {
|
||||||
|
name string
|
||||||
|
psd *ProxySetProvider
|
||||||
|
proxies []C.Proxy
|
||||||
|
filter *regexp.Regexp
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"name": pf.Name(),
|
||||||
|
"type": pf.Type().String(),
|
||||||
|
"vehicleType": pf.VehicleType().String(),
|
||||||
|
"proxies": pf.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) Name() string {
|
||||||
|
return pf.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) HealthCheck() {
|
||||||
|
pf.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) Update() error {
|
||||||
|
var proxies []C.Proxy
|
||||||
|
if pf.filter != nil {
|
||||||
|
for _, proxy := range pf.psd.Proxies() {
|
||||||
|
if !pf.filter.MatchString(proxy.Name()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
proxies = pf.psd.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
pf.proxies = proxies
|
||||||
|
pf.healthCheck.setProxy(proxies)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) VehicleType() types.VehicleType {
|
||||||
|
return pf.psd.VehicleType()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) Type() types.ProviderType {
|
||||||
|
return types.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) Proxies() []C.Proxy {
|
||||||
|
return pf.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pf *proxyFilterProvider) ProxiesWithTouch() []C.Proxy {
|
||||||
|
pf.healthCheck.touch()
|
||||||
|
return pf.Proxies()
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopProxyFilterProvider(pf *ProxyFilterProvider) {
|
||||||
|
pf.healthCheck.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxyFilterProvider(name string, psd *ProxySetProvider, hc *HealthCheck, filterRegx *regexp.Regexp) *ProxyFilterProvider {
|
||||||
|
pd := &proxyFilterProvider{
|
||||||
|
psd: psd,
|
||||||
|
name: name,
|
||||||
|
healthCheck: hc,
|
||||||
|
filter: filterRegx,
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = pd.Update()
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &ProxyFilterProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, stopProxyFilterProvider)
|
||||||
|
return wrapper
|
||||||
|
}
|
||||||
|
|
||||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
pd.version += 1
|
|
||||||
pd.getSubscriptionInfo()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray []string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, filterReg *regexp.Regexp, forceCertVerify bool, prefixName string) 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("%s, %w", err.Error(), err1)
|
return nil, fmt.Errorf("%w, %s", err, err1.Error())
|
||||||
}
|
}
|
||||||
schema.Proxies = proxies
|
schema.Proxies = proxies
|
||||||
}
|
}
|
||||||
@ -284,59 +318,20 @@ func proxiesParseAndFilter(filter string, excludeFilter string, excludeTypeArray
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
proxiesSet := map[string]struct{}{}
|
for idx, mapping := range schema.Proxies {
|
||||||
for _, filterReg := range filterRegs {
|
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
||||||
for idx, mapping := range schema.Proxies {
|
continue
|
||||||
if nil != excludeTypeArray && len(excludeTypeArray) > 0 {
|
|
||||||
mType, ok := mapping["type"]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
pType, ok := mType.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
flag := false
|
|
||||||
for i := range excludeTypeArray {
|
|
||||||
if strings.EqualFold(pType, excludeTypeArray[i]) {
|
|
||||||
flag = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if flag {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
mName, ok := mapping["name"]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
name, ok := mName.(string)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if len(excludeFilter) > 0 {
|
|
||||||
if mat, _ := excludeFilterReg.FindStringMatch(name); mat != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(filter) > 0 {
|
|
||||||
if mat, _ := filterReg.FindStringMatch(name); mat == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, ok := proxiesSet[name]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if prefixName != "" {
|
||||||
|
mapping["name"] = prefixName + mapping["name"].(string)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy, err := adapter.ParseProxy(mapping, forceCertVerify)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
|
@ -1,57 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type SubscriptionInfo struct {
|
|
||||||
Upload int64
|
|
||||||
Download int64
|
|
||||||
Total int64
|
|
||||||
Expire int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSubscriptionInfo(str string) (si *SubscriptionInfo, err error) {
|
|
||||||
si = &SubscriptionInfo{}
|
|
||||||
str = strings.ToLower(str)
|
|
||||||
reTraffic := regexp2.MustCompile("upload=(\\d+); download=(\\d+); total=(\\d+)", 0)
|
|
||||||
reExpire := regexp2.MustCompile("expire=(\\d+)", 0)
|
|
||||||
|
|
||||||
match, err := reTraffic.FindStringMatch(str)
|
|
||||||
if err != nil || match == nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
group := match.Groups()
|
|
||||||
si.Upload, err = str2uint64(group[1].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
si.Download, err = str2uint64(group[2].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
si.Total, err = str2uint64(group[3].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
match, _ = reExpire.FindStringMatch(str)
|
|
||||||
if match != nil {
|
|
||||||
group = match.Groups()
|
|
||||||
si.Expire, err = str2uint64(group[1].String())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func str2uint64(str string) (int64, error) {
|
|
||||||
i, err := strconv.ParseInt(str, 10, 64)
|
|
||||||
return i, err
|
|
||||||
}
|
|
114
adapter/provider/vehicle.go
Normal file
114
adapter/provider/vehicle.go
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileVehicle struct {
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Type() types.VehicleType {
|
||||||
|
return types.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Path() string {
|
||||||
|
return f.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Read() ([]byte, error) {
|
||||||
|
return os.ReadFile(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFileVehicle(path string) *FileVehicle {
|
||||||
|
return &FileVehicle{path: path}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPVehicle struct {
|
||||||
|
url string
|
||||||
|
path string
|
||||||
|
header http.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Type() types.VehicleType {
|
||||||
|
return types.HTTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Path() string {
|
||||||
|
return h.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
uri, err := url.Parse(h.url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.header != nil {
|
||||||
|
req.Header = h.header
|
||||||
|
}
|
||||||
|
|
||||||
|
if user := uri.User; user != nil {
|
||||||
|
password, _ := user.Password()
|
||||||
|
req.SetBasicAuth(user.Username(), password)
|
||||||
|
}
|
||||||
|
|
||||||
|
convert.SetUserAgent(req.Header)
|
||||||
|
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
DialContext: func(ctx context.Context, network, address string) (conn net.Conn, err error) {
|
||||||
|
conn, err = dialer.DialContext(ctx, network, address) // with direct
|
||||||
|
if err != nil {
|
||||||
|
// fallback to tun if tun enabled
|
||||||
|
conn, err = (&net.Dialer{Timeout: C.DefaultTCPTimeout}).Dial(network, address)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
buf, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPVehicle(url string, path string, header http.Header) *HTTPVehicle {
|
||||||
|
return &HTTPVehicle{url, path, header}
|
||||||
|
}
|
@ -1,28 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
flags=$(grep '^flags\b' </proc/cpuinfo | head -n 1)
|
|
||||||
flags=" ${flags#*:} "
|
|
||||||
|
|
||||||
has_flags () {
|
|
||||||
for flag; do
|
|
||||||
case "$flags" in
|
|
||||||
*" $flag "*) :;;
|
|
||||||
*) return 1;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
determine_level () {
|
|
||||||
level=0
|
|
||||||
has_flags lm cmov cx8 fpu fxsr mmx syscall sse2 || return 0
|
|
||||||
level=1
|
|
||||||
has_flags cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 || return 0
|
|
||||||
level=2
|
|
||||||
has_flags avx avx2 bmi1 bmi2 f16c fma abm movbe xsave || return 0
|
|
||||||
level=3
|
|
||||||
has_flags avx512f avx512bw avx512cd avx512dq avx512vl || return 0
|
|
||||||
level=4
|
|
||||||
}
|
|
||||||
|
|
||||||
determine_level
|
|
||||||
echo "Your CPU supports amd64-v$level"
|
|
||||||
return $level
|
|
@ -1,25 +0,0 @@
|
|||||||
package buf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
)
|
|
||||||
|
|
||||||
const BufferSize = buf.BufferSize
|
|
||||||
|
|
||||||
type Buffer = buf.Buffer
|
|
||||||
|
|
||||||
var New = buf.New
|
|
||||||
var StackNew = buf.StackNew
|
|
||||||
var StackNewSize = buf.StackNewSize
|
|
||||||
var With = buf.With
|
|
||||||
|
|
||||||
var KeepAlive = common.KeepAlive
|
|
||||||
|
|
||||||
//go:norace
|
|
||||||
func Dup[T any](obj T) T {
|
|
||||||
return common.Dup(obj)
|
|
||||||
}
|
|
||||||
|
|
||||||
var Must = common.Must
|
|
||||||
var Error = common.Error
|
|
106
common/cache/cache.go
vendored
Normal file
106
common/cache/cache.go
vendored
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cache store element with a expired time
|
||||||
|
type Cache[K comparable, V any] struct {
|
||||||
|
*cache[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
type cache[K comparable, V any] struct {
|
||||||
|
mapping sync.Map
|
||||||
|
janitor *janitor[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
type element[V any] struct {
|
||||||
|
Expired time.Time
|
||||||
|
Payload V
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put element in Cache with its ttl
|
||||||
|
func (c *cache[K, V]) Put(key K, payload V, ttl time.Duration) {
|
||||||
|
c.mapping.Store(key, &element[V]{
|
||||||
|
Payload: payload,
|
||||||
|
Expired: time.Now().Add(ttl),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get element in Cache, and drop when it expired
|
||||||
|
func (c *cache[K, V]) Get(key K) V {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return getZero[V]()
|
||||||
|
}
|
||||||
|
elm := item.(*element[V])
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return getZero[V]()
|
||||||
|
}
|
||||||
|
return elm.Payload
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire element in Cache with Expire Time
|
||||||
|
func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
||||||
|
item, exist := c.mapping.Load(key)
|
||||||
|
if !exist {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
elm := item.(*element[V])
|
||||||
|
// expired
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return elm.Payload, elm.Expired
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cache[K, V]) cleanup() {
|
||||||
|
c.mapping.Range(func(k, v any) bool {
|
||||||
|
key := k
|
||||||
|
elm := v.(*element[V])
|
||||||
|
if time.Since(elm.Expired) > 0 {
|
||||||
|
c.mapping.Delete(key)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type janitor[K comparable, V any] struct {
|
||||||
|
interval time.Duration
|
||||||
|
stop chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *janitor[K, V]) process(c *cache[K, V]) {
|
||||||
|
ticker := time.NewTicker(j.interval)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
c.cleanup()
|
||||||
|
case <-j.stop:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopJanitor[K comparable, V any](c *Cache[K, V]) {
|
||||||
|
c.janitor.stop <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// New return *Cache
|
||||||
|
func New[K comparable, V any](interval time.Duration) *Cache[K, V] {
|
||||||
|
j := &janitor[K, V]{
|
||||||
|
interval: interval,
|
||||||
|
stop: make(chan struct{}),
|
||||||
|
}
|
||||||
|
c := &cache[K, V]{janitor: j}
|
||||||
|
go j.process(c)
|
||||||
|
C := &Cache[K, V]{c}
|
||||||
|
runtime.SetFinalizer(C, stopJanitor[K, V])
|
||||||
|
return C
|
||||||
|
}
|
72
common/cache/cache_test.go
vendored
Normal file
72
common/cache/cache_test.go
vendored
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCache_Basic(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
d := New[string, string](interval)
|
||||||
|
d.Put("string", "a", ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
|
|
||||||
|
s := d.Get("string")
|
||||||
|
assert.Equal(t, s, "a", "should recv 'a'")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_TTL(t *testing.T) {
|
||||||
|
interval := 200 * time.Millisecond
|
||||||
|
ttl := 20 * time.Millisecond
|
||||||
|
now := time.Now()
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
c.Put("int2", 2, ttl)
|
||||||
|
|
||||||
|
i := c.Get("int")
|
||||||
|
_, expired := c.GetWithExpire("int2")
|
||||||
|
assert.Equal(t, i, 1, "should recv 1")
|
||||||
|
assert.True(t, now.Before(expired))
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i = c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int2")
|
||||||
|
assert.True(t, i == 0, "should recv 0")
|
||||||
|
assert.True(t, j == 0, "should recv 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoCleanup(t *testing.T) {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
|
||||||
|
time.Sleep(ttl * 2)
|
||||||
|
i := c.Get("int")
|
||||||
|
j, _ := c.GetWithExpire("int")
|
||||||
|
assert.True(t, i == 0, "should recv 0")
|
||||||
|
assert.True(t, j == 0, "should recv 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCache_AutoGC(t *testing.T) {
|
||||||
|
sign := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
interval := 10 * time.Millisecond
|
||||||
|
ttl := 15 * time.Millisecond
|
||||||
|
c := New[string, int](interval)
|
||||||
|
c.Put("int", 1, ttl)
|
||||||
|
sign <- struct{}{}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-sign
|
||||||
|
runtime.GC()
|
||||||
|
}
|
4
common/cache/lrucache.go
vendored
4
common/cache/lrucache.go
vendored
@ -65,8 +65,8 @@ type LruCache[K comparable, V any] struct {
|
|||||||
onEvict EvictCallback[K, V]
|
onEvict EvictCallback[K, V]
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates an LruCache
|
// NewLRUCache creates an LruCache
|
||||||
func New[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
func NewLRUCache[K comparable, V any](options ...Option[K, V]) *LruCache[K, V] {
|
||||||
lc := &LruCache[K, V]{
|
lc := &LruCache[K, V]{
|
||||||
lru: list.New[*entry[K, V]](),
|
lru: list.New[*entry[K, V]](),
|
||||||
cache: make(map[K]*list.Element[*entry[K, V]]),
|
cache: make(map[K]*list.Element[*entry[K, V]]),
|
||||||
|
20
common/cache/lrucache_test.go
vendored
20
common/cache/lrucache_test.go
vendored
@ -19,7 +19,7 @@ var entries = []struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUCache(t *testing.T) {
|
func TestLRUCache(t *testing.T) {
|
||||||
c := New[string, string]()
|
c := NewLRUCache[string, string]()
|
||||||
|
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
c.Set(e.key, e.value)
|
c.Set(e.key, e.value)
|
||||||
@ -45,7 +45,7 @@ func TestLRUCache(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUMaxAge(t *testing.T) {
|
func TestLRUMaxAge(t *testing.T) {
|
||||||
c := New[string, string](WithAge[string, string](86400))
|
c := NewLRUCache[string, string](WithAge[string, string](86400))
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expected := now + 86400
|
expected := now + 86400
|
||||||
@ -88,7 +88,7 @@ func TestLRUMaxAge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestLRUpdateOnGet(t *testing.T) {
|
func TestLRUpdateOnGet(t *testing.T) {
|
||||||
c := New[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
c := NewLRUCache[string, string](WithAge[string, string](86400), WithUpdateAgeOnGet[string, string]())
|
||||||
|
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
expires := now + 86400/2
|
expires := now + 86400/2
|
||||||
@ -103,7 +103,7 @@ func TestLRUpdateOnGet(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestMaxSize(t *testing.T) {
|
func TestMaxSize(t *testing.T) {
|
||||||
c := New[string, string](WithSize[string, string](2))
|
c := NewLRUCache[string, string](WithSize[string, string](2))
|
||||||
// Add one expired entry
|
// Add one expired entry
|
||||||
c.Set("foo", "bar")
|
c.Set("foo", "bar")
|
||||||
_, ok := c.Get("foo")
|
_, ok := c.Get("foo")
|
||||||
@ -117,7 +117,7 @@ func TestMaxSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExist(t *testing.T) {
|
func TestExist(t *testing.T) {
|
||||||
c := New[int, int](WithSize[int, int](1))
|
c := NewLRUCache[int, int](WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
assert.True(t, c.Exist(1))
|
assert.True(t, c.Exist(1))
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
@ -130,7 +130,7 @@ func TestEvict(t *testing.T) {
|
|||||||
temp = key + value
|
temp = key + value
|
||||||
}
|
}
|
||||||
|
|
||||||
c := New[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
c := NewLRUCache[int, int](WithEvict[int, int](evict), WithSize[int, int](1))
|
||||||
c.Set(1, 2)
|
c.Set(1, 2)
|
||||||
c.Set(2, 3)
|
c.Set(2, 3)
|
||||||
|
|
||||||
@ -138,7 +138,7 @@ func TestEvict(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSetWithExpire(t *testing.T) {
|
func TestSetWithExpire(t *testing.T) {
|
||||||
c := New[int, *struct{}](WithAge[int, *struct{}](1))
|
c := NewLRUCache[int, *struct{}](WithAge[int, *struct{}](1))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -153,7 +153,7 @@ func TestSetWithExpire(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStale(t *testing.T) {
|
func TestStale(t *testing.T) {
|
||||||
c := New[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
c := NewLRUCache[int, int](WithAge[int, int](1), WithStale[int, int](true))
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
tenSecBefore := time.Unix(now-10, 0)
|
tenSecBefore := time.Unix(now-10, 0)
|
||||||
@ -166,11 +166,11 @@ func TestStale(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCloneTo(t *testing.T) {
|
func TestCloneTo(t *testing.T) {
|
||||||
o := New[string, int](WithSize[string, int](10))
|
o := NewLRUCache[string, int](WithSize[string, int](10))
|
||||||
o.Set("1", 1)
|
o.Set("1", 1)
|
||||||
o.Set("2", 2)
|
o.Set("2", 2)
|
||||||
|
|
||||||
n := New[string, int](WithSize[string, int](2))
|
n := NewLRUCache[string, int](WithSize[string, int](2))
|
||||||
n.Set("3", 3)
|
n.Set("3", 3)
|
||||||
n.Set("4", 4)
|
n.Set("4", 4)
|
||||||
|
|
||||||
|
@ -1,25 +0,0 @@
|
|||||||
package callback
|
|
||||||
|
|
||||||
import (
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FirstWriteCallBackConn struct {
|
|
||||||
C.Conn
|
|
||||||
Callback func(error)
|
|
||||||
written bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FirstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
|
||||||
defer func() {
|
|
||||||
if !c.written {
|
|
||||||
c.written = true
|
|
||||||
c.Callback(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
return c.Conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *FirstWriteCallBackConn) Upstream() any {
|
|
||||||
return c.Conn
|
|
||||||
}
|
|
303
common/cert/cert.go
Normal file
303
common/cert/cert.go
Normal file
@ -0,0 +1,303 @@
|
|||||||
|
package cert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha1"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var currentSerialNumber = time.Now().Unix()
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
ca *x509.Certificate
|
||||||
|
caPrivateKey *rsa.PrivateKey
|
||||||
|
|
||||||
|
roots *x509.CertPool
|
||||||
|
|
||||||
|
privateKey *rsa.PrivateKey
|
||||||
|
|
||||||
|
validity time.Duration
|
||||||
|
keyID []byte
|
||||||
|
organization string
|
||||||
|
|
||||||
|
certsStorage CertsStorage
|
||||||
|
}
|
||||||
|
|
||||||
|
type CertsStorage interface {
|
||||||
|
Get(key string) (*tls.Certificate, bool)
|
||||||
|
|
||||||
|
Set(key string, cert *tls.Certificate)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
pub := privateKey.Public()
|
||||||
|
|
||||||
|
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
h := sha1.New()
|
||||||
|
_, err = h.Write(pkixPub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
keyID := h.Sum(nil)
|
||||||
|
|
||||||
|
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(serial),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: name,
|
||||||
|
Organization: []string{organization},
|
||||||
|
},
|
||||||
|
SubjectKeyId: keyID,
|
||||||
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
NotBefore: time.Now().Add(-validity),
|
||||||
|
NotAfter: time.Now().Add(validity),
|
||||||
|
DNSNames: []string{name},
|
||||||
|
IsCA: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
x509c, err := x509.ParseCertificate(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return x509c, privateKey, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConfig(ca *x509.Certificate, caPrivateKey *rsa.PrivateKey) (*Config, error) {
|
||||||
|
roots := x509.NewCertPool()
|
||||||
|
roots.AddCert(ca)
|
||||||
|
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pub := privateKey.Public()
|
||||||
|
|
||||||
|
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
h := sha1.New()
|
||||||
|
_, err = h.Write(pkixPub)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
keyID := h.Sum(nil)
|
||||||
|
|
||||||
|
return &Config{
|
||||||
|
ca: ca,
|
||||||
|
caPrivateKey: caPrivateKey,
|
||||||
|
privateKey: privateKey,
|
||||||
|
keyID: keyID,
|
||||||
|
validity: time.Hour,
|
||||||
|
organization: "Clash",
|
||||||
|
certsStorage: NewDomainTrieCertsStorage(),
|
||||||
|
roots: roots,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) GetCA() *x509.Certificate {
|
||||||
|
return c.ca
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) SetOrganization(organization string) {
|
||||||
|
c.organization = organization
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) SetValidity(validity time.Duration) {
|
||||||
|
c.validity = validity
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
|
host := clientHello.ServerName
|
||||||
|
if host == "" {
|
||||||
|
host = hostname
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.GetOrCreateCert(host)
|
||||||
|
},
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig.InsecureSkipVerify = true
|
||||||
|
|
||||||
|
return tlsConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) GetOrCreateCert(hostname string, ips ...net.IP) (*tls.Certificate, error) {
|
||||||
|
var leaf *x509.Certificate
|
||||||
|
tlsCertificate, ok := c.certsStorage.Get(hostname)
|
||||||
|
if ok {
|
||||||
|
leaf = tlsCertificate.Leaf
|
||||||
|
if _, err := leaf.Verify(x509.VerifyOptions{
|
||||||
|
DNSName: hostname,
|
||||||
|
Roots: c.roots,
|
||||||
|
}); err == nil {
|
||||||
|
return tlsCertificate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
key = hostname
|
||||||
|
topHost = hostname
|
||||||
|
wildcardHost = "*." + hostname
|
||||||
|
dnsNames []string
|
||||||
|
)
|
||||||
|
|
||||||
|
if ip := net.ParseIP(hostname); ip != nil {
|
||||||
|
ips = append(ips, ip)
|
||||||
|
} else {
|
||||||
|
parts := strings.Split(hostname, ".")
|
||||||
|
l := len(parts)
|
||||||
|
|
||||||
|
if leaf != nil {
|
||||||
|
dnsNames = append(dnsNames, leaf.DNSNames...)
|
||||||
|
}
|
||||||
|
|
||||||
|
if l > 2 {
|
||||||
|
topIndex := l - 2
|
||||||
|
topHost = strings.Join(parts[topIndex:], ".")
|
||||||
|
|
||||||
|
for i := topIndex; i > 0; i-- {
|
||||||
|
wildcardHost = "*." + strings.Join(parts[i:], ".")
|
||||||
|
|
||||||
|
if i == topIndex && (len(dnsNames) == 0 || dnsNames[0] != topHost) {
|
||||||
|
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||||
|
} else if !hasDnsNames(dnsNames, wildcardHost) {
|
||||||
|
dnsNames = append(dnsNames, wildcardHost)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dnsNames = append(dnsNames, topHost, wildcardHost)
|
||||||
|
}
|
||||||
|
|
||||||
|
key = "+." + topHost
|
||||||
|
}
|
||||||
|
|
||||||
|
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(serial),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
CommonName: topHost,
|
||||||
|
Organization: []string{c.organization},
|
||||||
|
},
|
||||||
|
SubjectKeyId: c.keyID,
|
||||||
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
NotBefore: time.Now().Add(-c.validity),
|
||||||
|
NotAfter: time.Now().Add(c.validity),
|
||||||
|
DNSNames: dnsNames,
|
||||||
|
IPAddresses: ips,
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
x509c, err := x509.ParseCertificate(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsCertificate = &tls.Certificate{
|
||||||
|
Certificate: [][]byte{raw, c.ca.Raw},
|
||||||
|
PrivateKey: c.privateKey,
|
||||||
|
Leaf: x509c,
|
||||||
|
}
|
||||||
|
|
||||||
|
c.certsStorage.Set(key, tlsCertificate)
|
||||||
|
return tlsCertificate, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateAndSave generate CA private key and CA certificate and dump them to file
|
||||||
|
func GenerateAndSave(caPath string, caKeyPath string) error {
|
||||||
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(time.Now().Unix()),
|
||||||
|
Subject: pkix.Name{
|
||||||
|
Country: []string{"US"},
|
||||||
|
CommonName: "Clash Root CA",
|
||||||
|
Organization: []string{"Clash Trust Services"},
|
||||||
|
},
|
||||||
|
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
NotBefore: time.Now().Add(-(time.Hour * 24 * 60)),
|
||||||
|
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 25),
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
IsCA: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
caRaw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, privateKey.Public(), privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
caOut, err := os.OpenFile(caPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func(caOut *os.File) {
|
||||||
|
_ = caOut.Close()
|
||||||
|
}(caOut)
|
||||||
|
|
||||||
|
if err = pem.Encode(caOut, &pem.Block{Type: "CERTIFICATE", Bytes: caRaw}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
caKeyOut, err := os.OpenFile(caKeyPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func(caKeyOut *os.File) {
|
||||||
|
_ = caKeyOut.Close()
|
||||||
|
}(caKeyOut)
|
||||||
|
|
||||||
|
if err = pem.Encode(caKeyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasDnsNames(dnsNames []string, hostname string) bool {
|
||||||
|
for _, name := range dnsNames {
|
||||||
|
if name == hostname {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
104
common/cert/cert_test.go
Normal file
104
common/cert/cert_test.go
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package cert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCert(t *testing.T) {
|
||||||
|
ca, privateKey, err := NewAuthority("Clash ca", "Clash", 24*time.Hour)
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.NotNil(t, ca)
|
||||||
|
assert.NotNil(t, privateKey)
|
||||||
|
|
||||||
|
c, err := NewConfig(ca, privateKey)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
c.SetValidity(20 * time.Hour)
|
||||||
|
c.SetOrganization("Test Organization")
|
||||||
|
|
||||||
|
conf := c.NewTLSConfigForHost("example.org")
|
||||||
|
assert.Equal(t, []string{"http/1.1"}, conf.NextProtos)
|
||||||
|
assert.True(t, conf.InsecureSkipVerify)
|
||||||
|
|
||||||
|
// Test generating a certificate
|
||||||
|
clientHello := &tls.ClientHelloInfo{
|
||||||
|
ServerName: "example.org",
|
||||||
|
}
|
||||||
|
tlsCert, err := conf.GetCertificate(clientHello)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.NotNil(t, tlsCert)
|
||||||
|
|
||||||
|
// Assert certificate details
|
||||||
|
x509c := tlsCert.Leaf
|
||||||
|
assert.Equal(t, "example.org", x509c.Subject.CommonName)
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("abc.example.org"))
|
||||||
|
assert.Equal(t, []string{"Test Organization"}, x509c.Subject.Organization)
|
||||||
|
assert.NotNil(t, x509c.SubjectKeyId)
|
||||||
|
assert.True(t, x509c.BasicConstraintsValid)
|
||||||
|
assert.True(t, x509c.KeyUsage&x509.KeyUsageKeyEncipherment == x509.KeyUsageKeyEncipherment)
|
||||||
|
assert.True(t, x509c.KeyUsage&x509.KeyUsageDigitalSignature == x509.KeyUsageDigitalSignature)
|
||||||
|
assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, x509c.ExtKeyUsage)
|
||||||
|
assert.Equal(t, []string{"example.org", "*.example.org"}, x509c.DNSNames)
|
||||||
|
assert.True(t, x509c.NotBefore.Before(time.Now().Add(-2*time.Hour)))
|
||||||
|
assert.True(t, x509c.NotAfter.After(time.Now().Add(2*time.Hour)))
|
||||||
|
|
||||||
|
// Check that certificate is cached
|
||||||
|
tlsCert2, err := c.GetOrCreateCert("abc.example.org")
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.True(t, tlsCert == tlsCert2)
|
||||||
|
|
||||||
|
// Check that certificate is new
|
||||||
|
_, _ = c.GetOrCreateCert("a.b.c.d.e.f.g.h.i.j.example.org")
|
||||||
|
tlsCert3, err := c.GetOrCreateCert("m.k.l.example.org")
|
||||||
|
x509c = tlsCert3.Leaf
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.False(t, tlsCert == tlsCert3)
|
||||||
|
assert.Equal(t, []string{"example.org", "*.example.org", "*.j.example.org", "*.i.j.example.org", "*.h.i.j.example.org", "*.g.h.i.j.example.org", "*.f.g.h.i.j.example.org", "*.e.f.g.h.i.j.example.org", "*.d.e.f.g.h.i.j.example.org", "*.c.d.e.f.g.h.i.j.example.org", "*.b.c.d.e.f.g.h.i.j.example.org", "*.l.example.org", "*.k.l.example.org"}, x509c.DNSNames)
|
||||||
|
|
||||||
|
// Check that certificate is cached
|
||||||
|
tlsCert4, err := c.GetOrCreateCert("xyz.example.org")
|
||||||
|
x509c = tlsCert4.Leaf
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.True(t, tlsCert3 == tlsCert4)
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("jkf.example.org"))
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("n.j.example.org"))
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("c.i.j.example.org"))
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("m.l.example.org"))
|
||||||
|
assert.Error(t, x509c.VerifyHostname("m.l.jkf.example.org"))
|
||||||
|
|
||||||
|
// Check the certificate for an IP
|
||||||
|
tlsCertForIP, err := c.GetOrCreateCert("192.168.0.1")
|
||||||
|
x509c = tlsCertForIP.Leaf
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, 1, len(x509c.IPAddresses))
|
||||||
|
assert.True(t, net.ParseIP("192.168.0.1").Equal(x509c.IPAddresses[0]))
|
||||||
|
|
||||||
|
// Check that certificate is cached
|
||||||
|
tlsCertForIP2, err := c.GetOrCreateCert("192.168.0.1")
|
||||||
|
x509c = tlsCertForIP2.Leaf
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.True(t, tlsCertForIP == tlsCertForIP2)
|
||||||
|
assert.Nil(t, x509c.VerifyHostname("192.168.0.1"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateAndSave(t *testing.T) {
|
||||||
|
caPath := "ca.crt"
|
||||||
|
caKeyPath := "ca.key"
|
||||||
|
|
||||||
|
err := GenerateAndSave(caPath, caKeyPath)
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
_ = os.Remove(caPath)
|
||||||
|
_ = os.Remove(caKeyPath)
|
||||||
|
}
|
32
common/cert/storage.go
Normal file
32
common/cert/storage.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package cert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DomainTrieCertsStorage cache wildcard certificates
|
||||||
|
type DomainTrieCertsStorage struct {
|
||||||
|
certsCache *trie.DomainTrie[*tls.Certificate]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gets the certificate from the storage
|
||||||
|
func (c *DomainTrieCertsStorage) Get(key string) (*tls.Certificate, bool) {
|
||||||
|
ca := c.certsCache.Search(key)
|
||||||
|
if ca == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return ca.Data, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set saves the certificate to the storage
|
||||||
|
func (c *DomainTrieCertsStorage) Set(key string, cert *tls.Certificate) {
|
||||||
|
_ = c.certsCache.Insert(key, cert)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDomainTrieCertsStorage() *DomainTrieCertsStorage {
|
||||||
|
return &DomainTrieCertsStorage{
|
||||||
|
certsCache: trie.New[*tls.Certificate](),
|
||||||
|
}
|
||||||
|
}
|
@ -14,9 +14,8 @@ func ExecCmd(cmdStr string) (string, error) {
|
|||||||
cmd = exec.Command(args[0])
|
cmd = exec.Command(args[0])
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command(args[0], args[1:]...)
|
cmd = exec.Command(args[0], args[1:]...)
|
||||||
|
|
||||||
}
|
}
|
||||||
prepareBackgroundCommand(cmd)
|
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os/exec"
|
|
||||||
)
|
|
||||||
|
|
||||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
|
||||||
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
|
|
||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os/exec"
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
|
||||||
}
|
|
@ -1,56 +0,0 @@
|
|||||||
package collections
|
|
||||||
|
|
||||||
import "sync"
|
|
||||||
|
|
||||||
type (
|
|
||||||
stack struct {
|
|
||||||
top *node
|
|
||||||
length int
|
|
||||||
lock *sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
node struct {
|
|
||||||
value interface{}
|
|
||||||
prev *node
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewStack Create a new stack
|
|
||||||
func NewStack() *stack {
|
|
||||||
return &stack{nil, 0, &sync.RWMutex{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len Return the number of items in the stack
|
|
||||||
func (this *stack) Len() int {
|
|
||||||
return this.length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Peek View the top item on the stack
|
|
||||||
func (this *stack) Peek() interface{} {
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return this.top.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pop the top item of the stack and return it
|
|
||||||
func (this *stack) Pop() interface{} {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
n := this.top
|
|
||||||
this.top = n.prev
|
|
||||||
this.length--
|
|
||||||
return n.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Push a value onto the top of the stack
|
|
||||||
func (this *stack) Push(value interface{}) {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
n := &node{value, this.top}
|
|
||||||
this.top = n
|
|
||||||
this.length++
|
|
||||||
}
|
|
@ -1,45 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
encRaw = base64.RawStdEncoding
|
|
||||||
enc = base64.StdEncoding
|
|
||||||
)
|
|
||||||
|
|
||||||
// DecodeBase64 try to decode content from the given bytes,
|
|
||||||
// which can be in base64.RawStdEncoding, base64.StdEncoding or just plaintext.
|
|
||||||
func DecodeBase64(buf []byte) []byte {
|
|
||||||
result, err := tryDecodeBase64(buf)
|
|
||||||
if err != nil {
|
|
||||||
return buf
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func tryDecodeBase64(buf []byte) ([]byte, error) {
|
|
||||||
dBuf := make([]byte, encRaw.DecodedLen(len(buf)))
|
|
||||||
n, err := encRaw.Decode(dBuf, buf)
|
|
||||||
if err != nil {
|
|
||||||
n, err = enc.Decode(dBuf, buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return dBuf[:n], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func urlSafe(data string) string {
|
|
||||||
return strings.NewReplacer("+", "-", "/", "_").Replace(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeUrlSafe(data string) string {
|
|
||||||
dcBuf, err := base64.RawURLEncoding.DecodeString(data)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(dcBuf)
|
|
||||||
}
|
|
@ -5,15 +5,38 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var enc = base64.StdEncoding
|
||||||
|
|
||||||
|
func DecodeBase64(buf []byte) ([]byte, error) {
|
||||||
|
dBuf := make([]byte, enc.DecodedLen(len(buf)))
|
||||||
|
n, err := enc.Decode(dBuf, buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dBuf[:n], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeBase64StringToString decode base64 string to string
|
||||||
|
func DecodeBase64StringToString(s string) (string, error) {
|
||||||
|
dBuf, err := enc.DecodeString(s)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(dBuf), nil
|
||||||
|
}
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
data := DecodeBase64(buf)
|
data, err := DecodeBase64(buf)
|
||||||
|
if err != nil {
|
||||||
|
data = buf
|
||||||
|
}
|
||||||
|
|
||||||
arr := strings.Split(string(data), "\n")
|
arr := strings.Split(string(data), "\n")
|
||||||
|
|
||||||
@ -33,39 +56,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
scheme = strings.ToLower(scheme)
|
scheme = strings.ToLower(scheme)
|
||||||
switch scheme {
|
switch scheme {
|
||||||
case "hysteria":
|
|
||||||
urlHysteria, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
query := urlHysteria.Query()
|
|
||||||
name := uniqueName(names, urlHysteria.Fragment)
|
|
||||||
hysteria := make(map[string]any, 20)
|
|
||||||
|
|
||||||
hysteria["name"] = name
|
|
||||||
hysteria["type"] = scheme
|
|
||||||
hysteria["server"] = urlHysteria.Hostname()
|
|
||||||
hysteria["port"] = urlHysteria.Port()
|
|
||||||
hysteria["sni"] = query.Get("peer")
|
|
||||||
hysteria["obfs"] = query.Get("obfs")
|
|
||||||
hysteria["alpn"] = []string{query.Get("alpn")}
|
|
||||||
hysteria["auth_str"] = query.Get("auth")
|
|
||||||
hysteria["protocol"] = query.Get("protocol")
|
|
||||||
up := query.Get("up")
|
|
||||||
down := query.Get("down")
|
|
||||||
if up == "" {
|
|
||||||
up = query.Get("upmbps")
|
|
||||||
}
|
|
||||||
if down == "" {
|
|
||||||
down = query.Get("downmbps")
|
|
||||||
}
|
|
||||||
hysteria["down"] = down
|
|
||||||
hysteria["up"] = up
|
|
||||||
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
|
||||||
|
|
||||||
proxies = append(proxies, hysteria)
|
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -83,7 +73,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["port"] = urlTrojan.Port()
|
trojan["port"] = urlTrojan.Port()
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
trojan["password"] = urlTrojan.User.Username()
|
||||||
trojan["udp"] = true
|
trojan["udp"] = true
|
||||||
trojan["skip-cert-verify"], _ = strconv.ParseBool(query.Get("allowInsecure"))
|
trojan["skip-cert-verify"] = false
|
||||||
|
|
||||||
sni := query.Get("sni")
|
sni := query.Get("sni")
|
||||||
if sni != "" {
|
if sni != "" {
|
||||||
@ -95,72 +85,23 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["network"] = network
|
trojan["network"] = network
|
||||||
}
|
}
|
||||||
|
|
||||||
switch network {
|
if network == "ws" {
|
||||||
case "ws":
|
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
|
|
||||||
|
headers["Host"] = RandHost()
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
|
||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
trojan["ws-opts"] = wsOpts
|
trojan["ws-opts"] = wsOpts
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
|
||||||
trojan["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
|
||||||
trojan["client-fingerprint"] = "chrome"
|
|
||||||
} else {
|
|
||||||
trojan["client-fingerprint"] = fingerprint
|
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
proxies = append(proxies, trojan)
|
||||||
|
|
||||||
case "vless":
|
|
||||||
urlVLess, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
query := urlVLess.Query()
|
|
||||||
vless := make(map[string]any, 20)
|
|
||||||
err = handleVShareLink(names, urlVLess, scheme, vless)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("error:%s line:%s", err.Error(), line)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if flow := query.Get("flow"); flow != "" {
|
|
||||||
vless["flow"] = strings.ToLower(flow)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, vless)
|
|
||||||
|
|
||||||
case "vmess":
|
case "vmess":
|
||||||
// V2RayN-styled share link
|
dcBuf, err := enc.DecodeString(body)
|
||||||
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
|
||||||
dcBuf, err := tryDecodeBase64([]byte(body))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Xray VMessAEAD share link
|
|
||||||
urlVMess, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
query := urlVMess.Query()
|
|
||||||
vmess := make(map[string]any, 20)
|
|
||||||
err = handleVShareLink(names, urlVMess, scheme, vmess)
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("error:%s line:%s", err.Error(), line)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
vmess["alterId"] = 0
|
|
||||||
vmess["cipher"] = "auto"
|
|
||||||
if encryption := query.Get("encryption"); encryption != "" {
|
|
||||||
vmess["cipher"] = encryption
|
|
||||||
}
|
|
||||||
proxies = append(proxies, vmess)
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,11 +111,8 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
if jsonDc.Decode(&values) != nil {
|
if jsonDc.Decode(&values) != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
tempName, ok := values["ps"].(string)
|
|
||||||
if !ok {
|
name := uniqueName(names, values["ps"].(string))
|
||||||
continue
|
|
||||||
}
|
|
||||||
name := uniqueName(names, tempName)
|
|
||||||
vmess := make(map[string]any, 20)
|
vmess := make(map[string]any, 20)
|
||||||
|
|
||||||
vmess["name"] = name
|
vmess["name"] = name
|
||||||
@ -182,86 +120,40 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["server"] = values["add"]
|
vmess["server"] = values["add"]
|
||||||
vmess["port"] = values["port"]
|
vmess["port"] = values["port"]
|
||||||
vmess["uuid"] = values["id"]
|
vmess["uuid"] = values["id"]
|
||||||
if alterId, ok := values["aid"]; ok {
|
vmess["alterId"] = values["aid"]
|
||||||
vmess["alterId"] = alterId
|
vmess["cipher"] = "auto"
|
||||||
} else {
|
|
||||||
vmess["alterId"] = 0
|
|
||||||
}
|
|
||||||
vmess["udp"] = true
|
vmess["udp"] = true
|
||||||
vmess["xudp"] = true
|
|
||||||
vmess["tls"] = false
|
|
||||||
vmess["skip-cert-verify"] = false
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
vmess["cipher"] = "auto"
|
host := values["host"]
|
||||||
if cipher, ok := values["scy"]; ok && cipher != "" {
|
|
||||||
vmess["cipher"] = cipher
|
|
||||||
}
|
|
||||||
|
|
||||||
if sni, ok := values["sni"]; ok && sni != "" {
|
|
||||||
vmess["servername"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(values["net"].(string))
|
network := strings.ToLower(values["net"].(string))
|
||||||
if values["type"] == "http" {
|
|
||||||
network = "http"
|
|
||||||
} else if network == "http" {
|
|
||||||
network = "h2"
|
|
||||||
}
|
|
||||||
vmess["network"] = network
|
vmess["network"] = network
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
tls := strings.ToLower(values["tls"].(string))
|
||||||
if strings.HasSuffix(tls, "tls") {
|
if tls != "" && tls != "0" && tls != "null" {
|
||||||
|
if host != nil {
|
||||||
|
vmess["servername"] = host
|
||||||
|
}
|
||||||
vmess["tls"] = true
|
vmess["tls"] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
switch network {
|
if network == "ws" {
|
||||||
case "http":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
httpOpts := make(map[string]any)
|
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
|
||||||
headers["Host"] = []string{host.(string)}
|
|
||||||
}
|
|
||||||
httpOpts["path"] = []string{"/"}
|
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
|
||||||
httpOpts["path"] = []string{path.(string)}
|
|
||||||
}
|
|
||||||
httpOpts["headers"] = headers
|
|
||||||
|
|
||||||
vmess["http-opts"] = httpOpts
|
|
||||||
|
|
||||||
case "h2":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
h2Opts := make(map[string]any)
|
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
|
||||||
headers["Host"] = []string{host.(string)}
|
|
||||||
}
|
|
||||||
|
|
||||||
h2Opts["path"] = values["path"]
|
|
||||||
h2Opts["headers"] = headers
|
|
||||||
|
|
||||||
vmess["h2-opts"] = h2Opts
|
|
||||||
|
|
||||||
case "ws":
|
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
wsOpts["path"] = []string{"/"}
|
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
headers["Host"] = RandHost()
|
||||||
headers["Host"] = host.(string)
|
headers["User-Agent"] = RandUserAgent()
|
||||||
}
|
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
if values["path"] != nil {
|
||||||
wsOpts["path"] = path.(string)
|
wsOpts["path"] = values["path"]
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
vmess["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
vmess["ws-opts"] = wsOpts
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = values["path"]
|
|
||||||
vmess["grpc-opts"] = grpcOpts
|
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, vmess)
|
proxies = append(proxies, vmess)
|
||||||
|
|
||||||
case "ss":
|
case "ss":
|
||||||
urlSS, err := url.Parse(line)
|
urlSS, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -272,7 +164,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
port := urlSS.Port()
|
port := urlSS.Port()
|
||||||
|
|
||||||
if port == "" {
|
if port == "" {
|
||||||
dcBuf, err := encRaw.DecodeString(urlSS.Host)
|
dcBuf, err := enc.DecodeString(urlSS.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -284,28 +176,23 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
cipherRaw = urlSS.User.Username()
|
cipher = urlSS.User.Username()
|
||||||
cipher string
|
password string
|
||||||
password string
|
|
||||||
)
|
)
|
||||||
cipher = cipherRaw
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
if password, found = urlSS.User.Password(); !found {
|
||||||
dcBuf, err := base64.RawURLEncoding.DecodeString(cipherRaw)
|
dcBuf, err := enc.DecodeString(cipher)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
dcBuf, _ = enc.DecodeString(cipherRaw)
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
if !found {
|
if !found {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err = VerifyMethod(cipher, password)
|
|
||||||
if err != nil {
|
|
||||||
dcBuf, _ = encRaw.DecodeString(cipherRaw)
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ss := make(map[string]any, 10)
|
ss := make(map[string]any, 20)
|
||||||
|
|
||||||
ss["name"] = name
|
ss["name"] = name
|
||||||
ss["type"] = scheme
|
ss["type"] = scheme
|
||||||
@ -313,22 +200,11 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
ss["port"] = urlSS.Port()
|
ss["port"] = urlSS.Port()
|
||||||
ss["cipher"] = cipher
|
ss["cipher"] = cipher
|
||||||
ss["password"] = password
|
ss["password"] = password
|
||||||
query := urlSS.Query()
|
|
||||||
ss["udp"] = true
|
ss["udp"] = true
|
||||||
if query.Get("udp-over-tcp") == "true" || query.Get("uot") == "1" {
|
|
||||||
ss["udp-over-tcp"] = true
|
|
||||||
}
|
|
||||||
if strings.Contains(query.Get("plugin"), "obfs") {
|
|
||||||
obfsParams := strings.Split(query.Get("plugin"), ";")
|
|
||||||
ss["plugin"] = "obfs"
|
|
||||||
ss["plugin-opts"] = map[string]any{
|
|
||||||
"host": obfsParams[2][10:],
|
|
||||||
"mode": obfsParams[1][5:],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
case "ssr":
|
case "ssr":
|
||||||
dcBuf, err := encRaw.DecodeString(body)
|
dcBuf, err := enc.DecodeString(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -385,6 +261,54 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, ssr)
|
proxies = append(proxies, ssr)
|
||||||
|
case "vless":
|
||||||
|
urlVless, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
query := urlVless.Query()
|
||||||
|
|
||||||
|
name := uniqueName(names, urlVless.Fragment)
|
||||||
|
vless := make(map[string]any, 20)
|
||||||
|
|
||||||
|
vless["name"] = name
|
||||||
|
vless["type"] = scheme
|
||||||
|
vless["server"] = urlVless.Hostname()
|
||||||
|
vless["port"] = urlVless.Port()
|
||||||
|
vless["uuid"] = urlVless.User.Username()
|
||||||
|
vless["udp"] = true
|
||||||
|
vless["skip-cert-verify"] = false
|
||||||
|
|
||||||
|
sni := query.Get("sni")
|
||||||
|
if sni != "" {
|
||||||
|
vless["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
flow := strings.ToLower(query.Get("flow"))
|
||||||
|
if flow != "" {
|
||||||
|
vless["flow"] = flow
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(query.Get("type"))
|
||||||
|
if network != "" {
|
||||||
|
vless["network"] = network
|
||||||
|
}
|
||||||
|
|
||||||
|
if network == "ws" {
|
||||||
|
headers := make(map[string]any)
|
||||||
|
wsOpts := make(map[string]any)
|
||||||
|
|
||||||
|
headers["Host"] = RandHost()
|
||||||
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
|
||||||
|
wsOpts["path"] = query.Get("path")
|
||||||
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
vless["ws-opts"] = wsOpts
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, vless)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -395,6 +319,18 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func urlSafe(data string) string {
|
||||||
|
return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_")
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeUrlSafe(data string) string {
|
||||||
|
dcBuf, err := base64.URLEncoding.DecodeString(data)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(dcBuf)
|
||||||
|
}
|
||||||
|
|
||||||
func uniqueName(names map[string]int, name string) string {
|
func uniqueName(names map[string]int, name string) string {
|
||||||
if index, ok := names[name]; ok {
|
if index, ok := names[name]; ok {
|
||||||
index++
|
index++
|
||||||
|
@ -2,14 +2,11 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
"github.com/gofrs/uuid"
|
||||||
|
|
||||||
"github.com/metacubex/sing-shadowsocks/shadowimpl"
|
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
var hostsSuffix = []string{
|
||||||
@ -32,7 +29,6 @@ var hostsSuffix = []string{
|
|||||||
".alidns.com",
|
".alidns.com",
|
||||||
".cdngslb.com",
|
".cdngslb.com",
|
||||||
".mxhichina.com",
|
".mxhichina.com",
|
||||||
".alibabadns.com",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var userAgents = []string{
|
var userAgents = []string{
|
||||||
@ -294,7 +290,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 +299,11 @@ func RandHost() string {
|
|||||||
prefix += string(buf[6:8]) + "-"
|
prefix += string(buf[6:8]) + "-"
|
||||||
prefix += string(buf[len(buf)-8:])
|
prefix += string(buf[len(buf)-8:])
|
||||||
|
|
||||||
return prefix + hostsSuffix[fastrand.Intn(hostsLen)]
|
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func RandUserAgent() string {
|
func RandUserAgent() string {
|
||||||
return userAgents[fastrand.Intn(uaLen)]
|
return userAgents[rand.Intn(uaLen)]
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
func SetUserAgent(header http.Header) {
|
||||||
@ -316,8 +313,3 @@ func SetUserAgent(header http.Header) {
|
|||||||
userAgent := RandUserAgent()
|
userAgent := RandUserAgent()
|
||||||
header.Set("User-Agent", userAgent)
|
header.Set("User-Agent", userAgent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func VerifyMethod(cipher, password string) (err error) {
|
|
||||||
_, err = shadowimpl.FetchMethod(cipher, password, time.Now)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
@ -1,129 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) error {
|
|
||||||
// Xray VMessAEAD / VLESS share link standard
|
|
||||||
// https://github.com/XTLS/Xray-core/discussions/716
|
|
||||||
query := url.Query()
|
|
||||||
proxy["name"] = uniqueName(names, url.Fragment)
|
|
||||||
if url.Hostname() == "" {
|
|
||||||
return errors.New("url.Hostname() is empty")
|
|
||||||
}
|
|
||||||
if url.Port() == "" {
|
|
||||||
return errors.New("url.Port() is empty")
|
|
||||||
}
|
|
||||||
proxy["type"] = scheme
|
|
||||||
proxy["server"] = url.Hostname()
|
|
||||||
proxy["port"] = url.Port()
|
|
||||||
proxy["uuid"] = url.User.Username()
|
|
||||||
proxy["udp"] = true
|
|
||||||
proxy["skip-cert-verify"] = false
|
|
||||||
proxy["tls"] = false
|
|
||||||
tls := strings.ToLower(query.Get("security"))
|
|
||||||
if strings.HasSuffix(tls, "tls") || tls == "reality" {
|
|
||||||
proxy["tls"] = true
|
|
||||||
if fingerprint := query.Get("fp"); fingerprint == "" {
|
|
||||||
proxy["client-fingerprint"] = "chrome"
|
|
||||||
} else {
|
|
||||||
proxy["client-fingerprint"] = fingerprint
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if sni := query.Get("sni"); sni != "" {
|
|
||||||
proxy["servername"] = sni
|
|
||||||
}
|
|
||||||
if realityPublicKey := query.Get("pbk"); realityPublicKey != "" {
|
|
||||||
proxy["reality-opts"] = map[string]any{
|
|
||||||
"public-key": realityPublicKey,
|
|
||||||
"short-id": query.Get("sid"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch query.Get("packetEncoding") {
|
|
||||||
case "none":
|
|
||||||
case "packet":
|
|
||||||
proxy["packet-addr"] = true
|
|
||||||
default:
|
|
||||||
proxy["xudp"] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
|
||||||
if network == "" {
|
|
||||||
network = "tcp"
|
|
||||||
}
|
|
||||||
fakeType := strings.ToLower(query.Get("headerType"))
|
|
||||||
if fakeType == "http" {
|
|
||||||
network = "http"
|
|
||||||
} else if network == "http" {
|
|
||||||
network = "h2"
|
|
||||||
}
|
|
||||||
proxy["network"] = network
|
|
||||||
switch network {
|
|
||||||
case "tcp":
|
|
||||||
if fakeType != "none" {
|
|
||||||
headers := make(map[string]any)
|
|
||||||
httpOpts := make(map[string]any)
|
|
||||||
httpOpts["path"] = []string{"/"}
|
|
||||||
|
|
||||||
if host := query.Get("host"); host != "" {
|
|
||||||
headers["Host"] = []string{host}
|
|
||||||
}
|
|
||||||
|
|
||||||
if method := query.Get("method"); method != "" {
|
|
||||||
httpOpts["method"] = method
|
|
||||||
}
|
|
||||||
|
|
||||||
if path := query.Get("path"); path != "" {
|
|
||||||
httpOpts["path"] = []string{path}
|
|
||||||
}
|
|
||||||
httpOpts["headers"] = headers
|
|
||||||
proxy["http-opts"] = httpOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
case "http":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
h2Opts := make(map[string]any)
|
|
||||||
h2Opts["path"] = []string{"/"}
|
|
||||||
if path := query.Get("path"); path != "" {
|
|
||||||
h2Opts["path"] = []string{path}
|
|
||||||
}
|
|
||||||
if host := query.Get("host"); host != "" {
|
|
||||||
h2Opts["host"] = []string{host}
|
|
||||||
}
|
|
||||||
h2Opts["headers"] = headers
|
|
||||||
proxy["h2-opts"] = h2Opts
|
|
||||||
|
|
||||||
case "ws":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
headers["Host"] = query.Get("host")
|
|
||||||
wsOpts["path"] = query.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
if earlyData := query.Get("ed"); earlyData != "" {
|
|
||||||
med, err := strconv.Atoi(earlyData)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("bad WebSocket max early data size: %v", err)
|
|
||||||
}
|
|
||||||
wsOpts["max-early-data"] = med
|
|
||||||
}
|
|
||||||
if earlyDataHeader := query.Get("eh"); earlyDataHeader != "" {
|
|
||||||
wsOpts["early-data-header-name"] = earlyDataHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
|
||||||
proxy["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
@ -5,10 +5,10 @@
|
|||||||
// Package list implements a doubly linked list.
|
// Package list implements a doubly linked list.
|
||||||
//
|
//
|
||||||
// To iterate over a list (where l is a *List):
|
// To iterate over a list (where l is a *List):
|
||||||
//
|
|
||||||
// for e := l.Front(); e != nil; e = e.Next() {
|
// for e := l.Front(); e != nil; e = e.Next() {
|
||||||
// // do something with e.Value
|
// // do something with e.Value
|
||||||
// }
|
// }
|
||||||
|
//
|
||||||
package list
|
package list
|
||||||
|
|
||||||
// Element is an element of a linked list.
|
// Element is an element of a linked list.
|
||||||
|
@ -1,36 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CustomAddr interface {
|
|
||||||
net.Addr
|
|
||||||
RawAddr() net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
type customAddr struct {
|
|
||||||
networkStr string
|
|
||||||
addrStr string
|
|
||||||
rawAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) Network() string {
|
|
||||||
return a.networkStr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) String() string {
|
|
||||||
return a.addrStr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a customAddr) RawAddr() net.Addr {
|
|
||||||
return a.rawAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCustomAddr(networkStr string, addrStr string, rawAddr net.Addr) CustomAddr {
|
|
||||||
return customAddr{
|
|
||||||
networkStr: networkStr,
|
|
||||||
addrStr: addrStr,
|
|
||||||
rawAddr: rawAddr,
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import "net"
|
|
||||||
|
|
||||||
type bindPacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Read(b []byte) (n int, err error) {
|
|
||||||
n, _, err = wpc.PacketConn.ReadFrom(b)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) Write(b []byte) (n int, err error) {
|
|
||||||
return wpc.PacketConn.WriteTo(b, wpc.rAddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) RemoteAddr() net.Addr {
|
|
||||||
return wpc.rAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wpc *bindPacketConn) LocalAddr() net.Addr {
|
|
||||||
if wpc.PacketConn.LocalAddr() == nil {
|
|
||||||
return &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
|
||||||
} else {
|
|
||||||
return wpc.PacketConn.LocalAddr()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBindPacketConn(pc net.PacketConn, rAddr net.Addr) net.Conn {
|
|
||||||
return &bindPacketConn{
|
|
||||||
PacketConn: pc,
|
|
||||||
rAddr: rAddr,
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,23 +3,18 @@ package net
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/buf"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ ExtendedConn = (*BufferedConn)(nil)
|
|
||||||
|
|
||||||
type BufferedConn struct {
|
type BufferedConn struct {
|
||||||
r *bufio.Reader
|
r *bufio.Reader
|
||||||
ExtendedConn
|
net.Conn
|
||||||
peeked bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBufferedConn(c net.Conn) *BufferedConn {
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
||||||
if bc, ok := c.(*BufferedConn); ok {
|
if bc, ok := c.(*BufferedConn); ok {
|
||||||
return bc
|
return bc
|
||||||
}
|
}
|
||||||
return &BufferedConn{bufio.NewReader(c), NewExtendedConn(c), false}
|
return &BufferedConn{bufio.NewReader(c), c}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reader returns the internal bufio.Reader.
|
// Reader returns the internal bufio.Reader.
|
||||||
@ -27,24 +22,11 @@ func (c *BufferedConn) Reader() *bufio.Reader {
|
|||||||
return c.r
|
return c.r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ResetPeeked() {
|
|
||||||
c.peeked = false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Peeked() bool {
|
|
||||||
return c.peeked
|
|
||||||
}
|
|
||||||
|
|
||||||
// Peek returns the next n bytes without advancing the reader.
|
// Peek returns the next n bytes without advancing the reader.
|
||||||
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
||||||
c.peeked = true
|
|
||||||
return c.r.Peek(n)
|
return c.r.Peek(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) Discard(n int) (discarded int, err error) {
|
|
||||||
return c.r.Discard(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Read(p []byte) (int, error) {
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
||||||
return c.r.Read(p)
|
return c.r.Read(p)
|
||||||
}
|
}
|
||||||
@ -60,22 +42,3 @@ func (c *BufferedConn) UnreadByte() error {
|
|||||||
func (c *BufferedConn) Buffered() int {
|
func (c *BufferedConn) Buffered() int {
|
||||||
return c.r.Buffered()
|
return c.r.Buffered()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
_, err = buffer.ReadOnceFrom(c.r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return c.ExtendedConn.ReadBuffer(buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) Upstream() any {
|
|
||||||
return c.ExtendedConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *BufferedConn) ReaderReplaceable() bool {
|
|
||||||
if c.r.Buffered() > 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
@ -1,104 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"runtime"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type refConn struct {
|
|
||||||
conn net.Conn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Read(b []byte) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Read(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Write(b []byte) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) RemoteAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.RemoteAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(c.ref)
|
|
||||||
return c.conn.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *refConn) Upstream() any {
|
|
||||||
return c.conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefConn(conn net.Conn, ref any) net.Conn {
|
|
||||||
return &refConn{conn: conn, ref: ref}
|
|
||||||
}
|
|
||||||
|
|
||||||
type refPacketConn struct {
|
|
||||||
pc net.PacketConn
|
|
||||||
ref any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.ReadFrom(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.WriteTo(p, addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) Close() error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) LocalAddr() net.Addr {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.LocalAddr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetReadDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *refPacketConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
defer runtime.KeepAlive(pc.ref)
|
|
||||||
return pc.pc.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefPacketConn(pc net.PacketConn, ref any) net.PacketConn {
|
|
||||||
return &refPacketConn{pc: pc, ref: ref}
|
|
||||||
}
|
|
@ -1,24 +1,39 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
//import (
|
import (
|
||||||
// "io"
|
"io"
|
||||||
// "net"
|
"net"
|
||||||
// "time"
|
"time"
|
||||||
//)
|
|
||||||
//
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
//// Relay copies between left and right bidirectionally.
|
)
|
||||||
//func Relay(leftConn, rightConn net.Conn) {
|
|
||||||
// ch := make(chan error)
|
// Relay copies between left and right bidirectionally.
|
||||||
//
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
// go func() {
|
ch := make(chan error)
|
||||||
// // Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
|
||||||
// // See also https://github.com/Dreamacro/clash/pull/1209
|
tcpKeepAlive(leftConn)
|
||||||
// _, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
tcpKeepAlive(rightConn)
|
||||||
// leftConn.SetReadDeadline(time.Now())
|
|
||||||
// ch <- err
|
go func() {
|
||||||
// }()
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
//
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// _, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
// rightConn.SetReadDeadline(time.Now())
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
// <-ch
|
_ = pool.Put(buf)
|
||||||
//}
|
_ = leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
|
_, _ = io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
|
_ = pool.Put(buf)
|
||||||
|
_ = rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
"github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
var NewExtendedConn = bufio.NewExtendedConn
|
|
||||||
var NewExtendedWriter = bufio.NewExtendedWriter
|
|
||||||
var NewExtendedReader = bufio.NewExtendedReader
|
|
||||||
|
|
||||||
type ExtendedConn = network.ExtendedConn
|
|
||||||
type ExtendedWriter = network.ExtendedWriter
|
|
||||||
type ExtendedReader = network.ExtendedReader
|
|
||||||
|
|
||||||
func NeedHandshake(conn any) bool {
|
|
||||||
if earlyConn, isEarlyConn := common.Cast[network.EarlyConn](conn); isEarlyConn && earlyConn.NeedHandshake() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
|
||||||
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn)
|
|
||||||
}
|
|
@ -1,46 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SplitNetworkType(s string) (string, string, error) {
|
|
||||||
var (
|
|
||||||
shecme string
|
|
||||||
hostPort string
|
|
||||||
)
|
|
||||||
result := strings.Split(s, "://")
|
|
||||||
if len(result) == 2 {
|
|
||||||
shecme = result[0]
|
|
||||||
hostPort = result[1]
|
|
||||||
} else if len(result) == 1 {
|
|
||||||
hostPort = result[0]
|
|
||||||
} else {
|
|
||||||
return "", "", fmt.Errorf("tcp/udp style error")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(shecme) == 0 {
|
|
||||||
shecme = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
if shecme != "tcp" && shecme != "udp" {
|
|
||||||
return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
|
|
||||||
} else {
|
|
||||||
return shecme, hostPort, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
|
||||||
temp := s
|
|
||||||
hasPort = true
|
|
||||||
|
|
||||||
if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
|
|
||||||
temp += ":0"
|
|
||||||
hasPort = false
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, err = net.SplitHostPort(temp)
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"math/big"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ParseCert(certificate, privateKey string) (tls.Certificate, error) {
|
|
||||||
if certificate == "" || privateKey == "" {
|
|
||||||
return newRandomTLSKeyPair()
|
|
||||||
}
|
|
||||||
cert, painTextErr := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
|
|
||||||
if painTextErr == nil {
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
cert, loadErr := tls.LoadX509KeyPair(certificate, privateKey)
|
|
||||||
if loadErr != nil {
|
|
||||||
return tls.Certificate{}, fmt.Errorf("parse certificate failed, maybe format error:%s, or path error: %s", painTextErr.Error(), loadErr.Error())
|
|
||||||
}
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRandomTLSKeyPair() (tls.Certificate, error) {
|
|
||||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
template := x509.Certificate{SerialNumber: big.NewInt(1)}
|
|
||||||
certDER, err := x509.CreateCertificate(
|
|
||||||
rand.Reader,
|
|
||||||
&template,
|
|
||||||
&template,
|
|
||||||
&key.PublicKey,
|
|
||||||
key)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
|
||||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
|
||||||
|
|
||||||
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
|
|
||||||
if err != nil {
|
|
||||||
return tls.Certificate{}, err
|
|
||||||
}
|
|
||||||
return tlsCert, nil
|
|
||||||
}
|
|
@ -1,131 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"math/bits"
|
|
||||||
)
|
|
||||||
|
|
||||||
// kanged from https://github.com/nhooyr/websocket/blob/master/frame.go
|
|
||||||
// License: MIT
|
|
||||||
|
|
||||||
// MaskWebSocket applies the WebSocket masking algorithm to p
|
|
||||||
// with the given key.
|
|
||||||
// See https://tools.ietf.org/html/rfc6455#section-5.3
|
|
||||||
//
|
|
||||||
// The returned value is the correctly rotated key to
|
|
||||||
// to continue to mask/unmask the message.
|
|
||||||
//
|
|
||||||
// It is optimized for LittleEndian and expects the key
|
|
||||||
// to be in little endian.
|
|
||||||
//
|
|
||||||
// See https://github.com/golang/go/issues/31586
|
|
||||||
func MaskWebSocket(key uint32, b []byte) uint32 {
|
|
||||||
if len(b) >= 8 {
|
|
||||||
key64 := uint64(key)<<32 | uint64(key)
|
|
||||||
|
|
||||||
// At some point in the future we can clean these unrolled loops up.
|
|
||||||
// See https://github.com/golang/go/issues/31586#issuecomment-487436401
|
|
||||||
|
|
||||||
// Then we xor until b is less than 128 bytes.
|
|
||||||
for len(b) >= 128 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[32:40])
|
|
||||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[40:48])
|
|
||||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[48:56])
|
|
||||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[56:64])
|
|
||||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[64:72])
|
|
||||||
binary.LittleEndian.PutUint64(b[64:72], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[72:80])
|
|
||||||
binary.LittleEndian.PutUint64(b[72:80], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[80:88])
|
|
||||||
binary.LittleEndian.PutUint64(b[80:88], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[88:96])
|
|
||||||
binary.LittleEndian.PutUint64(b[88:96], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[96:104])
|
|
||||||
binary.LittleEndian.PutUint64(b[96:104], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[104:112])
|
|
||||||
binary.LittleEndian.PutUint64(b[104:112], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[112:120])
|
|
||||||
binary.LittleEndian.PutUint64(b[112:120], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[120:128])
|
|
||||||
binary.LittleEndian.PutUint64(b[120:128], v^key64)
|
|
||||||
b = b[128:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 64 bytes.
|
|
||||||
for len(b) >= 64 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[32:40])
|
|
||||||
binary.LittleEndian.PutUint64(b[32:40], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[40:48])
|
|
||||||
binary.LittleEndian.PutUint64(b[40:48], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[48:56])
|
|
||||||
binary.LittleEndian.PutUint64(b[48:56], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[56:64])
|
|
||||||
binary.LittleEndian.PutUint64(b[56:64], v^key64)
|
|
||||||
b = b[64:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 32 bytes.
|
|
||||||
for len(b) >= 32 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[16:24])
|
|
||||||
binary.LittleEndian.PutUint64(b[16:24], v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[24:32])
|
|
||||||
binary.LittleEndian.PutUint64(b[24:32], v^key64)
|
|
||||||
b = b[32:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 16 bytes.
|
|
||||||
for len(b) >= 16 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
v = binary.LittleEndian.Uint64(b[8:16])
|
|
||||||
binary.LittleEndian.PutUint64(b[8:16], v^key64)
|
|
||||||
b = b[16:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 8 bytes.
|
|
||||||
for len(b) >= 8 {
|
|
||||||
v := binary.LittleEndian.Uint64(b)
|
|
||||||
binary.LittleEndian.PutUint64(b, v^key64)
|
|
||||||
b = b[8:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then we xor until b is less than 4 bytes.
|
|
||||||
for len(b) >= 4 {
|
|
||||||
v := binary.LittleEndian.Uint32(b)
|
|
||||||
binary.LittleEndian.PutUint32(b, v^key)
|
|
||||||
b = b[4:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// xor remaining bytes.
|
|
||||||
for i := range b {
|
|
||||||
b[i] ^= byte(key)
|
|
||||||
key = bits.RotateLeft32(key, -8)
|
|
||||||
}
|
|
||||||
|
|
||||||
return key
|
|
||||||
}
|
|
@ -1,10 +1,10 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math/rand"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/zhangyunhao116/fastrand"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAllocGet(t *testing.T) {
|
func TestAllocGet(t *testing.T) {
|
||||||
@ -43,6 +43,6 @@ func TestAllocPutThenGet(t *testing.T) {
|
|||||||
|
|
||||||
func BenchmarkMSB(b *testing.B) {
|
func BenchmarkMSB(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
msb(fastrand.Int())
|
msb(rand.Int())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,15 +0,0 @@
|
|||||||
//go:build with_low_memory
|
|
||||||
|
|
||||||
package pool
|
|
||||||
|
|
||||||
const (
|
|
||||||
// io.Copy default buffer size is 32 KiB
|
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
|
||||||
RelayBufferSize = 16 * 1024
|
|
||||||
|
|
||||||
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
|
||||||
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
|
||||||
// set to 9000, so the UDP Buffer size set to 16Kib
|
|
||||||
UDPBufferSize = 8 * 1024
|
|
||||||
)
|
|
@ -1,15 +0,0 @@
|
|||||||
//go:build !with_low_memory
|
|
||||||
|
|
||||||
package pool
|
|
||||||
|
|
||||||
const (
|
|
||||||
// io.Copy default buffer size is 32 KiB
|
|
||||||
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
|
||||||
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
|
||||||
RelayBufferSize = 20 * 1024
|
|
||||||
|
|
||||||
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
|
||||||
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
|
||||||
// set to 9000, so the UDP Buffer size set to 16Kib
|
|
||||||
UDPBufferSize = 16 * 1024
|
|
||||||
)
|
|
@ -1,5 +1,17 @@
|
|||||||
package pool
|
package pool
|
||||||
|
|
||||||
|
const (
|
||||||
|
// io.Copy default buffer size is 32 KiB
|
||||||
|
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
|
||||||
|
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
|
||||||
|
RelayBufferSize = 20 * 1024
|
||||||
|
|
||||||
|
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
|
||||||
|
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
|
||||||
|
// set to 9000, so the UDP Buffer size set to 16Kib
|
||||||
|
UDPBufferSize = 16 * 1024
|
||||||
|
)
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return defaultAllocator.Get(size)
|
return defaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
@ -1,7 +0,0 @@
|
|||||||
package pool
|
|
||||||
|
|
||||||
import "github.com/sagernet/sing/common/buf"
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
buf.DefaultAllocator = defaultAllocator
|
|
||||||
}
|
|
@ -1,132 +1,107 @@
|
|||||||
package sniffer
|
package tls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/utils"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/sniffer"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrNoClue = errors.New("not enough information for making a decision")
|
||||||
|
|
||||||
|
type SniffHeader struct {
|
||||||
|
domain string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SniffHeader) Protocol() string {
|
||||||
|
return "tls"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SniffHeader) Domain() string {
|
||||||
|
return h.domain
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errNotTLS = errors.New("not TLS header")
|
errNotTLS = errors.New("not TLS header")
|
||||||
errNotClientHello = errors.New("not client hello")
|
errNotClientHello = errors.New("not client hello")
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ sniffer.Sniffer = (*TLSSniffer)(nil)
|
|
||||||
|
|
||||||
type TLSSniffer struct {
|
|
||||||
*BaseSniffer
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTLSSniffer(snifferConfig SnifferConfig) (*TLSSniffer, error) {
|
|
||||||
ports := make([]utils.Range[uint16], 0)
|
|
||||||
if len(snifferConfig.Ports) == 0 {
|
|
||||||
ports = append(ports, *utils.NewRange[uint16](443, 443))
|
|
||||||
} else {
|
|
||||||
ports = append(ports, snifferConfig.Ports...)
|
|
||||||
}
|
|
||||||
return &TLSSniffer{
|
|
||||||
BaseSniffer: NewBaseSniffer(ports, C.TCP),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tls *TLSSniffer) Protocol() string {
|
|
||||||
return "tls"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tls *TLSSniffer) SupportNetwork() C.NetWork {
|
|
||||||
return C.TCP
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tls *TLSSniffer) SniffTCP(bytes []byte) (string, error) {
|
|
||||||
domain, err := SniffTLS(bytes)
|
|
||||||
if err == nil {
|
|
||||||
return *domain, nil
|
|
||||||
} else {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsValidTLSVersion(major, minor byte) bool {
|
func IsValidTLSVersion(major, minor byte) bool {
|
||||||
return major == 3
|
return major == 3
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadClientHello returns server name (if any) from TLS client hello message.
|
// ReadClientHello returns server name (if any) from TLS client hello message.
|
||||||
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
|
// https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go#L300
|
||||||
func ReadClientHello(data []byte) (*string, error) {
|
func ReadClientHello(data []byte, h *SniffHeader) error {
|
||||||
if len(data) < 42 {
|
if len(data) < 42 {
|
||||||
return nil, ErrNoClue
|
return ErrNoClue
|
||||||
}
|
}
|
||||||
sessionIDLen := int(data[38])
|
sessionIDLen := int(data[38])
|
||||||
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
|
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
|
||||||
return nil, ErrNoClue
|
return ErrNoClue
|
||||||
}
|
}
|
||||||
data = data[39+sessionIDLen:]
|
data = data[39+sessionIDLen:]
|
||||||
if len(data) < 2 {
|
if len(data) < 2 {
|
||||||
return nil, ErrNoClue
|
return ErrNoClue
|
||||||
}
|
}
|
||||||
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
||||||
// they are uint16s, the number must be even.
|
// they are uint16s, the number must be even.
|
||||||
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
||||||
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
data = data[2+cipherSuiteLen:]
|
data = data[2+cipherSuiteLen:]
|
||||||
if len(data) < 1 {
|
if len(data) < 1 {
|
||||||
return nil, ErrNoClue
|
return ErrNoClue
|
||||||
}
|
}
|
||||||
compressionMethodsLen := int(data[0])
|
compressionMethodsLen := int(data[0])
|
||||||
if len(data) < 1+compressionMethodsLen {
|
if len(data) < 1+compressionMethodsLen {
|
||||||
return nil, ErrNoClue
|
return ErrNoClue
|
||||||
}
|
}
|
||||||
data = data[1+compressionMethodsLen:]
|
data = data[1+compressionMethodsLen:]
|
||||||
|
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
if len(data) < 2 {
|
if len(data) < 2 {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
extensionsLength := int(data[0])<<8 | int(data[1])
|
extensionsLength := int(data[0])<<8 | int(data[1])
|
||||||
data = data[2:]
|
data = data[2:]
|
||||||
if extensionsLength != len(data) {
|
if extensionsLength != len(data) {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
for len(data) != 0 {
|
for len(data) != 0 {
|
||||||
if len(data) < 4 {
|
if len(data) < 4 {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
extension := uint16(data[0])<<8 | uint16(data[1])
|
extension := uint16(data[0])<<8 | uint16(data[1])
|
||||||
length := int(data[2])<<8 | int(data[3])
|
length := int(data[2])<<8 | int(data[3])
|
||||||
data = data[4:]
|
data = data[4:]
|
||||||
if len(data) < length {
|
if len(data) < length {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
|
|
||||||
if extension == 0x00 { /* extensionServerName */
|
if extension == 0x00 { /* extensionServerName */
|
||||||
d := data[:length]
|
d := data[:length]
|
||||||
if len(d) < 2 {
|
if len(d) < 2 {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
namesLen := int(d[0])<<8 | int(d[1])
|
namesLen := int(d[0])<<8 | int(d[1])
|
||||||
d = d[2:]
|
d = d[2:]
|
||||||
if len(d) != namesLen {
|
if len(d) != namesLen {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
for len(d) > 0 {
|
for len(d) > 0 {
|
||||||
if len(d) < 3 {
|
if len(d) < 3 {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
nameType := d[0]
|
nameType := d[0]
|
||||||
nameLen := int(d[1])<<8 | int(d[2])
|
nameLen := int(d[1])<<8 | int(d[2])
|
||||||
d = d[3:]
|
d = d[3:]
|
||||||
if len(d) < nameLen {
|
if len(d) < nameLen {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
if nameType == 0 {
|
if nameType == 0 {
|
||||||
serverName := string(d[:nameLen])
|
serverName := string(d[:nameLen])
|
||||||
@ -134,22 +109,21 @@ func ReadClientHello(data []byte) (*string, error) {
|
|||||||
// trailing dot. See
|
// trailing dot. See
|
||||||
// https://tools.ietf.org/html/rfc6066#section-3.
|
// https://tools.ietf.org/html/rfc6066#section-3.
|
||||||
if strings.HasSuffix(serverName, ".") {
|
if strings.HasSuffix(serverName, ".") {
|
||||||
return nil, errNotClientHello
|
return errNotClientHello
|
||||||
}
|
}
|
||||||
|
h.domain = serverName
|
||||||
return &serverName, nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
d = d[nameLen:]
|
d = d[nameLen:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data = data[length:]
|
data = data[length:]
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errNotTLS
|
return errNotTLS
|
||||||
}
|
}
|
||||||
|
|
||||||
func SniffTLS(b []byte) (*string, error) {
|
func SniffTLS(b []byte) (*SniffHeader, error) {
|
||||||
if len(b) < 5 {
|
if len(b) < 5 {
|
||||||
return nil, ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
@ -165,9 +139,10 @@ func SniffTLS(b []byte) (*string, error) {
|
|||||||
return nil, ErrNoClue
|
return nil, ErrNoClue
|
||||||
}
|
}
|
||||||
|
|
||||||
domain, err := ReadClientHello(b[5 : 5+headerLen])
|
h := &SniffHeader{}
|
||||||
|
err := ReadClientHello(b[5:5+headerLen], h)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return domain, nil
|
return h, nil
|
||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package sniffer
|
package tls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
@ -142,7 +142,7 @@ func TestTLSHeaders(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range cases {
|
for _, test := range cases {
|
||||||
domain, err := SniffTLS(test.input)
|
header, err := SniffTLS(test.input)
|
||||||
if test.err {
|
if test.err {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("Exepct error but nil in test %v", test)
|
t.Errorf("Exepct error but nil in test %v", test)
|
||||||
@ -151,8 +151,8 @@ func TestTLSHeaders(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
|
t.Errorf("Expect no error but actually %s in test %v", err.Error(), test)
|
||||||
}
|
}
|
||||||
if *domain != test.domain {
|
if header.Domain() != test.domain {
|
||||||
t.Error("expect domain ", test.domain, " but got ", domain)
|
t.Error("expect domain ", test.domain, " but got ", header.Domain())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,7 +3,6 @@ package structure
|
|||||||
// references: https://github.com/mitchellh/mapstructure
|
// references: https://github.com/mitchellh/mapstructure
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -14,11 +13,8 @@ import (
|
|||||||
type Option struct {
|
type Option struct {
|
||||||
TagName string
|
TagName string
|
||||||
WeaklyTypedInput bool
|
WeaklyTypedInput bool
|
||||||
KeyReplacer *strings.Replacer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var DefaultKeyReplacer = strings.NewReplacer("_", "-")
|
|
||||||
|
|
||||||
// Decoder is the core of structure
|
// Decoder is the core of structure
|
||||||
type Decoder struct {
|
type Decoder struct {
|
||||||
option *Option
|
option *Option
|
||||||
@ -35,7 +31,7 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
// Decode transform a map[string]any to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
return fmt.Errorf("decode must recive a ptr struct")
|
return fmt.Errorf("Decode must recive a ptr struct")
|
||||||
}
|
}
|
||||||
t := reflect.TypeOf(dst).Elem()
|
t := reflect.TypeOf(dst).Elem()
|
||||||
v := reflect.ValueOf(dst).Elem()
|
v := reflect.ValueOf(dst).Elem()
|
||||||
@ -53,23 +49,6 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
omitempty := found && omitKey == "omitempty"
|
omitempty := found && omitKey == "omitempty"
|
||||||
|
|
||||||
value, ok := src[key]
|
value, ok := src[key]
|
||||||
if !ok {
|
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
key = d.option.KeyReplacer.Replace(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _strKey := range src {
|
|
||||||
strKey := _strKey
|
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
strKey = d.option.KeyReplacer.Replace(strKey)
|
|
||||||
}
|
|
||||||
if strings.EqualFold(key, strKey) {
|
|
||||||
value = src[_strKey]
|
|
||||||
ok = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !ok || value == nil {
|
if !ok || value == nil {
|
||||||
if omitempty {
|
if omitempty {
|
||||||
continue
|
continue
|
||||||
@ -86,16 +65,9 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
||||||
kind := val.Kind()
|
switch val.Kind() {
|
||||||
switch {
|
case reflect.Int:
|
||||||
case isInt(kind):
|
|
||||||
return d.decodeInt(name, data, val)
|
return d.decodeInt(name, data, val)
|
||||||
case isUint(kind):
|
|
||||||
return d.decodeUint(name, data, val)
|
|
||||||
case isFloat(kind):
|
|
||||||
return d.decodeFloat(name, data, val)
|
|
||||||
}
|
|
||||||
switch kind {
|
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
return d.decodeString(name, data, val)
|
return d.decodeString(name, data, val)
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
@ -113,42 +85,13 @@ func (d *Decoder) decode(name string, data any, val reflect.Value) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isInt(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isUint(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isFloat(kind reflect.Kind) bool {
|
|
||||||
switch kind {
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case isInt(kind):
|
case kind == reflect.Int:
|
||||||
val.SetInt(dataVal.Int())
|
val.SetInt(dataVal.Int())
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
|
||||||
val.SetInt(int64(dataVal.Uint()))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetInt(int64(dataVal.Float()))
|
val.SetInt(int64(dataVal.Float()))
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
case kind == reflect.String && d.option.WeaklyTypedInput:
|
||||||
var i int64
|
var i int64
|
||||||
@ -167,72 +110,14 @@ func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Decoder) decodeUint(name string, data any, val reflect.Value) (err error) {
|
|
||||||
dataVal := reflect.ValueOf(data)
|
|
||||||
kind := dataVal.Kind()
|
|
||||||
switch {
|
|
||||||
case isUint(kind):
|
|
||||||
val.SetUint(dataVal.Uint())
|
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetUint(uint64(dataVal.Int()))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetUint(uint64(dataVal.Float()))
|
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
|
||||||
var i uint64
|
|
||||||
i, err = strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
|
|
||||||
if err == nil {
|
|
||||||
val.SetUint(i)
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf(
|
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
|
||||||
name, val.Type(), dataVal.Type(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeFloat(name string, data any, val reflect.Value) (err error) {
|
|
||||||
dataVal := reflect.ValueOf(data)
|
|
||||||
kind := dataVal.Kind()
|
|
||||||
switch {
|
|
||||||
case isFloat(kind):
|
|
||||||
val.SetFloat(dataVal.Float())
|
|
||||||
case isUint(kind):
|
|
||||||
val.SetFloat(float64(dataVal.Uint()))
|
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetFloat(float64(dataVal.Int()))
|
|
||||||
case kind == reflect.String && d.option.WeaklyTypedInput:
|
|
||||||
var i float64
|
|
||||||
i, err = strconv.ParseFloat(dataVal.String(), val.Type().Bits())
|
|
||||||
if err == nil {
|
|
||||||
val.SetFloat(i)
|
|
||||||
} else {
|
|
||||||
err = fmt.Errorf("cannot parse '%s' as int: %s", name, err)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf(
|
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
|
||||||
name, val.Type(), dataVal.Type(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
kind := dataVal.Kind()
|
kind := dataVal.Kind()
|
||||||
switch {
|
switch {
|
||||||
case kind == reflect.String:
|
case kind == reflect.String:
|
||||||
val.SetString(dataVal.String())
|
val.SetString(dataVal.String())
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
val.SetString(strconv.FormatInt(dataVal.Int(), 10))
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
|
||||||
case isFloat(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatFloat(dataVal.Float(), 'E', -1, dataVal.Type().Bits()))
|
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -248,10 +133,8 @@ func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err erro
|
|||||||
switch {
|
switch {
|
||||||
case kind == reflect.Bool:
|
case kind == reflect.Bool:
|
||||||
val.SetBool(dataVal.Bool())
|
val.SetBool(dataVal.Bool())
|
||||||
case isInt(kind) && d.option.WeaklyTypedInput:
|
case kind == reflect.Int && d.option.WeaklyTypedInput:
|
||||||
val.SetBool(dataVal.Int() != 0)
|
val.SetBool(dataVal.Int() != 0)
|
||||||
case isUint(kind) && d.option.WeaklyTypedInput:
|
|
||||||
val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
|
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf(
|
err = fmt.Errorf(
|
||||||
"'%s' expected type '%s', got unconvertible type '%s'",
|
"'%s' expected type '%s', got unconvertible type '%s'",
|
||||||
@ -266,17 +149,6 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
valType := val.Type()
|
valType := val.Type()
|
||||||
valElemType := valType.Elem()
|
valElemType := valType.Elem()
|
||||||
|
|
||||||
if dataVal.Kind() == reflect.String && valElemType.Kind() == reflect.Uint8 { // from encoding/json
|
|
||||||
s := []byte(dataVal.String())
|
|
||||||
b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
|
|
||||||
n, err := base64.StdEncoding.Decode(b, s)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("try decode '%s' by base64 error: %w", name, err)
|
|
||||||
}
|
|
||||||
val.SetBytes(b[:n])
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if dataVal.Kind() != reflect.Slice {
|
if dataVal.Kind() != reflect.Slice {
|
||||||
return fmt.Errorf("'%s' is not a slice", name)
|
return fmt.Errorf("'%s' is not a slice", name)
|
||||||
}
|
}
|
||||||
@ -429,7 +301,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
field reflect.StructField
|
field reflect.StructField
|
||||||
val reflect.Value
|
val reflect.Value
|
||||||
}
|
}
|
||||||
var fields []field
|
fields := []field{}
|
||||||
for len(structs) > 0 {
|
for len(structs) > 0 {
|
||||||
structVal := structs[0]
|
structVal := structs[0]
|
||||||
structs = structs[1:]
|
structs = structs[1:]
|
||||||
@ -481,18 +353,12 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
if !rawMapVal.IsValid() {
|
if !rawMapVal.IsValid() {
|
||||||
// Do a slower search by iterating over each key and
|
// Do a slower search by iterating over each key and
|
||||||
// doing case-insensitive search.
|
// doing case-insensitive search.
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
fieldName = d.option.KeyReplacer.Replace(fieldName)
|
|
||||||
}
|
|
||||||
for dataValKey := range dataValKeys {
|
for dataValKey := range dataValKeys {
|
||||||
mK, ok := dataValKey.Interface().(string)
|
mK, ok := dataValKey.Interface().(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
// Not a string key
|
// Not a string key
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if d.option.KeyReplacer != nil {
|
|
||||||
mK = d.option.KeyReplacer.Replace(mK)
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.EqualFold(mK, fieldName) {
|
if strings.EqualFold(mK, fieldName) {
|
||||||
rawMapKey = dataValKey
|
rawMapKey = dataValKey
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
func MustOK[T any](result T, ok bool) T {
|
|
||||||
if ok {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
panic("operation failed")
|
|
||||||
}
|
|
@ -1,44 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"golang.org/x/exp/constraints"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Range[T constraints.Ordered] struct {
|
|
||||||
start T
|
|
||||||
end T
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
|
||||||
if start > end {
|
|
||||||
return &Range[T]{
|
|
||||||
start: end,
|
|
||||||
end: start,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Range[T]{
|
|
||||||
start: start,
|
|
||||||
end: end,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Range[T]) Contains(t T) bool {
|
|
||||||
return t >= r.start && t <= r.end
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Range[T]) LeftContains(t T) bool {
|
|
||||||
return t >= r.start && t < r.end
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Range[T]) RightContains(t T) bool {
|
|
||||||
return t > r.start && t <= r.end
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Range[T]) Start() T {
|
|
||||||
return r.start
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Range[T]) End() T {
|
|
||||||
return r.end
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
|
|
||||||
result := make([]T, 0)
|
|
||||||
for _, t := range tSlice {
|
|
||||||
if filter(t) {
|
|
||||||
result = append(result, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func ToStringSlice(value any) ([]string, error) {
|
|
||||||
strArr := make([]string, 0)
|
|
||||||
switch reflect.TypeOf(value).Kind() {
|
|
||||||
case reflect.Slice, reflect.Array:
|
|
||||||
origin := reflect.ValueOf(value)
|
|
||||||
for i := 0; i < origin.Len(); i++ {
|
|
||||||
item := fmt.Sprintf("%v", origin.Index(i))
|
|
||||||
strArr = append(strArr, item)
|
|
||||||
}
|
|
||||||
case reflect.String:
|
|
||||||
strArr = append(strArr, fmt.Sprintf("%v", value))
|
|
||||||
default:
|
|
||||||
return nil, errors.New("value format error, must be string or array")
|
|
||||||
}
|
|
||||||
return strArr, nil
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
func Reverse(s string) string {
|
|
||||||
a := []rune(s)
|
|
||||||
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
|
|
||||||
a[i], a[j] = a[j], a[i]
|
|
||||||
}
|
|
||||||
return string(a)
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user