Compare commits
87 Commits
v1.13.2
...
v1.0.0_tun
Author | SHA1 | Date | |
---|---|---|---|
39d524dc18 | |||
0be8fc387a | |||
985dc99b5d | |||
67905bcf7e | |||
b37e1fb2b9 | |||
22449da5d3 | |||
6ad2cde909 | |||
68cf94a866 | |||
7f41f94fff | |||
d1f0dac302 | |||
afb3e00067 | |||
fe44a762c2 | |||
ce1014eae3 | |||
9a31ad6151 | |||
09cc6b69e3 | |||
622b10d34d | |||
88b5741ad8 | |||
d11d28c358 | |||
03499fcea6 | |||
f788411154 | |||
3d2b4b1f3a | |||
5642d9c98e | |||
7a406b991e | |||
8603ac40a1 | |||
34eeb58bfa | |||
3d25f16b3b | |||
891a56fd99 | |||
ffbdcfcbfd | |||
72b9b829e9 | |||
8b3e42bf19 | |||
e92bea8401 | |||
b384449717 | |||
53c83118bc | |||
da7ffc0da9 | |||
ace84ff548 | |||
95db646b3b | |||
ad1e09db55 | |||
2eb7f3ad2f | |||
5dd94c8298 | |||
412b44a981 | |||
fe69ec7d6c | |||
045b67524c | |||
3c07ba6b56 | |||
8c84c8b193 | |||
7e85d5a954 | |||
da92601902 | |||
22458ad0be | |||
30025c0241 | |||
7c50c068f5 | |||
ca4961a146 | |||
aef4dd3fe7 | |||
85f14f1c63 | |||
6a92c6af4e | |||
7115f7e61b | |||
62bc75af8a | |||
d763900b14 | |||
6acba9ab8f | |||
ca9f3bf8a9 | |||
c812363090 | |||
450c608c83 | |||
567fe74f10 | |||
cd62daccb0 | |||
29c775331a | |||
33d23dad6c | |||
42cf42fd8b | |||
e010940b61 | |||
46f7c5e565 | |||
6327cf7434 | |||
2c9a4d276a | |||
4dfba73e5c | |||
c282d662ca | |||
ca76e5cf0e | |||
b3d7594813 | |||
a3a50f9c7b | |||
abc8ed4df0 | |||
643f1ae970 | |||
21a56ea36b | |||
a98749eb16 | |||
008ee613ab | |||
5999b6262d | |||
f036e06f6f | |||
5a27ebd1b3 | |||
a8646082a3 | |||
400be9a905 | |||
0582c608b3 | |||
92d9d03f99 | |||
b6653dd9b5 |
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
|
||||||
|
"
|
20
.github/workflows/build.yaml
vendored
20
.github/workflows/build.yaml
vendored
@ -1,20 +0,0 @@
|
|||||||
name: Build All
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.18
|
|
||||||
- name: Check out code
|
|
||||||
uses: actions/checkout@v1
|
|
||||||
- name: Build
|
|
||||||
run: make all
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
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
|
61
.github/workflows/docker.yaml
vendored
61
.github/workflows/docker.yaml
vendored
@ -1,61 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Beta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
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
|
22
.github/workflows/linter.yml
vendored
Normal file
22
.github/workflows/linter.yml
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
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
|
70
.github/workflows/prerelease.yml
vendored
70
.github/workflows/prerelease.yml
vendored
@ -1,70 +0,0 @@
|
|||||||
name: Prerelease
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{github.ref_name=='Beta'}}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{ github.ref_name }}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Alpha
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref_name }}
|
|
||||||
tag_name: Prerelease-${{ github.ref_name }}
|
|
||||||
files: bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
44
.github/workflows/release.yaml
vendored
44
.github/workflows/release.yaml
vendored
@ -1,44 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
- name: Test
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j$(($(nproc) + 1)) releases
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
73
.github/workflows/release.yml
vendored
Normal file
73
.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
name: Release
|
||||||
|
on: [push]
|
||||||
|
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: Get dependencies, run test
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
#if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
NAME: clash
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j releases
|
||||||
|
|
||||||
|
- name: Prepare upload
|
||||||
|
run: |
|
||||||
|
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
|
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
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -23,5 +23,3 @@ vendor
|
|||||||
|
|
||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
|
||||||
/.vscode
|
|
30
Dockerfile
30
Dockerfile
@ -1,26 +1,18 @@
|
|||||||
FROM golang:alpine as builder
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
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 && \
|
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
|
||||||
|
|
||||||
|
|
||||||
COPY . /clash-src
|
|
||||||
WORKDIR /clash-src
|
WORKDIR /clash-src
|
||||||
RUN go mod download &&\
|
COPY --from=tonistiigi/xx:golang / /
|
||||||
make docker &&\
|
COPY . /clash-src
|
||||||
mv ./bin/Clash.Meta-docker /clash
|
RUN go mod download && \
|
||||||
|
make docker && \
|
||||||
|
mv ./bin/clash-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/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
|
|
||||||
RUN chmod +x /clash
|
|
||||||
ENTRYPOINT [ "/clash" ]
|
|
||||||
|
80
Makefile
80
Makefile
@ -1,60 +1,50 @@
|
|||||||
NAME=Clash.Meta
|
NAME=clash
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
VERSION=$(shell git describe --tags --always 2>/dev/null || date +%F)
|
||||||
ifeq ($(BRANCH),Alpha)
|
|
||||||
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
|
||||||
else ifeq ($(BRANCH),Beta)
|
|
||||||
VERSION=beta-$(shell git rev-parse --short HEAD)
|
|
||||||
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)" \
|
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
|
darwin-amd64-v3 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64-compatible \
|
linux-386 \
|
||||||
linux-amd64 \
|
linux-amd64 \
|
||||||
|
linux-amd64-v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
linux-arm64 \
|
linux-arm64 \
|
||||||
linux-mips64 \
|
|
||||||
linux-mips64le \
|
|
||||||
linux-mips-softfloat \
|
linux-mips-softfloat \
|
||||||
linux-mips-hardfloat \
|
linux-mips-hardfloat \
|
||||||
linux-mipsle-softfloat \
|
linux-mipsle-softfloat \
|
||||||
linux-mipsle-hardfloat \
|
linux-mipsle-hardfloat \
|
||||||
android-arm64 \
|
linux-mips64 \
|
||||||
|
linux-mips64le \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64 \
|
freebsd-amd64 \
|
||||||
|
freebsd-amd64-v3 \
|
||||||
freebsd-arm64
|
freebsd-arm64
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64-compatible \
|
|
||||||
windows-amd64 \
|
windows-amd64 \
|
||||||
|
windows-amd64-v3 \
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-arm32v7
|
||||||
|
|
||||||
all:linux-amd64 linux-arm64\
|
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
||||||
darwin-amd64 darwin-arm64\
|
|
||||||
windows-amd64 windows-arm64\
|
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64-compatible:
|
darwin-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@ -63,14 +53,11 @@ linux-386:
|
|||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64:
|
linux-amd64:
|
||||||
|
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64-compatible:
|
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-arm64:
|
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-armv5:
|
linux-armv5:
|
||||||
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -80,6 +67,9 @@ linux-armv6:
|
|||||||
linux-armv7:
|
linux-armv7:
|
||||||
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-arm64:
|
||||||
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-mips-softfloat:
|
linux-mips-softfloat:
|
||||||
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@ -98,13 +88,13 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
android-arm64:
|
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
freebsd-386:
|
freebsd-386:
|
||||||
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-amd64:
|
freebsd-amd64:
|
||||||
|
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
freebsd-arm64:
|
freebsd-arm64:
|
||||||
@ -114,10 +104,10 @@ windows-386:
|
|||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64-compatible:
|
windows-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
@ -143,15 +133,11 @@ vet:
|
|||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
golangci-lint run ./...
|
GOOS=darwin golangci-lint run ./...
|
||||||
|
GOOS=windows golangci-lint run ./...
|
||||||
|
GOOS=linux golangci-lint run ./...
|
||||||
|
GOOS=freebsd golangci-lint run ./...
|
||||||
|
GOOS=openbsd golangci-lint run ./...
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm -rf $(BINDIR)/*
|
||||||
|
|
||||||
CLANG ?= clang-14
|
|
||||||
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
|
||||||
|
|
||||||
ebpf: export BPF_CLANG := $(CLANG)
|
|
||||||
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
|
||||||
ebpf:
|
|
||||||
cd component/ebpf/ && go generate ./...
|
|
340
README.md
340
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>
|
||||||
|
|
||||||
@ -33,32 +36,57 @@
|
|||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
## Advanced usage for this branch
|
## Advanced usage for this branch
|
||||||
|
### General configuration
|
||||||
|
```yaml
|
||||||
|
sniffing: true # Sniff TLS SNI
|
||||||
|
|
||||||
|
force-cert-verify: true # force verify TLS Certificate, prevent machine-in-the-middle attacks
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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"'
|
||||||
|
```
|
||||||
|
|
||||||
### DNS configuration
|
### DNS configuration
|
||||||
|
Support resolve ip with a proxy tunnel.
|
||||||
|
|
||||||
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:
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxy-groups:
|
|
||||||
|
|
||||||
- name: DNS
|
|
||||||
type: url-test
|
|
||||||
use:
|
|
||||||
- HK
|
|
||||||
url: http://cp.cloudflare.com
|
|
||||||
interval: 180
|
|
||||||
lazy: true
|
|
||||||
```
|
|
||||||
```yaml
|
|
||||||
dns:
|
|
||||||
enable: true
|
enable: true
|
||||||
use-hosts: true
|
use-hosts: true
|
||||||
ipv6: false
|
ipv6: false
|
||||||
enhanced-mode: redir-host
|
enhanced-mode: fake-ip
|
||||||
fake-ip-range: 198.18.0.1/16
|
fake-ip-range: 198.18.0.1/16
|
||||||
listen: 127.0.0.1:6868
|
listen: 127.0.0.1:6868
|
||||||
default-nameserver:
|
default-nameserver:
|
||||||
@ -68,50 +96,98 @@ dns:
|
|||||||
- https://doh.pub/dns-query
|
- https://doh.pub/dns-query
|
||||||
- tls://223.5.5.5:853
|
- tls://223.5.5.5:853
|
||||||
fallback:
|
fallback:
|
||||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
- 'https://1.0.0.1/dns-query#Proxy' # append the proxy adapter name to the end of DNS URL with '#' prefix.
|
||||||
- 'tls://8.8.4.4:853#DNS'
|
- 'tls://8.8.4.4:853#Proxy'
|
||||||
fallback-filter:
|
fallback-filter:
|
||||||
geoip: false
|
geoip: false
|
||||||
geosite:
|
geosite:
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to untrusted DNS providers.
|
||||||
domain:
|
domain:
|
||||||
- +.example.com
|
- +.example.com
|
||||||
ipcidr:
|
ipcidr:
|
||||||
- 0.0.0.0/32
|
- 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: gvisor # only 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
|
||||||
rules:
|
rules:
|
||||||
|
# network condition for all rules
|
||||||
|
- DOMAIN-SUFFIX,example.com,DIRECT,tcp
|
||||||
|
- DOMAIN-SUFFIX,example.com,REJECT,udp
|
||||||
|
|
||||||
# network(tcp/udp) condition for all rules
|
# process condition for all rules (add 'P:' prefix)
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
- DOMAIN-SUFFIX,example.com,REJECT,P:Google Chrome Helper
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
|
# 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
|
||||||
@ -127,89 +203,75 @@ rules:
|
|||||||
#- 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
|
### Proxies configuration
|
||||||
|
Support outbound protocol `VLESS`.
|
||||||
|
|
||||||
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 `Trojan` with XTLS.
|
||||||
|
|
||||||
Support `Policy Group Filter`
|
Support relay `UDP` traffic.
|
||||||
|
|
||||||
```yaml
|
Currently XTLS only supports TCP transport.
|
||||||
proxy-groups:
|
|
||||||
|
|
||||||
- name: 🚀 HK Group
|
|
||||||
type: select
|
|
||||||
use:
|
|
||||||
- ALL
|
|
||||||
filter: 'HK'
|
|
||||||
|
|
||||||
- name: 🚀 US Group
|
|
||||||
type: select
|
|
||||||
use:
|
|
||||||
- ALL
|
|
||||||
filter: 'US'
|
|
||||||
|
|
||||||
proxy-providers:
|
|
||||||
ALL:
|
|
||||||
type: http
|
|
||||||
url: "xxxxx"
|
|
||||||
interval: 3600
|
|
||||||
path: "xxxxx"
|
|
||||||
health-check:
|
|
||||||
enable: true
|
|
||||||
interval: 600
|
|
||||||
url: http://www.gstatic.com/generate_204
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
proxies:
|
||||||
- name: "vless"
|
# VLESS
|
||||||
|
- name: "vless-tls"
|
||||||
type: vless
|
type: vless
|
||||||
server: server
|
server: server
|
||||||
port: 443
|
port: 443
|
||||||
uuid: uuid
|
uuid: uuid
|
||||||
servername: example.com # AKA SNI
|
network: tcp
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
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
|
# skip-cert-verify: true
|
||||||
|
|
||||||
- name: "vless-ws"
|
# Trojan
|
||||||
type: vless
|
- name: "trojan-xtls"
|
||||||
|
type: trojan
|
||||||
server: server
|
server: server
|
||||||
port: 443
|
port: 443
|
||||||
uuid: uuid
|
password: yourpsk
|
||||||
tls: true
|
network: tcp
|
||||||
udp: true
|
flow: xtls-rprx-direct # or xtls-rprx-origin
|
||||||
network: ws
|
# flow-show: true # print the XTLS direction log
|
||||||
servername: example.com # priority over wss host
|
# udp: true
|
||||||
|
# sni: example.com # aka server name
|
||||||
# skip-cert-verify: true
|
# skip-cert-verify: true
|
||||||
ws-opts:
|
|
||||||
path: /path
|
|
||||||
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
|
||||||
|
|
||||||
- name: "vless-grpc"
|
proxy-groups:
|
||||||
type: vless
|
# Relay chains the proxies. proxies shall not contain a relay.
|
||||||
server: server
|
# Support relay UDP traffic.
|
||||||
port: 443
|
# Traffic: clash <-> ss1 <-> trojan <-> vmess <-> ss2 <-> Internet
|
||||||
uuid: uuid
|
- name: "relay-udp-over-tcp"
|
||||||
tls: true
|
type: relay
|
||||||
udp: true
|
proxies:
|
||||||
network: grpc
|
- ss1
|
||||||
servername: example.com # priority over wss host
|
- trojan
|
||||||
# skip-cert-verify: true
|
- vmess
|
||||||
grpc-opts:
|
- ss2
|
||||||
grpc-service-name: grpcname
|
|
||||||
|
- name: "relay-raw-udp"
|
||||||
|
type: relay
|
||||||
|
proxies:
|
||||||
|
- ss1
|
||||||
|
- ss2
|
||||||
|
- ss3
|
||||||
```
|
```
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
@ -223,73 +285,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.
|
||||||
|
|
||||||
|
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
||||||
### General installation guide for Linux
|
```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:
|
||||||
```shell
|
```sh
|
||||||
$ systemctl enable Clash-Meta
|
$ systemctl enable clash
|
||||||
```
|
```
|
||||||
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 [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
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.
|
||||||
|
|
||||||

|
## Plus Pro Release
|
||||||
|
[Release](https://github.com/yaling888/clash/releases/tag/plus)
|
||||||
|
|
||||||
## 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)
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
|
||||||
|
|
||||||
## 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -110,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
|
||||||
@ -144,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
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *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
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
|
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)
|
||||||
|
}
|
@ -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"
|
||||||
@ -14,38 +13,10 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
remoteAddr := conn.RemoteAddr()
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
// Filter when net.Addr interface is nil
|
|
||||||
if remoteAddr != nil {
|
|
||||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = 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.DNSMapping
|
|
||||||
metadata.Host = host
|
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
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
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
if ip.Is6() {
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
return context.NewConnContext(conn, metadata)
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -26,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]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,9 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/gofrs/uuid"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -19,8 +18,6 @@ type Base struct {
|
|||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
rmark int
|
rmark int
|
||||||
id string
|
|
||||||
prefer C.DNSPrefer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@ -28,49 +25,26 @@ func (b *Base) Name() string {
|
|||||||
return b.name
|
return b.name
|
||||||
}
|
}
|
||||||
|
|
||||||
// Id implements C.ProxyAdapter
|
|
||||||
func (b *Base) Id() string {
|
|
||||||
if b.id == "" {
|
|
||||||
id, err := uuid.NewV6()
|
|
||||||
if err != nil {
|
|
||||||
b.id = b.name
|
|
||||||
} else {
|
|
||||||
b.id = id.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")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (b *Base) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
||||||
@ -80,7 +54,6 @@ func (b *Base) SupportUDP() bool {
|
|||||||
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(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -104,25 +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:
|
|
||||||
}
|
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
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 {
|
||||||
@ -132,7 +92,6 @@ type BaseOption struct {
|
|||||||
UDP bool
|
UDP bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
Prefer C.DNSPrefer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBase(opt BaseOption) *Base {
|
func NewBase(opt BaseOption) *Base {
|
||||||
@ -143,18 +102,12 @@ func NewBase(opt BaseOption) *Base {
|
|||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
iface: opt.Interface,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
prefer: opt.Prefer,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
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
|
||||||
@ -168,17 +121,12 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{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
|
||||||
actualRemoteDestination string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *packetConn) RemoteDestination() string {
|
|
||||||
return c.actualRemoteDestination
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -191,18 +139,40 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func NewPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
return &packetConn{pc, []string{a.Name()}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRemoteDestination(addr string) string {
|
type wrapConn struct {
|
||||||
if dst, _, err := net.SplitHostPort(addr); err == nil {
|
net.PacketConn
|
||||||
return dst
|
}
|
||||||
} else {
|
|
||||||
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
func (*wrapConn) Read([]byte) (int, error) {
|
||||||
return dst
|
return 0, io.EOF
|
||||||
} else {
|
}
|
||||||
return ""
|
|
||||||
}
|
func (*wrapConn) Write([]byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
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,6 +3,7 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -19,18 +20,26 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, 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.WithDirect())
|
opts = append(opts, dialer.WithDirect())
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", 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 {
|
||||||
@ -43,18 +52,6 @@ func NewDirect() *Direct {
|
|||||||
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,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -23,7 +22,6 @@ 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 {
|
||||||
@ -36,8 +34,6 @@ type HttpOption struct {
|
|||||||
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
|
||||||
@ -88,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
|
||||||
}
|
}
|
||||||
@ -128,26 +121,16 @@ 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.GetGlobalFingerprintTLCConfig(&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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -158,11 +141,9 @@ func NewHttp(option HttpOption) (*Http, error) {
|
|||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
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,332 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/lucas-clemente/quic-go"
|
|
||||||
"github.com/lucas-clemente/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
|
|
||||||
minSpeedBPS = 16384
|
|
||||||
|
|
||||||
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
|
||||||
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
|
||||||
DefaultMaxIncomingStreams = 1024
|
|
||||||
|
|
||||||
DefaultALPN = "hysteria"
|
|
||||||
DefaultProtocol = "udp"
|
|
||||||
)
|
|
||||||
|
|
||||||
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() (net.PacketConn, error) {
|
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
|
||||||
},
|
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
|
||||||
return resolveUDPAddrWithPrefer("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() (net.PacketConn, error) {
|
|
||||||
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
|
||||||
},
|
|
||||||
remoteAddr: func(addr string) (net.Addr, error) {
|
|
||||||
return resolveUDPAddrWithPrefer("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"`
|
|
||||||
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"`
|
|
||||||
}
|
|
||||||
|
|
||||||
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))
|
|
||||||
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.GetGlobalFingerprintTLCConfig(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.ReceiveWindowConn == 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, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
|
||||||
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
|
||||||
}, obfuscator,
|
|
||||||
)
|
|
||||||
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,
|
|
||||||
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() (net.PacketConn, error)
|
|
||||||
ctx context.Context
|
|
||||||
remoteAddr func(host string) (net.Addr, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
|
|
||||||
return h.hyDialer()
|
|
||||||
}
|
|
||||||
|
|
||||||
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{}),
|
||||||
|
}
|
||||||
|
}
|
@ -6,22 +6,49 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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) {
|
||||||
|
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
|
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 {
|
||||||
@ -30,18 +57,6 @@ func NewReject() *Reject {
|
|||||||
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,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -13,18 +13,14 @@ import (
|
|||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
"github.com/sagernet/sing-shadowsocks"
|
|
||||||
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
"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
|
||||||
@ -41,7 +37,6 @@ type ShadowSocksOption struct {
|
|||||||
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"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -54,7 +49,6 @@ 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"`
|
||||||
@ -75,10 +69,24 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
c = ss.cipher.StreamConn(c)
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(uot.UOTMagicAddress+":443"))
|
_, err := c.Write(serializesSocksAddr(metadata))
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
|
addr, err := resolveUDPAddr("udp", ss.addr)
|
||||||
|
if err != nil {
|
||||||
|
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
|
||||||
@ -97,43 +105,25 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// 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) {
|
||||||
if ss.option.UDPOverTCP {
|
|
||||||
tcpConn, err := ss.DialContext(ctx, metadata, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
|
||||||
}
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddrWithPrefer("udp", ss.addr, ss.prefer)
|
c, err := ss.StreamPacketConn(WrapConn(pc), metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
_ = pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
|
||||||
return newPacketConn(pc, ss), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
return NewPacketConn(c.(net.PacketConn), ss), nil
|
||||||
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
if ss.option.UDPOverTCP {
|
|
||||||
return newPacketConn(uot.NewClientConn(c), 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)
|
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)
|
||||||
}
|
}
|
||||||
@ -185,11 +175,9 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
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,
|
||||||
|
@ -8,11 +8,12 @@ import (
|
|||||||
|
|
||||||
"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/shadowsocks/core"
|
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
|
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
|
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/core"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
||||||
|
"github.com/Dreamacro/go-shadowsocks2/shadowstream"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
@ -58,6 +59,22 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) 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", 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
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
||||||
@ -79,15 +96,13 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddrWithPrefer("udp", ssr.addr, ssr.prefer)
|
c, err := ssr.StreamPacketConn(WrapConn(pc), metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
_ = 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
@ -149,7 +164,6 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
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,7 +80,7 @@ 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
|
||||||
@ -97,26 +105,14 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
pc := snell.PacketConn(c)
|
|
||||||
return newPacketConn(pc, s), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
|
||||||
func (s *Snell) SupportUOT() bool {
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
@ -158,7 +154,6 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
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,
|
||||||
|
@ -5,7 +5,6 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -34,17 +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)
|
||||||
err := cc.Handshake()
|
err := cc.Handshake()
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,10 +100,14 @@ 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
|
||||||
@ -83,79 +132,33 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
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)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if ss.tls {
|
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
|
||||||
err = cc.Handshake()
|
|
||||||
c = cc
|
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
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)
|
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("client hanshake error: %w", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
tcpKeepAlive(c)
|
||||||
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.
|
pc, err = ss.StreamSocks5PacketConn(c, pc, metadata)
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
err = errors.New("invalid UDP bind address")
|
|
||||||
return
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
return NewPacketConn(pc, ss), nil
|
||||||
}
|
|
||||||
|
|
||||||
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.GetGlobalFingerprintTLCConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &Socks5{
|
||||||
@ -166,14 +169,13 @@ func NewSocks5(option Socks5Option) (*Socks5, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
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 {
|
||||||
@ -211,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()
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -14,6 +13,8 @@ import (
|
|||||||
"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 {
|
||||||
@ -24,7 +25,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
@ -36,7 +37,6 @@ type TrojanOption struct {
|
|||||||
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"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
@ -72,8 +72,7 @@ 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 t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
@ -85,43 +84,63 @@ 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 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
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
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)
|
||||||
}
|
}
|
||||||
@ -141,44 +160,44 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
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 safeConnClose(c, err)
|
|
||||||
} else {
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = t.plainStream(c)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
defer safeConnClose(c, err)
|
||||||
return newPacketConn(pc, t), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
c, err = t.instance.PrepareXTLSConn(c)
|
||||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
if err != nil {
|
||||||
pc := t.instance.PacketConn(c)
|
return nil, err
|
||||||
return newPacketConn(pc, t), err
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
if err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata)); err != nil {
|
||||||
func (t *Trojan) SupportUOT() bool {
|
return nil, err
|
||||||
return true
|
}
|
||||||
|
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
|
||||||
|
return NewPacketConn(pc, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
c, err = t.StreamPacketConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewPacketConn(c.(net.PacketConn), t), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
@ -190,7 +209,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
Fingerprint: option.Fingerprint,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
@ -215,7 +233,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
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,
|
||||||
@ -238,15 +255,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(option.Fingerprint) == 0 {
|
|
||||||
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
if t.option.Flow != "" {
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
|
@ -2,12 +2,8 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"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"
|
||||||
@ -15,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)
|
||||||
@ -28,20 +18,6 @@ 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
|
||||||
aType := uint8(metadata.AddrType)
|
aType := uint8(metadata.AddrType)
|
||||||
@ -75,65 +51,8 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddrWithPrefer(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
|
|
||||||
switch prefer {
|
|
||||||
case C.IPv4Only:
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
case C.IPv6Only:
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
case C.IPv6Prefer:
|
|
||||||
var ips []netip.Addr
|
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
|
||||||
var fallback netip.Addr
|
|
||||||
if err == nil {
|
|
||||||
for _, addr := range ips {
|
|
||||||
if addr.Is6() {
|
|
||||||
ip = addr
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
if !fallback.IsValid() {
|
|
||||||
fallback = addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ip = fallback
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// C.IPv4Prefer, C.DualStack and other
|
|
||||||
var ips []netip.Addr
|
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
|
||||||
var fallback netip.Addr
|
|
||||||
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 {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
|
||||||
}
|
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil {
|
if err != nil && c != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,8 +6,6 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -20,6 +18,8 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -35,7 +35,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
@ -46,7 +46,6 @@ type VlessOption struct {
|
|||||||
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"`
|
Network string `proxy:"network,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
@ -56,14 +55,20 @@ type VlessOption struct {
|
|||||||
WSPath string `proxy:"ws-path,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
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{
|
||||||
@ -72,40 +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,
|
||||||
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
|
wsOpts.TLS = true
|
||||||
tlsConfig := &tls.Config{
|
wsOpts.TLSConfig = &tls.Config{
|
||||||
MinVersion: tls.VersionTLS12,
|
MinVersion: tls.VersionTLS12,
|
||||||
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.GetGlobalFingerprintTLCConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
if host := wsOpts.Headers.Get("Host"); host == "" {
|
|
||||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(wsOpts.Headers)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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
|
||||||
@ -154,6 +148,26 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
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)
|
||||||
|
|
||||||
@ -161,7 +175,6 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
FingerPrint: v.option.Fingerprint,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -174,11 +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,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -191,8 +203,6 @@ 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) isXTLSEnabled() bool {
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
@ -230,6 +240,9 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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) {
|
||||||
|
var c net.Conn
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
@ -239,9 +252,6 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
var c net.Conn
|
|
||||||
// gun transport
|
|
||||||
if v.transport != nil && len(opts) == 0 {
|
|
||||||
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
|
||||||
@ -249,32 +259,27 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
} else {
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
if err != nil {
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
tcpKeepAlive(c)
|
||||||
func (v *Vless) SupportUOT() bool {
|
defer safeConnClose(c, err)
|
||||||
return true
|
|
||||||
|
c, err = v.StreamPacketConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewPacketConn(c.(net.PacketConn), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
@ -282,18 +287,18 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType {
|
||||||
case C.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 C.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 C.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)
|
||||||
@ -308,40 +313,29 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
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
|
||||||
}
|
}
|
||||||
@ -355,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)
|
||||||
@ -388,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) {
|
||||||
@ -423,7 +428,6 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -448,10 +452,10 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
}
|
}
|
||||||
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&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)
|
||||||
|
@ -3,23 +3,19 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
tlsC "github.com/Dreamacro/clash/component/tls"
|
|
||||||
vmess "github.com/sagernet/sing-vmess"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"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"
|
||||||
"github.com/sagernet/sing-vmess/packetaddr"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
@ -30,7 +26,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
@ -45,17 +41,15 @@ type VmessOption struct {
|
|||||||
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"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
|
||||||
XUDP bool `proxy:"xudp,omitempty"`
|
// TODO: compatible with VMESS WS older version configurations
|
||||||
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -85,52 +79,49 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
var err error
|
var err error
|
||||||
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,
|
||||||
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.GetGlobalFingerprintTLCConfig(tlsConfig)
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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,
|
||||||
}
|
}
|
||||||
@ -139,24 +130,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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"},
|
||||||
@ -166,24 +157,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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)
|
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,
|
||||||
}
|
}
|
||||||
@ -192,22 +183,35 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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))
|
||||||
return v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
}
|
||||||
} else {
|
|
||||||
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
// StreamPacketConn implements C.ProxyAdapter
|
||||||
|
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
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return c, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
}
|
}
|
||||||
} else {
|
metadata.DstIP = ip
|
||||||
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
@ -220,7 +224,7 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
@ -241,98 +245,62 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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) {
|
||||||
|
var c net.Conn
|
||||||
|
// gun transport
|
||||||
|
if v.transport != nil && len(opts) == 0 {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
if !metadata.Resolved() {
|
if !metadata.Resolved() {
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("can't resolve ip")
|
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
}
|
}
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
|
||||||
_metadata := *metadata // make a copy
|
|
||||||
metadata = &_metadata
|
|
||||||
metadata.Host = packetaddr.SeqPacketMagicAddress
|
|
||||||
metadata.DstPort = "443"
|
|
||||||
}
|
|
||||||
|
|
||||||
var c net.Conn
|
|
||||||
// gun transport
|
|
||||||
if v.transport != nil && len(opts) == 0 {
|
|
||||||
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 safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
if v.option.XUDP {
|
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
||||||
c, err = v.client.DialXUDPPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
} else {
|
|
||||||
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.PacketAddr {
|
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
if err != nil {
|
||||||
if v.option.PacketAddr {
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
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
|
tcpKeepAlive(c)
|
||||||
func (v *Vmess) SupportUOT() bool {
|
defer safeConnClose(c, err)
|
||||||
return true
|
|
||||||
|
c, err = v.StreamPacketConn(c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewPacketConn(c.(net.PacketConn), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
@ -348,7 +316,6 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
prefer: C.NewDNSPrefer(option.IPVersion),
|
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -388,29 +355,44 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
||||||
uc.access.Lock()
|
|
||||||
defer uc.access.Unlock()
|
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,19 +3,19 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"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"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
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 {
|
||||||
@ -29,11 +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)
|
||||||
f.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
f.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,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{
|
||||||
@ -72,68 +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,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
testUrl: option.URL,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,250 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"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"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GroupBase struct {
|
|
||||||
*outbound.Base
|
|
||||||
filterRegs []*regexp2.Regexp
|
|
||||||
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
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
|
||||||
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,
|
|
||||||
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 {
|
|
||||||
if len(gb.filterRegs) == 0 {
|
|
||||||
var proxies []C.Proxy
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
if touch {
|
|
||||||
pd.Touch()
|
|
||||||
}
|
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
|
||||||
}
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxies []C.Proxy
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
@ -5,12 +5,11 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"net"
|
"net"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
"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,25 +20,25 @@ import (
|
|||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) 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 {
|
||||||
|
if strategy, ok := elm.(string); ok {
|
||||||
return strategy
|
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 {
|
||||||
@ -58,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
|
||||||
|
|
||||||
@ -82,17 +71,14 @@ 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() {
|
defer func() {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(lb)
|
c.AppendToChains(lb)
|
||||||
lb.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
lb.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
proxy := lb.Unwrap(metadata)
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -105,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...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -143,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.NewLRUCache[uint64, int](
|
|
||||||
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
|
||||||
cache.WithSize[uint64, int](1000))
|
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) 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)
|
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{
|
||||||
@ -214,22 +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,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
|
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}, nil
|
}, nil
|
||||||
|
@ -29,7 +29,6 @@ type GroupCommonOption struct {
|
|||||||
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"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
@ -75,12 +74,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 = "http://www.gstatic.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)
|
||||||
@ -100,8 +95,6 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
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
|
||||||
|
@ -4,20 +4,32 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"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"
|
||||||
|
"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
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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:
|
||||||
@ -26,115 +38,165 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
first := proxies[0]
|
c, err := r.streamContext(ctx, proxies, r.Base.DialOptions(opts...)...)
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
var currentMeta *C.Metadata
|
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
last := proxies[len(proxies)-1]
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
c, err = last.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
conn := outbound.NewConn(c, last)
|
return outbound.NewConn(c, r), nil
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
|
||||||
conn.AppendToChains(chainProxies[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
conn.AppendToChains(r)
|
|
||||||
|
|
||||||
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...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
first := proxies[0]
|
var (
|
||||||
last := proxies[len(proxies)-1]
|
firstIndex = 0
|
||||||
|
nextIndex = 1
|
||||||
|
lastUDPOverTCPIndex = -1
|
||||||
|
rawUDPRelay = false
|
||||||
|
|
||||||
|
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...)...)
|
||||||
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
var currentMeta *C.Metadata
|
if nextIndex < length {
|
||||||
for _, proxy := range proxies[1:] {
|
for i, proxy := range proxies[nextIndex:] { // raw udp in loop
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
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
|
first = proxy
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cc != nil {
|
||||||
|
c, err = streamSocks5PacketConn(last, cc, c, metadata)
|
||||||
|
} else {
|
||||||
|
c, err = last.StreamPacketConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var pc C.PacketConn
|
return outbound.NewPacketConn(c.(net.PacketConn), r), nil
|
||||||
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
|
||||||
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
|
||||||
}
|
}
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
return last.SupportUDP() && last.SupportUOT()
|
last := proxies[l-1]
|
||||||
|
|
||||||
|
return isRawUDP(last) || last.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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{
|
||||||
@ -143,49 +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, true)
|
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,34 +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) {
|
||||||
|
proxies := getProvidersProxies(s.providers, touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if proxy.Name() == s.selected {
|
if proxy.Name() == s.selected {
|
||||||
return proxy
|
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,
|
|
||||||
providers,
|
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,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 {
|
||||||
@ -34,13 +36,9 @@ func (u *URLTest) Now() string {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
||||||
proxy := u.fast(true)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
c, err = proxy.DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.onDialSuccess()
|
|
||||||
} else {
|
|
||||||
u.onDialFailed(proxy.Type(), err)
|
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -51,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
|
||||||
@ -90,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
|
||||||
}
|
}
|
||||||
@ -108,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{
|
||||||
@ -134,18 +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,
|
|
||||||
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,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -24,8 +24,7 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
err = nil
|
return addr, nil
|
||||||
return
|
|
||||||
} else if ip.Is4() {
|
} else if ip.Is4() {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
AddrType: C.AtypIPv4,
|
||||||
@ -51,7 +50,3 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type SelectAble interface {
|
|
||||||
Set(string) error
|
|
||||||
}
|
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
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})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
@ -40,14 +40,20 @@ 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{
|
||||||
@ -59,6 +65,9 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
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{}
|
vlessOption := &outbound.VlessOption{}
|
||||||
@ -66,6 +75,9 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
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{}
|
||||||
@ -80,14 +92,10 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
if forceCertVerify {
|
||||||
case "hysteria":
|
trojanOption.SkipCertVerify = false
|
||||||
hyOption := &outbound.HysteriaOption{}
|
|
||||||
err = decoder.Decode(mapping, hyOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewHysteria(*hyOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
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,46 +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]
|
||||||
interval time.Duration
|
onUpdate func(V)
|
||||||
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]) VehicleType() types.VehicleType {
|
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.Infoln("[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()
|
||||||
}
|
}
|
||||||
@ -64,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
|
||||||
@ -90,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
|
||||||
}
|
}
|
||||||
@ -106,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
|
||||||
@ -123,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
|
||||||
}
|
}
|
||||||
@ -139,20 +117,20 @@ 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:
|
||||||
@ -163,13 +141,13 @@ func (f *Fetcher[V]) pullLoop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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()
|
||||||
@ -190,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,11 +5,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -29,21 +26,25 @@ 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() {
|
go func() {
|
||||||
time.Sleep(30 * time.Second)
|
t := time.NewTicker(30 * time.Second)
|
||||||
hc.lazyCheck()
|
<-t.C
|
||||||
|
t.Stop()
|
||||||
|
hc.check()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
hc.lazyCheck()
|
now := time.Now().Unix()
|
||||||
|
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
||||||
|
hc.check()
|
||||||
|
}
|
||||||
case <-hc.done:
|
case <-hc.done:
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
@ -51,17 +52,6 @@ func (hc *HealthCheck) process() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) lazyCheck() bool {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
|
||||||
hc.check()
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
log.Debugln("Skip once health check because we are lazy")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
@ -75,29 +65,17 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
|
||||||
id := ""
|
|
||||||
if uid, err := uuid.NewV4(); err == nil {
|
|
||||||
id = uid.String()
|
|
||||||
}
|
|
||||||
log.Debugln("Start New Health Checking {%s}", id)
|
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
log.Debugln("Health Checking %s {%s}", p.Name(), id)
|
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
log.Debugln("Health Checked %s : %t %d ms {%s}", p.Name(), p.Alive(), p.LastDelay(), id)
|
|
||||||
return false, nil
|
return false, nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
b.Wait()
|
b.Wait()
|
||||||
log.Debugln("Finish A Health Checking {%s}", id)
|
|
||||||
return struct{}{}, nil
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
@ -112,6 +90,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),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,6 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
@ -26,11 +25,11 @@ type proxyProviderSchema struct {
|
|||||||
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"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
ForceCertVerify bool `provider:"force-cert-verify,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{
|
||||||
@ -38,6 +37,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
|
||||||
}
|
}
|
||||||
@ -53,15 +57,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)
|
||||||
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)
|
||||||
return NewProxySetProvider(name, interval, filter, excludeFilter, vehicle, hc)
|
|
||||||
}
|
}
|
||||||
|
@ -4,11 +4,8 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
"regexp"
|
||||||
"github.com/Dreamacro/clash/component/resource"
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
@ -32,10 +29,9 @@ 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -44,16 +40,12 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.UpdatedAt,
|
"updatedAt": pp.updatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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() {
|
||||||
@ -61,19 +53,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.onUpdate(elm)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,36 +78,29 @@ 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() {
|
if pp.healthCheck.auto() {
|
||||||
defer func() { go pp.healthCheck.lazyCheck() }()
|
go pp.healthCheck.check()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck, forceCertVerify bool) (*ProxySetProvider, error) {
|
||||||
excludeFilterReg, err := regexp2.Compile(excludeFilter, 0)
|
filterReg, err := regexp.Compile(filter)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
|
||||||
}
|
|
||||||
var filterRegs []*regexp2.Regexp
|
|
||||||
for _, filter := range strings.Split(filter, "`") {
|
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
filterRegs = append(filterRegs, filterReg)
|
|
||||||
}
|
|
||||||
|
|
||||||
if hc.auto() {
|
if hc.auto() {
|
||||||
go hc.process()
|
go hc.process()
|
||||||
@ -125,8 +111,8 @@ 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, filterRegs, excludeFilterReg), proxiesOnUpdate(pd))
|
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg, forceCertVerify), proxiesOnUpdate(pd))
|
||||||
pd.Fetcher = fetcher
|
pd.fetcher = fetcher
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
@ -142,7 +128,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) {
|
||||||
@ -154,10 +139,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
|
||||||
}
|
}
|
||||||
@ -186,8 +167,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) {
|
||||||
@ -217,20 +199,15 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*regexp2.Regexp, excludeFilterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, filterReg *regexp.Regexp, forceCertVerify bool) 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)
|
return nil, err
|
||||||
if err1 != nil {
|
|
||||||
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
|
||||||
}
|
|
||||||
schema.Proxies = proxies
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if schema.Proxies == nil {
|
if schema.Proxies == nil {
|
||||||
@ -238,38 +215,16 @@ func proxiesParseAndFilter(filter string, excludeFilter string, filterRegs []*re
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
proxiesSet := map[string]struct{}{}
|
|
||||||
for _, filterReg := range filterRegs {
|
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
mName, ok := mapping["name"]
|
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
||||||
if !ok {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
name, ok := mName.(string)
|
proxy, err := adapter.ParseProxy(mapping, forceCertVerify)
|
||||||
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
proxiesSet[name] = struct{}{}
|
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
if len(filter) > 0 {
|
if len(filter) > 0 {
|
||||||
|
@ -1,13 +1,16 @@
|
|||||||
package resource
|
package provider
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
netHttp "github.com/Dreamacro/clash/component/http"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
"io"
|
"io"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type FileVehicle struct {
|
type FileVehicle struct {
|
||||||
@ -46,16 +49,47 @@ func (h *HTTPVehicle) Path() string {
|
|||||||
func (h *HTTPVehicle) Read() ([]byte, error) {
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
resp, err := netHttp.HttpRequest(ctx, h.url, http.MethodGet, nil, nil)
|
|
||||||
|
uri, err := url.Parse(h.url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if user := uri.User; user != nil {
|
||||||
|
password, _ := user.Password()
|
||||||
|
req.SetBasicAuth(user.Username(), password)
|
||||||
|
}
|
||||||
|
|
||||||
|
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) (net.Conn, error) {
|
||||||
|
return dialer.DialContext(ctx, network, address)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
buf, err := io.ReadAll(resp.Body)
|
buf, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
@ -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
|
|
2
common/cache/cache.go
vendored
2
common/cache/cache.go
vendored
@ -61,7 +61,7 @@ func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
|||||||
|
|
||||||
func (c *cache[K, V]) cleanup() {
|
func (c *cache[K, V]) cleanup() {
|
||||||
c.mapping.Range(func(k, v any) bool {
|
c.mapping.Range(func(k, v any) bool {
|
||||||
key := k.(string)
|
key := k
|
||||||
elm := v.(*element[V])
|
elm := v.(*element[V])
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
|
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)
|
|
||||||
}
|
|
@ -1,387 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|
||||||
data := DecodeBase64(buf)
|
|
||||||
|
|
||||||
arr := strings.Split(string(data), "\n")
|
|
||||||
|
|
||||||
proxies := make([]map[string]any, 0, len(arr))
|
|
||||||
names := make(map[string]int, 200)
|
|
||||||
|
|
||||||
for _, line := range arr {
|
|
||||||
line = strings.TrimRight(line, " \r")
|
|
||||||
if line == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
scheme, body, found := strings.Cut(line, "://")
|
|
||||||
if !found {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
scheme = strings.ToLower(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":
|
|
||||||
urlTrojan, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
query := urlTrojan.Query()
|
|
||||||
|
|
||||||
name := uniqueName(names, urlTrojan.Fragment)
|
|
||||||
trojan := make(map[string]any, 20)
|
|
||||||
|
|
||||||
trojan["name"] = name
|
|
||||||
trojan["type"] = scheme
|
|
||||||
trojan["server"] = urlTrojan.Hostname()
|
|
||||||
trojan["port"] = urlTrojan.Port()
|
|
||||||
trojan["password"] = urlTrojan.User.Username()
|
|
||||||
trojan["udp"] = true
|
|
||||||
trojan["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
sni := query.Get("sni")
|
|
||||||
if sni != "" {
|
|
||||||
trojan["sni"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
|
||||||
if network != "" {
|
|
||||||
trojan["network"] = network
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
|
||||||
case "ws":
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
|
|
||||||
wsOpts["path"] = query.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
trojan["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
|
||||||
trojan["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
|
||||||
|
|
||||||
case "vless":
|
|
||||||
urlVLess, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
query := urlVLess.Query()
|
|
||||||
vless := make(map[string]any, 20)
|
|
||||||
handleVShareLink(names, urlVLess, scheme, vless)
|
|
||||||
if flow := query.Get("flow"); flow != "" {
|
|
||||||
vless["flow"] = strings.ToLower(flow)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, vless)
|
|
||||||
|
|
||||||
case "vmess":
|
|
||||||
// V2RayN-styled share link
|
|
||||||
// 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 {
|
|
||||||
// Xray VMessAEAD share link
|
|
||||||
urlVMess, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
query := urlVMess.Query()
|
|
||||||
vmess := make(map[string]any, 20)
|
|
||||||
handleVShareLink(names, urlVMess, scheme, vmess)
|
|
||||||
vmess["alterId"] = 0
|
|
||||||
vmess["cipher"] = "auto"
|
|
||||||
if encryption := query.Get("encryption"); encryption != "" {
|
|
||||||
vmess["cipher"] = encryption
|
|
||||||
}
|
|
||||||
if packetEncoding := query.Get("packetEncoding"); packetEncoding != "" {
|
|
||||||
switch packetEncoding {
|
|
||||||
case "packet":
|
|
||||||
vmess["packet-addr"] = true
|
|
||||||
case "xudp":
|
|
||||||
vmess["xudp"] = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
proxies = append(proxies, vmess)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
|
||||||
values := make(map[string]any, 20)
|
|
||||||
|
|
||||||
if jsonDc.Decode(&values) != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
name := uniqueName(names, values["ps"].(string))
|
|
||||||
vmess := make(map[string]any, 20)
|
|
||||||
|
|
||||||
vmess["name"] = name
|
|
||||||
vmess["type"] = scheme
|
|
||||||
vmess["server"] = values["add"]
|
|
||||||
vmess["port"] = values["port"]
|
|
||||||
vmess["uuid"] = values["id"]
|
|
||||||
if alterId, ok := values["aid"]; ok {
|
|
||||||
vmess["alterId"] = alterId
|
|
||||||
} else {
|
|
||||||
vmess["alterId"] = 0
|
|
||||||
}
|
|
||||||
vmess["udp"] = true
|
|
||||||
vmess["tls"] = false
|
|
||||||
vmess["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
vmess["cipher"] = "auto"
|
|
||||||
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))
|
|
||||||
if values["type"] == "http" {
|
|
||||||
network = "http"
|
|
||||||
} else if network == "http" {
|
|
||||||
network = "h2"
|
|
||||||
}
|
|
||||||
vmess["network"] = network
|
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
|
||||||
if strings.HasSuffix(tls, "tls") {
|
|
||||||
vmess["tls"] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
|
||||||
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)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
wsOpts["path"] = []string{"/"}
|
|
||||||
if host, ok := values["host"]; ok && host != "" {
|
|
||||||
headers["Host"] = host.(string)
|
|
||||||
}
|
|
||||||
if path, ok := values["path"]; ok && path != "" {
|
|
||||||
wsOpts["path"] = path.(string)
|
|
||||||
}
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
vmess["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = values["path"]
|
|
||||||
vmess["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, vmess)
|
|
||||||
|
|
||||||
case "ss":
|
|
||||||
urlSS, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
name := uniqueName(names, urlSS.Fragment)
|
|
||||||
port := urlSS.Port()
|
|
||||||
|
|
||||||
if port == "" {
|
|
||||||
dcBuf, err := encRaw.DecodeString(urlSS.Host)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
urlSS, err = url.Parse("ss://" + string(dcBuf))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
cipher = urlSS.User.Username()
|
|
||||||
password string
|
|
||||||
)
|
|
||||||
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
|
||||||
dcBuf, _ := enc.DecodeString(cipher)
|
|
||||||
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
|
||||||
dcBuf, _ = encRaw.DecodeString(cipher)
|
|
||||||
}
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
|
||||||
if !found {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ss := make(map[string]any, 20)
|
|
||||||
|
|
||||||
ss["name"] = name
|
|
||||||
ss["type"] = scheme
|
|
||||||
ss["server"] = urlSS.Hostname()
|
|
||||||
ss["port"] = urlSS.Port()
|
|
||||||
ss["cipher"] = cipher
|
|
||||||
ss["password"] = password
|
|
||||||
query := urlSS.Query()
|
|
||||||
ss["udp"] = 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)
|
|
||||||
case "ssr":
|
|
||||||
dcBuf, err := encRaw.DecodeString(body)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// ssr://host:port:protocol:method:obfs:urlsafebase64pass/?obfsparam=urlsafebase64&protoparam=&remarks=urlsafebase64&group=urlsafebase64&udpport=0&uot=1
|
|
||||||
|
|
||||||
before, after, ok := strings.Cut(string(dcBuf), "/?")
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeArr := strings.Split(before, ":")
|
|
||||||
|
|
||||||
if len(beforeArr) != 6 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
host := beforeArr[0]
|
|
||||||
port := beforeArr[1]
|
|
||||||
protocol := beforeArr[2]
|
|
||||||
method := beforeArr[3]
|
|
||||||
obfs := beforeArr[4]
|
|
||||||
password := decodeUrlSafe(urlSafe(beforeArr[5]))
|
|
||||||
|
|
||||||
query, err := url.ParseQuery(urlSafe(after))
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
remarks := decodeUrlSafe(query.Get("remarks"))
|
|
||||||
name := uniqueName(names, remarks)
|
|
||||||
|
|
||||||
obfsParam := decodeUrlSafe(query.Get("obfsparam"))
|
|
||||||
protocolParam := query.Get("protoparam")
|
|
||||||
|
|
||||||
ssr := make(map[string]any, 20)
|
|
||||||
|
|
||||||
ssr["name"] = name
|
|
||||||
ssr["type"] = scheme
|
|
||||||
ssr["server"] = host
|
|
||||||
ssr["port"] = port
|
|
||||||
ssr["cipher"] = method
|
|
||||||
ssr["password"] = password
|
|
||||||
ssr["obfs"] = obfs
|
|
||||||
ssr["protocol"] = protocol
|
|
||||||
ssr["udp"] = true
|
|
||||||
|
|
||||||
if obfsParam != "" {
|
|
||||||
ssr["obfs-param"] = obfsParam
|
|
||||||
}
|
|
||||||
|
|
||||||
if protocolParam != "" {
|
|
||||||
ssr["protocol-param"] = protocolParam
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, ssr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, fmt.Errorf("convert v2ray subscribe error: format invalid")
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueName(names map[string]int, name string) string {
|
|
||||||
if index, ok := names[name]; ok {
|
|
||||||
index++
|
|
||||||
names[name] = index
|
|
||||||
name = fmt.Sprintf("%s-%02d", name, index)
|
|
||||||
} else {
|
|
||||||
index = 0
|
|
||||||
names[name] = index
|
|
||||||
}
|
|
||||||
return name
|
|
||||||
}
|
|
@ -1,316 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
var hostsSuffix = []string{
|
|
||||||
"-cdn.aliyuncs.com",
|
|
||||||
".alicdn.com",
|
|
||||||
".pan.baidu.com",
|
|
||||||
".tbcache.com",
|
|
||||||
".aliyuncdn.com",
|
|
||||||
".vod.miguvideo.com",
|
|
||||||
".cibntv.net",
|
|
||||||
".myqcloud.com",
|
|
||||||
".smtcdns.com",
|
|
||||||
".alikunlun.com",
|
|
||||||
".smtcdns.net",
|
|
||||||
".apcdns.net",
|
|
||||||
".cdn-go.cn",
|
|
||||||
".cdntip.com",
|
|
||||||
".cdntips.com",
|
|
||||||
".alidayu.com",
|
|
||||||
".alidns.com",
|
|
||||||
".cdngslb.com",
|
|
||||||
".mxhichina.com",
|
|
||||||
".alibabadns.com",
|
|
||||||
}
|
|
||||||
|
|
||||||
var userAgents = []string{
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Moto C Build/NRD90M.059) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J120M Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Moto G (5) Build/NPPS25.137-93-14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L03 Build/HUAWEICAM-L03) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Datanyze; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; SM-J111M Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J700M Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Slackware/Chrome/12.0.742.100 Safari/534.30",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; WAS-LX3 Build/HUAWEIWAS-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1805 Safari/537.36 MVisionPlayer/1.0.0.0",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX3 Build/HUAWEITRT-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1610 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 4.4.2; de-de; SAMSUNG GT-I9195 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; ANE-LX3 Build/HUAWEIANE-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; U; Linux i586; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.1 Safari/533.2",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-J500M Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1606 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1; vivo 1716 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G570M Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; MYA-L22 Build/HUAWEIMYA-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; A1601 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; TRT-LX2 Build/HUAWEITRT-LX2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; CAM-L21 Build/HUAWEICAM-L21; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.3 Safari/534.24",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4X Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 4.4.2; SM-G7102 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; HUAWEI CUN-L22 Build/HUAWEICUN-L22; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1.1; A37fw Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J730GM Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-G610F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.2; Redmi Note 5A Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Unknown; Linux) AppleWebKit/538.1 (KHTML, like Gecko) Chrome/v1.0.0 Safari/538.1",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; BLL-L22 Build/HUAWEIBLL-L22) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.0; SM-J710F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1.1; CPH1723 Build/N6F26Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 8.0.0; FIG-LX3 Build/HUAWEIFIG-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/10.0.649.0 Safari/534.17",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 7.1; Mi A1 Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 MVisionPlayer/1.0.0.0",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 5.1; A37f Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; CPH1607 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; vivo 1603 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4A Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.116 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Linux; Android 6.0; vivo 1713 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.124 Mobile Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36",
|
|
||||||
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
hostsLen = len(hostsSuffix)
|
|
||||||
uaLen = len(userAgents)
|
|
||||||
)
|
|
||||||
|
|
||||||
func RandHost() string {
|
|
||||||
id, _ := uuid.NewV4()
|
|
||||||
base := strings.ToLower(base64.RawURLEncoding.EncodeToString(id.Bytes()))
|
|
||||||
base = strings.ReplaceAll(base, "-", "")
|
|
||||||
base = strings.ReplaceAll(base, "_", "")
|
|
||||||
buf := []byte(base)
|
|
||||||
prefix := string(buf[:3]) + "---"
|
|
||||||
prefix += string(buf[6:8]) + "-"
|
|
||||||
prefix += string(buf[len(buf)-8:])
|
|
||||||
|
|
||||||
return prefix + hostsSuffix[rand.Intn(hostsLen)]
|
|
||||||
}
|
|
||||||
|
|
||||||
func RandUserAgent() string {
|
|
||||||
return userAgents[rand.Intn(uaLen)]
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetUserAgent(header http.Header) {
|
|
||||||
if header.Get("User-Agent") != "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
userAgent := RandUserAgent()
|
|
||||||
header.Set("User-Agent", userAgent)
|
|
||||||
}
|
|
@ -1,89 +0,0 @@
|
|||||||
package convert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
|
||||||
// Xray VMessAEAD / VLESS share link standard
|
|
||||||
// https://github.com/XTLS/Xray-core/discussions/716
|
|
||||||
query := url.Query()
|
|
||||||
proxy["name"] = uniqueName(names, url.Fragment)
|
|
||||||
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") {
|
|
||||||
proxy["tls"] = true
|
|
||||||
}
|
|
||||||
if sni := query.Get("sni"); sni != "" {
|
|
||||||
proxy["servername"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
proxy["ws-opts"] = wsOpts
|
|
||||||
|
|
||||||
case "grpc":
|
|
||||||
grpcOpts := make(map[string]any)
|
|
||||||
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
|
||||||
proxy["grpc-opts"] = grpcOpts
|
|
||||||
}
|
|
||||||
}
|
|
@ -4,21 +4,36 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Relay copies between left and right bidirectionally.
|
// Relay copies between left and right bidirectionally.
|
||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
ch := make(chan error)
|
ch := make(chan error)
|
||||||
|
|
||||||
|
tcpKeepAlive(leftConn)
|
||||||
|
tcpKeepAlive(rightConn)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
leftConn.SetReadDeadline(time.Now())
|
_ = pool.Put(buf)
|
||||||
|
_ = leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
_, _ = io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
rightConn.SetReadDeadline(time.Now())
|
_, _ = io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
|
_ = pool.Put(buf)
|
||||||
|
_ = rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
<-ch
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func tcpKeepAlive(c net.Conn) {
|
||||||
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
|
_ = tcp.SetKeepAlive(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -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,7 +0,0 @@
|
|||||||
package pool
|
|
||||||
|
|
||||||
import "github.com/sagernet/sing/common/buf"
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
buf.DefaultAllocator = defaultAllocator
|
|
||||||
}
|
|
@ -1,115 +1,107 @@
|
|||||||
package sniffer
|
package tls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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")
|
||||||
)
|
)
|
||||||
|
|
||||||
type TLSSniffer struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
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])
|
||||||
@ -117,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
|
||||||
}
|
}
|
||||||
@ -148,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())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -31,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()
|
||||||
@ -301,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:]
|
||||||
|
@ -137,3 +137,45 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValue(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"foo": 1,
|
||||||
|
"bar": []any{"bar", nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
goal := &BazSlice{
|
||||||
|
Foo: 1,
|
||||||
|
Bar: []string{"bar", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &BazSlice{}
|
||||||
|
err := weakTypeDecoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, goal.Bar, s.Bar)
|
||||||
|
|
||||||
|
s = &BazSlice{}
|
||||||
|
err = decoder.Decode(rawMap, s)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
||||||
|
rawMap := map[string]any{
|
||||||
|
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &struct {
|
||||||
|
Bar []map[string]any `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := decoder.Decode(rawMap, s)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Nil(t, s.Bar[1])
|
||||||
|
|
||||||
|
ss := &struct {
|
||||||
|
Bar []Baz `test:"bar"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = decoder.Decode(rawMap, ss)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
}
|
||||||
|
@ -1,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,16 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
|
||||||
|
|
||||||
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
|
||||||
func UUIDMap(str string) (uuid.UUID, error) {
|
|
||||||
u, err := uuid.FromString(str)
|
|
||||||
if err != nil {
|
|
||||||
return uuid.NewV5(uuidNamespace, str), nil
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
@ -1,74 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gofrs/uuid"
|
|
||||||
"reflect"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestUUIDMap(t *testing.T) {
|
|
||||||
type args struct {
|
|
||||||
str string
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
args args
|
|
||||||
want uuid.UUID
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "uuid-test-1",
|
|
||||||
args: args{
|
|
||||||
str: "82410302-039e-41b6-98b0-d964084b4170",
|
|
||||||
},
|
|
||||||
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "uuid-test-2",
|
|
||||||
args: args{
|
|
||||||
str: "88c502e6-d7eb-4c8e-8259-94cb13d83c77",
|
|
||||||
},
|
|
||||||
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "uuid-map-1",
|
|
||||||
args: args{
|
|
||||||
str: "123456",
|
|
||||||
},
|
|
||||||
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
// GENERATED BY 'xray uuid -i'
|
|
||||||
{
|
|
||||||
name: "uuid-map-2",
|
|
||||||
args: args{
|
|
||||||
str: "a9dk23bz0",
|
|
||||||
},
|
|
||||||
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "uuid-map-2",
|
|
||||||
args: args{
|
|
||||||
str: "中文123",
|
|
||||||
},
|
|
||||||
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
got, err := UUIDMap(tt.args.str)
|
|
||||||
if (err != nil) != tt.wantErr {
|
|
||||||
t.Errorf("UUIDMap() error = %v, wantErr %v", err, tt.wantErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(got, tt.want) {
|
|
||||||
t.Errorf("UUIDMap() got = %v, want %v", got, tt.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
@ -3,23 +3,10 @@ package dialer
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
dialMux sync.Mutex
|
|
||||||
actualSingleDialContext = singleDialContext
|
|
||||||
actualDualStackDialContext = dualStackDialContext
|
|
||||||
tcpConcurrent = false
|
|
||||||
DisableIPv6 = false
|
|
||||||
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
|
||||||
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
@ -36,23 +23,37 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
o(opt)
|
o(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opt.network == 4 || opt.network == 6 {
|
|
||||||
if strings.Contains(network, "tcp") {
|
|
||||||
network = "tcp"
|
|
||||||
} else {
|
|
||||||
network = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
network = fmt.Sprintf("%s%d", network, opt.network)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
return actualSingleDialContext(ctx, network, address, opt)
|
host, port, err := net.SplitHostPort(address)
|
||||||
case "tcp", "udp":
|
if err != nil {
|
||||||
return actualDualStackDialContext(ctx, network, address, opt)
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ip netip.Addr
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return nil, ErrorInvalidedNetworkStack
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialContext(ctx, network, ip, port, opt)
|
||||||
|
case "tcp", "udp":
|
||||||
|
return dualStackDialContext(ctx, network, address, opt)
|
||||||
|
default:
|
||||||
|
return nil, errors.New("network invalid")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,24 +89,6 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func SetDial(concurrent bool) {
|
|
||||||
dialMux.Lock()
|
|
||||||
tcpConcurrent = concurrent
|
|
||||||
if concurrent {
|
|
||||||
actualSingleDialContext = concurrentSingleDialContext
|
|
||||||
actualDualStackDialContext = concurrentDualStackDialContext
|
|
||||||
} else {
|
|
||||||
actualSingleDialContext = singleDialContext
|
|
||||||
actualDualStackDialContext = dualStackDialContext
|
|
||||||
}
|
|
||||||
|
|
||||||
dialMux.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetDial() bool {
|
|
||||||
return tcpConcurrent
|
|
||||||
}
|
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
@ -117,10 +100,6 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
if DisableIPv6 && destination.Is6() {
|
|
||||||
return nil, ErrorDisableIPv6
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -180,10 +159,7 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
go startRacer(ctx, network+"4", host, opt.direct, false)
|
go startRacer(ctx, network+"4", host, opt.direct, false)
|
||||||
go startRacer(ctx, network+"6", host, opt.direct, true)
|
go startRacer(ctx, network+"6", host, opt.direct, true)
|
||||||
|
|
||||||
count := 2
|
for res := range results {
|
||||||
for i := 0; i < count; i++ {
|
|
||||||
select {
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
return res.Conn, nil
|
return res.Conn, nil
|
||||||
}
|
}
|
||||||
@ -203,210 +179,7 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
return nil, primary.error
|
return nil, primary.error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case <-ctx.Done():
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("dual stack tcp shake hands failed")
|
return nil, errors.New("never touched")
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ips []netip.Addr
|
|
||||||
if opt.direct {
|
|
||||||
ips, err = resolver.ResolveAllIP(host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
|
||||||
returned := make(chan struct{})
|
|
||||||
defer close(returned)
|
|
||||||
|
|
||||||
type dialResult struct {
|
|
||||||
ip netip.Addr
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
isPrimary bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
|
|
||||||
preferCount := atomic.NewInt32(0)
|
|
||||||
results := make(chan dialResult)
|
|
||||||
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
|
||||||
result := dialResult{ip: ip, done: true}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
select {
|
|
||||||
case results <- result:
|
|
||||||
case <-returned:
|
|
||||||
if result.Conn != nil {
|
|
||||||
_ = result.Conn.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
if strings.Contains(network, "tcp") {
|
|
||||||
network = "tcp"
|
|
||||||
} else {
|
|
||||||
network = "udp"
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is6() {
|
|
||||||
network += "6"
|
|
||||||
if opt.prefer != 4 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.Is4() {
|
|
||||||
network += "4"
|
|
||||||
if opt.prefer != 6 {
|
|
||||||
result.isPrimary = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if result.isPrimary {
|
|
||||||
preferCount.Add(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, ip := range ips {
|
|
||||||
go tcpRacer(ctx, ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
connCount := len(ips)
|
|
||||||
var fallback dialResult
|
|
||||||
var primaryError error
|
|
||||||
for i := 0; i < connCount; i++ {
|
|
||||||
select {
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
if res.isPrimary {
|
|
||||||
return res.Conn, nil
|
|
||||||
} else {
|
|
||||||
if !fallback.done || fallback.error != nil {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if res.isPrimary {
|
|
||||||
primaryError = res.error
|
|
||||||
preferCount.Add(-1)
|
|
||||||
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case <-ctx.Done():
|
|
||||||
if fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallback.done && fallback.error == nil {
|
|
||||||
return fallback.Conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if primaryError != nil {
|
|
||||||
return nil, primaryError
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallback.error != nil {
|
|
||||||
return nil, fallback.error
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
|
||||||
}
|
|
||||||
|
|
||||||
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ip netip.Addr
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
return concurrentIPv4DialContext(ctx, network, address, opt)
|
|
||||||
default:
|
|
||||||
return concurrentIPv6DialContext(ctx, network, address, opt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ips []netip.Addr
|
|
||||||
if !opt.direct {
|
|
||||||
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.ResolveAllIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
|
||||||
host, port, err := net.SplitHostPort(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ips []netip.Addr
|
|
||||||
if !opt.direct {
|
|
||||||
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ips, err = resolver.ResolveAllIPv6(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return concurrentDialContext(ctx, network, ips, port, opt)
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import "go.uber.org/atomic"
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
DefaultOptions []Option
|
DefaultOptions []Option
|
||||||
@ -15,8 +13,6 @@ type option struct {
|
|||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
direct bool
|
direct bool
|
||||||
network int
|
|
||||||
prefer int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -44,25 +40,3 @@ func WithDirect() Option {
|
|||||||
opt.direct = true
|
opt.direct = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithPreferIPv4() Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.prefer = 4
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithPreferIPv6() Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.prefer = 6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func WithOnlySingleStack(isIPv4 bool) Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
if isIPv4 {
|
|
||||||
opt.network = 4
|
|
||||||
} else {
|
|
||||||
opt.network = 6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,99 +0,0 @@
|
|||||||
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
|
||||||
#ifndef __BPF_ENDIAN__
|
|
||||||
#define __BPF_ENDIAN__
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Isolate byte #n and put it into byte #m, for __u##b type.
|
|
||||||
* E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64:
|
|
||||||
* 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx
|
|
||||||
* 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000
|
|
||||||
* 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn
|
|
||||||
* 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000
|
|
||||||
*/
|
|
||||||
#define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8))
|
|
||||||
|
|
||||||
#define ___bpf_swab16(x) ((__u16)( \
|
|
||||||
___bpf_mvb(x, 16, 0, 1) | \
|
|
||||||
___bpf_mvb(x, 16, 1, 0)))
|
|
||||||
|
|
||||||
#define ___bpf_swab32(x) ((__u32)( \
|
|
||||||
___bpf_mvb(x, 32, 0, 3) | \
|
|
||||||
___bpf_mvb(x, 32, 1, 2) | \
|
|
||||||
___bpf_mvb(x, 32, 2, 1) | \
|
|
||||||
___bpf_mvb(x, 32, 3, 0)))
|
|
||||||
|
|
||||||
#define ___bpf_swab64(x) ((__u64)( \
|
|
||||||
___bpf_mvb(x, 64, 0, 7) | \
|
|
||||||
___bpf_mvb(x, 64, 1, 6) | \
|
|
||||||
___bpf_mvb(x, 64, 2, 5) | \
|
|
||||||
___bpf_mvb(x, 64, 3, 4) | \
|
|
||||||
___bpf_mvb(x, 64, 4, 3) | \
|
|
||||||
___bpf_mvb(x, 64, 5, 2) | \
|
|
||||||
___bpf_mvb(x, 64, 6, 1) | \
|
|
||||||
___bpf_mvb(x, 64, 7, 0)))
|
|
||||||
|
|
||||||
/* LLVM's BPF target selects the endianness of the CPU
|
|
||||||
* it compiles on, or the user specifies (bpfel/bpfeb),
|
|
||||||
* respectively. The used __BYTE_ORDER__ is defined by
|
|
||||||
* the compiler, we cannot rely on __BYTE_ORDER from
|
|
||||||
* libc headers, since it doesn't reflect the actual
|
|
||||||
* requested byte order.
|
|
||||||
*
|
|
||||||
* Note, LLVM's BPF target has different __builtin_bswapX()
|
|
||||||
* semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
|
|
||||||
* in bpfel and bpfeb case, which means below, that we map
|
|
||||||
* to cpu_to_be16(). We could use it unconditionally in BPF
|
|
||||||
* case, but better not rely on it, so that this header here
|
|
||||||
* can be used from application and BPF program side, which
|
|
||||||
* use different targets.
|
|
||||||
*/
|
|
||||||
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
|
||||||
# define __bpf_ntohs(x) __builtin_bswap16(x)
|
|
||||||
# define __bpf_htons(x) __builtin_bswap16(x)
|
|
||||||
# define __bpf_constant_ntohs(x) ___bpf_swab16(x)
|
|
||||||
# define __bpf_constant_htons(x) ___bpf_swab16(x)
|
|
||||||
# define __bpf_ntohl(x) __builtin_bswap32(x)
|
|
||||||
# define __bpf_htonl(x) __builtin_bswap32(x)
|
|
||||||
# define __bpf_constant_ntohl(x) ___bpf_swab32(x)
|
|
||||||
# define __bpf_constant_htonl(x) ___bpf_swab32(x)
|
|
||||||
# define __bpf_be64_to_cpu(x) __builtin_bswap64(x)
|
|
||||||
# define __bpf_cpu_to_be64(x) __builtin_bswap64(x)
|
|
||||||
# define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x)
|
|
||||||
# define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x)
|
|
||||||
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
|
|
||||||
# define __bpf_ntohs(x) (x)
|
|
||||||
# define __bpf_htons(x) (x)
|
|
||||||
# define __bpf_constant_ntohs(x) (x)
|
|
||||||
# define __bpf_constant_htons(x) (x)
|
|
||||||
# define __bpf_ntohl(x) (x)
|
|
||||||
# define __bpf_htonl(x) (x)
|
|
||||||
# define __bpf_constant_ntohl(x) (x)
|
|
||||||
# define __bpf_constant_htonl(x) (x)
|
|
||||||
# define __bpf_be64_to_cpu(x) (x)
|
|
||||||
# define __bpf_cpu_to_be64(x) (x)
|
|
||||||
# define __bpf_constant_be64_to_cpu(x) (x)
|
|
||||||
# define __bpf_constant_cpu_to_be64(x) (x)
|
|
||||||
#else
|
|
||||||
# error "Fix your compiler's __BYTE_ORDER__?!"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define bpf_htons(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_htons(x) : __bpf_htons(x))
|
|
||||||
#define bpf_ntohs(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_ntohs(x) : __bpf_ntohs(x))
|
|
||||||
#define bpf_htonl(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_htonl(x) : __bpf_htonl(x))
|
|
||||||
#define bpf_ntohl(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_ntohl(x) : __bpf_ntohl(x))
|
|
||||||
#define bpf_cpu_to_be64(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
|
|
||||||
#define bpf_be64_to_cpu(x) \
|
|
||||||
(__builtin_constant_p(x) ? \
|
|
||||||
__bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
|
|
||||||
|
|
||||||
#endif /* __BPF_ENDIAN__ */
|
|
File diff suppressed because it is too large
Load Diff
@ -1,262 +0,0 @@
|
|||||||
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
|
||||||
#ifndef __BPF_HELPERS__
|
|
||||||
#define __BPF_HELPERS__
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Note that bpf programs need to include either
|
|
||||||
* vmlinux.h (auto-generated from BTF) or linux/types.h
|
|
||||||
* in advance since bpf_helper_defs.h uses such types
|
|
||||||
* as __u64.
|
|
||||||
*/
|
|
||||||
#include "bpf_helper_defs.h"
|
|
||||||
|
|
||||||
#define __uint(name, val) int (*name)[val]
|
|
||||||
#define __type(name, val) typeof(val) *name
|
|
||||||
#define __array(name, val) typeof(val) *name[]
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper macro to place programs, maps, license in
|
|
||||||
* different sections in elf_bpf file. Section names
|
|
||||||
* are interpreted by libbpf depending on the context (BPF programs, BPF maps,
|
|
||||||
* extern variables, etc).
|
|
||||||
* To allow use of SEC() with externs (e.g., for extern .maps declarations),
|
|
||||||
* make sure __attribute__((unused)) doesn't trigger compilation warning.
|
|
||||||
*/
|
|
||||||
#define SEC(name) \
|
|
||||||
_Pragma("GCC diagnostic push") \
|
|
||||||
_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \
|
|
||||||
__attribute__((section(name), used)) \
|
|
||||||
_Pragma("GCC diagnostic pop") \
|
|
||||||
|
|
||||||
/* Avoid 'linux/stddef.h' definition of '__always_inline'. */
|
|
||||||
#undef __always_inline
|
|
||||||
#define __always_inline inline __attribute__((always_inline))
|
|
||||||
|
|
||||||
#ifndef __noinline
|
|
||||||
#define __noinline __attribute__((noinline))
|
|
||||||
#endif
|
|
||||||
#ifndef __weak
|
|
||||||
#define __weak __attribute__((weak))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Use __hidden attribute to mark a non-static BPF subprogram effectively
|
|
||||||
* static for BPF verifier's verification algorithm purposes, allowing more
|
|
||||||
* extensive and permissive BPF verification process, taking into account
|
|
||||||
* subprogram's caller context.
|
|
||||||
*/
|
|
||||||
#define __hidden __attribute__((visibility("hidden")))
|
|
||||||
|
|
||||||
/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
|
|
||||||
* any system-level headers (such as stddef.h, linux/version.h, etc), and
|
|
||||||
* commonly-used macros like NULL and KERNEL_VERSION aren't available through
|
|
||||||
* vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
|
|
||||||
* them on their own. So as a convenience, provide such definitions here.
|
|
||||||
*/
|
|
||||||
#ifndef NULL
|
|
||||||
#define NULL ((void *)0)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef KERNEL_VERSION
|
|
||||||
#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper macros to manipulate data structures
|
|
||||||
*/
|
|
||||||
#ifndef offsetof
|
|
||||||
#define offsetof(TYPE, MEMBER) ((unsigned long)&((TYPE *)0)->MEMBER)
|
|
||||||
#endif
|
|
||||||
#ifndef container_of
|
|
||||||
#define container_of(ptr, type, member) \
|
|
||||||
({ \
|
|
||||||
void *__mptr = (void *)(ptr); \
|
|
||||||
((type *)(__mptr - offsetof(type, member))); \
|
|
||||||
})
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper macro to throw a compilation error if __bpf_unreachable() gets
|
|
||||||
* built into the resulting code. This works given BPF back end does not
|
|
||||||
* implement __builtin_trap(). This is useful to assert that certain paths
|
|
||||||
* of the program code are never used and hence eliminated by the compiler.
|
|
||||||
*
|
|
||||||
* For example, consider a switch statement that covers known cases used by
|
|
||||||
* the program. __bpf_unreachable() can then reside in the default case. If
|
|
||||||
* the program gets extended such that a case is not covered in the switch
|
|
||||||
* statement, then it will throw a build error due to the default case not
|
|
||||||
* being compiled out.
|
|
||||||
*/
|
|
||||||
#ifndef __bpf_unreachable
|
|
||||||
# define __bpf_unreachable() __builtin_trap()
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper function to perform a tail call with a constant/immediate map slot.
|
|
||||||
*/
|
|
||||||
#if __clang_major__ >= 8 && defined(__bpf__)
|
|
||||||
static __always_inline void
|
|
||||||
bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
|
|
||||||
{
|
|
||||||
if (!__builtin_constant_p(slot))
|
|
||||||
__bpf_unreachable();
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Provide a hard guarantee that LLVM won't optimize setting r2 (map
|
|
||||||
* pointer) and r3 (constant map index) from _different paths_ ending
|
|
||||||
* up at the _same_ call insn as otherwise we won't be able to use the
|
|
||||||
* jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
|
|
||||||
* given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
|
|
||||||
* tracking for prog array pokes") for details on verifier tracking.
|
|
||||||
*
|
|
||||||
* Note on clobber list: we need to stay in-line with BPF calling
|
|
||||||
* convention, so even if we don't end up using r0, r4, r5, we need
|
|
||||||
* to mark them as clobber so that LLVM doesn't end up using them
|
|
||||||
* before / after the call.
|
|
||||||
*/
|
|
||||||
asm volatile("r1 = %[ctx]\n\t"
|
|
||||||
"r2 = %[map]\n\t"
|
|
||||||
"r3 = %[slot]\n\t"
|
|
||||||
"call 12"
|
|
||||||
:: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
|
|
||||||
: "r0", "r1", "r2", "r3", "r4", "r5");
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper structure used by eBPF C program
|
|
||||||
* to describe BPF map attributes to libbpf loader
|
|
||||||
*/
|
|
||||||
struct bpf_map_def {
|
|
||||||
unsigned int type;
|
|
||||||
unsigned int key_size;
|
|
||||||
unsigned int value_size;
|
|
||||||
unsigned int max_entries;
|
|
||||||
unsigned int map_flags;
|
|
||||||
};
|
|
||||||
|
|
||||||
enum libbpf_pin_type {
|
|
||||||
LIBBPF_PIN_NONE,
|
|
||||||
/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
|
|
||||||
LIBBPF_PIN_BY_NAME,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum libbpf_tristate {
|
|
||||||
TRI_NO = 0,
|
|
||||||
TRI_YES = 1,
|
|
||||||
TRI_MODULE = 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
#define __kconfig __attribute__((section(".kconfig")))
|
|
||||||
#define __ksym __attribute__((section(".ksyms")))
|
|
||||||
|
|
||||||
#ifndef ___bpf_concat
|
|
||||||
#define ___bpf_concat(a, b) a ## b
|
|
||||||
#endif
|
|
||||||
#ifndef ___bpf_apply
|
|
||||||
#define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
|
|
||||||
#endif
|
|
||||||
#ifndef ___bpf_nth
|
|
||||||
#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
|
|
||||||
#endif
|
|
||||||
#ifndef ___bpf_narg
|
|
||||||
#define ___bpf_narg(...) \
|
|
||||||
___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define ___bpf_fill0(arr, p, x) do {} while (0)
|
|
||||||
#define ___bpf_fill1(arr, p, x) arr[p] = x
|
|
||||||
#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
|
|
||||||
#define ___bpf_fill(arr, args...) \
|
|
||||||
___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
|
|
||||||
|
|
||||||
/*
|
|
||||||
* BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
|
|
||||||
* in a structure.
|
|
||||||
*/
|
|
||||||
#define BPF_SEQ_PRINTF(seq, fmt, args...) \
|
|
||||||
({ \
|
|
||||||
static const char ___fmt[] = fmt; \
|
|
||||||
unsigned long long ___param[___bpf_narg(args)]; \
|
|
||||||
\
|
|
||||||
_Pragma("GCC diagnostic push") \
|
|
||||||
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
|
||||||
___bpf_fill(___param, args); \
|
|
||||||
_Pragma("GCC diagnostic pop") \
|
|
||||||
\
|
|
||||||
bpf_seq_printf(seq, ___fmt, sizeof(___fmt), \
|
|
||||||
___param, sizeof(___param)); \
|
|
||||||
})
|
|
||||||
|
|
||||||
/*
|
|
||||||
* BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
|
|
||||||
* an array of u64.
|
|
||||||
*/
|
|
||||||
#define BPF_SNPRINTF(out, out_size, fmt, args...) \
|
|
||||||
({ \
|
|
||||||
static const char ___fmt[] = fmt; \
|
|
||||||
unsigned long long ___param[___bpf_narg(args)]; \
|
|
||||||
\
|
|
||||||
_Pragma("GCC diagnostic push") \
|
|
||||||
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
|
||||||
___bpf_fill(___param, args); \
|
|
||||||
_Pragma("GCC diagnostic pop") \
|
|
||||||
\
|
|
||||||
bpf_snprintf(out, out_size, ___fmt, \
|
|
||||||
___param, sizeof(___param)); \
|
|
||||||
})
|
|
||||||
|
|
||||||
#ifdef BPF_NO_GLOBAL_DATA
|
|
||||||
#define BPF_PRINTK_FMT_MOD
|
|
||||||
#else
|
|
||||||
#define BPF_PRINTK_FMT_MOD static const
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define __bpf_printk(fmt, ...) \
|
|
||||||
({ \
|
|
||||||
BPF_PRINTK_FMT_MOD char ____fmt[] = fmt; \
|
|
||||||
bpf_trace_printk(____fmt, sizeof(____fmt), \
|
|
||||||
##__VA_ARGS__); \
|
|
||||||
})
|
|
||||||
|
|
||||||
/*
|
|
||||||
* __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
|
|
||||||
* instead of an array of u64.
|
|
||||||
*/
|
|
||||||
#define __bpf_vprintk(fmt, args...) \
|
|
||||||
({ \
|
|
||||||
static const char ___fmt[] = fmt; \
|
|
||||||
unsigned long long ___param[___bpf_narg(args)]; \
|
|
||||||
\
|
|
||||||
_Pragma("GCC diagnostic push") \
|
|
||||||
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
|
||||||
___bpf_fill(___param, args); \
|
|
||||||
_Pragma("GCC diagnostic pop") \
|
|
||||||
\
|
|
||||||
bpf_trace_vprintk(___fmt, sizeof(___fmt), \
|
|
||||||
___param, sizeof(___param)); \
|
|
||||||
})
|
|
||||||
|
|
||||||
/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
|
|
||||||
* Otherwise use __bpf_vprintk
|
|
||||||
*/
|
|
||||||
#define ___bpf_pick_printk(...) \
|
|
||||||
___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
|
||||||
__bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
|
||||||
__bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
|
|
||||||
__bpf_printk /*1*/, __bpf_printk /*0*/)
|
|
||||||
|
|
||||||
/* Helper macro to print out debug messages */
|
|
||||||
#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
|
|
||||||
|
|
||||||
#endif
|
|
@ -1,342 +0,0 @@
|
|||||||
#include <stdint.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
//#include <linux/types.h>
|
|
||||||
|
|
||||||
#include <linux/bpf.h>
|
|
||||||
#include <linux/if_ether.h>
|
|
||||||
//#include <linux/if_packet.h>
|
|
||||||
//#include <linux/if_vlan.h>
|
|
||||||
#include <linux/ip.h>
|
|
||||||
#include <linux/in.h>
|
|
||||||
#include <linux/tcp.h>
|
|
||||||
//#include <linux/udp.h>
|
|
||||||
|
|
||||||
#include <linux/pkt_cls.h>
|
|
||||||
|
|
||||||
#include "bpf_endian.h"
|
|
||||||
#include "bpf_helpers.h"
|
|
||||||
|
|
||||||
#define IP_CSUM_OFF (ETH_HLEN + offsetof(struct iphdr, check))
|
|
||||||
#define IP_DST_OFF (ETH_HLEN + offsetof(struct iphdr, daddr))
|
|
||||||
#define IP_SRC_OFF (ETH_HLEN + offsetof(struct iphdr, saddr))
|
|
||||||
#define IP_PROTO_OFF (ETH_HLEN + offsetof(struct iphdr, protocol))
|
|
||||||
#define TCP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, check))
|
|
||||||
#define TCP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, source))
|
|
||||||
#define TCP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, dest))
|
|
||||||
//#define UDP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, check))
|
|
||||||
//#define UDP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, source))
|
|
||||||
//#define UDP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, dest))
|
|
||||||
#define IS_PSEUDO 0x10
|
|
||||||
|
|
||||||
struct origin_info {
|
|
||||||
__be32 ip;
|
|
||||||
__be16 port;
|
|
||||||
__u16 pad;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct origin_info *origin_info_unused __attribute__((unused));
|
|
||||||
|
|
||||||
struct redir_info {
|
|
||||||
__be32 sip;
|
|
||||||
__be32 dip;
|
|
||||||
__be16 sport;
|
|
||||||
__be16 dport;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct redir_info *redir_info_unused __attribute__((unused));
|
|
||||||
|
|
||||||
struct {
|
|
||||||
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
|
||||||
__type(key, struct redir_info);
|
|
||||||
__type(value, struct origin_info);
|
|
||||||
__uint(max_entries, 65535);
|
|
||||||
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
|
||||||
} pair_original_dst_map SEC(".maps");
|
|
||||||
|
|
||||||
struct {
|
|
||||||
__uint(type, BPF_MAP_TYPE_ARRAY);
|
|
||||||
__type(key, __u32);
|
|
||||||
__type(value, __u32);
|
|
||||||
__uint(max_entries, 3);
|
|
||||||
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
|
||||||
} redir_params_map SEC(".maps");
|
|
||||||
|
|
||||||
static __always_inline int rewrite_ip(struct __sk_buff *skb, __be32 new_ip, bool is_dest) {
|
|
||||||
int ret, off = 0, flags = IS_PSEUDO;
|
|
||||||
__be32 old_ip;
|
|
||||||
|
|
||||||
if (is_dest)
|
|
||||||
ret = bpf_skb_load_bytes(skb, IP_DST_OFF, &old_ip, 4);
|
|
||||||
else
|
|
||||||
ret = bpf_skb_load_bytes(skb, IP_SRC_OFF, &old_ip, 4);
|
|
||||||
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
off = TCP_CSUM_OFF;
|
|
||||||
// __u8 proto;
|
|
||||||
//
|
|
||||||
// ret = bpf_skb_load_bytes(skb, IP_PROTO_OFF, &proto, 1);
|
|
||||||
// if (ret < 0) {
|
|
||||||
// return BPF_DROP;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// switch (proto) {
|
|
||||||
// case IPPROTO_TCP:
|
|
||||||
// off = TCP_CSUM_OFF;
|
|
||||||
// break;
|
|
||||||
//
|
|
||||||
// case IPPROTO_UDP:
|
|
||||||
// off = UDP_CSUM_OFF;
|
|
||||||
// flags |= BPF_F_MARK_MANGLED_0;
|
|
||||||
// break;
|
|
||||||
//
|
|
||||||
// case IPPROTO_ICMPV6:
|
|
||||||
// off = offsetof(struct icmp6hdr, icmp6_cksum);
|
|
||||||
// break;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if (off) {
|
|
||||||
ret = bpf_l4_csum_replace(skb, off, old_ip, new_ip, flags | sizeof(new_ip));
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
// }
|
|
||||||
|
|
||||||
ret = bpf_l3_csum_replace(skb, IP_CSUM_OFF, old_ip, new_ip, sizeof(new_ip));
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_dest)
|
|
||||||
ret = bpf_skb_store_bytes(skb, IP_DST_OFF, &new_ip, sizeof(new_ip), 0);
|
|
||||||
else
|
|
||||||
ret = bpf_skb_store_bytes(skb, IP_SRC_OFF, &new_ip, sizeof(new_ip), 0);
|
|
||||||
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
static __always_inline int rewrite_port(struct __sk_buff *skb, __be16 new_port, bool is_dest) {
|
|
||||||
int ret, off = 0;
|
|
||||||
__be16 old_port;
|
|
||||||
|
|
||||||
if (is_dest)
|
|
||||||
ret = bpf_skb_load_bytes(skb, TCP_DST_OFF, &old_port, 2);
|
|
||||||
else
|
|
||||||
ret = bpf_skb_load_bytes(skb, TCP_SRC_OFF, &old_port, 2);
|
|
||||||
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
off = TCP_CSUM_OFF;
|
|
||||||
|
|
||||||
ret = bpf_l4_csum_replace(skb, off, old_port, new_port, sizeof(new_port));
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_dest)
|
|
||||||
ret = bpf_skb_store_bytes(skb, TCP_DST_OFF, &new_port, sizeof(new_port), 0);
|
|
||||||
else
|
|
||||||
ret = bpf_skb_store_bytes(skb, TCP_SRC_OFF, &new_port, sizeof(new_port), 0);
|
|
||||||
|
|
||||||
if (ret < 0) {
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
static __always_inline bool is_lan_ip(__be32 addr) {
|
|
||||||
if (addr == 0xffffffff)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
__u8 fist = (__u8)(addr & 0xff);
|
|
||||||
|
|
||||||
if (fist == 127 || fist == 10)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
__u8 second = (__u8)((addr >> 8) & 0xff);
|
|
||||||
|
|
||||||
if (fist == 172 && second >= 16 && second <= 31)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
if (fist == 192 && second == 168)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
SEC("tc_clash_auto_redir_ingress")
|
|
||||||
int tc_redir_ingress_func(struct __sk_buff *skb) {
|
|
||||||
void *data = (void *)(long)skb->data;
|
|
||||||
void *data_end = (void *)(long)skb->data_end;
|
|
||||||
struct ethhdr *eth = data;
|
|
||||||
|
|
||||||
if ((void *)(eth + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
|
||||||
if ((void *)(iph + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__u32 key = 0, *route_index, *redir_ip, *redir_port;
|
|
||||||
|
|
||||||
route_index = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
if (!route_index)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (iph->protocol == IPPROTO_ICMP && *route_index != 0)
|
|
||||||
return bpf_redirect(*route_index, 0);
|
|
||||||
|
|
||||||
if (iph->protocol != IPPROTO_TCP)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
|
||||||
if ((void *)(tcph + 1) > data_end)
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
|
|
||||||
key = 1;
|
|
||||||
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
if (!redir_ip)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
key = 2;
|
|
||||||
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
if (!redir_port)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__be32 new_ip = bpf_htonl(*redir_ip);
|
|
||||||
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
|
||||||
__be32 old_ip = iph->daddr;
|
|
||||||
__be16 old_port = tcph->dest;
|
|
||||||
|
|
||||||
if (old_ip == new_ip || is_lan_ip(old_ip) || bpf_ntohs(old_port) == 53) {
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct redir_info p_key = {
|
|
||||||
.sip = iph->saddr,
|
|
||||||
.sport = tcph->source,
|
|
||||||
.dip = new_ip,
|
|
||||||
.dport = new_port,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (tcph->syn && !tcph->ack) {
|
|
||||||
struct origin_info origin = {
|
|
||||||
.ip = old_ip,
|
|
||||||
.port = old_port,
|
|
||||||
};
|
|
||||||
|
|
||||||
bpf_map_update_elem(&pair_original_dst_map, &p_key, &origin, BPF_NOEXIST);
|
|
||||||
|
|
||||||
if (rewrite_ip(skb, new_ip, true) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rewrite_port(skb, new_port, true) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
|
||||||
if (!origin) {
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rewrite_ip(skb, new_ip, true) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rewrite_port(skb, new_port, true) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
SEC("tc_clash_auto_redir_egress")
|
|
||||||
int tc_redir_egress_func(struct __sk_buff *skb) {
|
|
||||||
void *data = (void *)(long)skb->data;
|
|
||||||
void *data_end = (void *)(long)skb->data_end;
|
|
||||||
struct ethhdr *eth = data;
|
|
||||||
|
|
||||||
if ((void *)(eth + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__u32 key = 0, *redir_ip, *redir_port; // *clash_mark
|
|
||||||
|
|
||||||
// clash_mark = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
// if (clash_mark && *clash_mark != 0 && *clash_mark == skb->mark)
|
|
||||||
// return TC_ACT_OK;
|
|
||||||
|
|
||||||
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
|
||||||
if ((void *)(iph + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (iph->protocol != IPPROTO_TCP)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
|
||||||
if ((void *)(tcph + 1) > data_end)
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
|
|
||||||
key = 1;
|
|
||||||
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
if (!redir_ip)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
key = 2;
|
|
||||||
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
|
||||||
if (!redir_port)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__be32 new_ip = bpf_htonl(*redir_ip);
|
|
||||||
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
|
||||||
__be32 old_ip = iph->saddr;
|
|
||||||
__be16 old_port = tcph->source;
|
|
||||||
|
|
||||||
if (old_ip != new_ip || old_port != new_port) {
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct redir_info p_key = {
|
|
||||||
.sip = iph->daddr,
|
|
||||||
.sport = tcph->dest,
|
|
||||||
.dip = iph->saddr,
|
|
||||||
.dport = tcph->source,
|
|
||||||
};
|
|
||||||
|
|
||||||
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
|
||||||
if (!origin) {
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tcph->fin && tcph->ack) {
|
|
||||||
bpf_map_delete_elem(&pair_original_dst_map, &p_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rewrite_ip(skb, origin->ip, false) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rewrite_port(skb, origin->port, false) < 0) {
|
|
||||||
return TC_ACT_SHOT;
|
|
||||||
}
|
|
||||||
|
|
||||||
return TC_ACT_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
char _license[] SEC("license") = "GPL";
|
|
@ -1,103 +0,0 @@
|
|||||||
#include <stdbool.h>
|
|
||||||
#include <linux/bpf.h>
|
|
||||||
#include <linux/if_ether.h>
|
|
||||||
#include <linux/ip.h>
|
|
||||||
#include <linux/in.h>
|
|
||||||
//#include <linux/tcp.h>
|
|
||||||
//#include <linux/udp.h>
|
|
||||||
#include <linux/pkt_cls.h>
|
|
||||||
|
|
||||||
#include "bpf_endian.h"
|
|
||||||
#include "bpf_helpers.h"
|
|
||||||
|
|
||||||
struct {
|
|
||||||
__uint(type, BPF_MAP_TYPE_ARRAY);
|
|
||||||
__type(key, __u32);
|
|
||||||
__type(value, __u32);
|
|
||||||
__uint(max_entries, 2);
|
|
||||||
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
|
||||||
} tc_params_map SEC(".maps");
|
|
||||||
|
|
||||||
static __always_inline bool is_lan_ip(__be32 addr) {
|
|
||||||
if (addr == 0xffffffff)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
__u8 fist = (__u8)(addr & 0xff);
|
|
||||||
|
|
||||||
if (fist == 127 || fist == 10)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
__u8 second = (__u8)((addr >> 8) & 0xff);
|
|
||||||
|
|
||||||
if (fist == 172 && second >= 16 && second <= 31)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
if (fist == 192 && second == 168)
|
|
||||||
return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
SEC("tc_clash_redirect_to_tun")
|
|
||||||
int tc_tun_func(struct __sk_buff *skb) {
|
|
||||||
void *data = (void *)(long)skb->data;
|
|
||||||
void *data_end = (void *)(long)skb->data_end;
|
|
||||||
struct ethhdr *eth = data;
|
|
||||||
|
|
||||||
if ((void *)(eth + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (eth->h_proto == bpf_htons(ETH_P_ARP))
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__u32 key = 0, *clash_mark, *tun_ifindex;
|
|
||||||
|
|
||||||
clash_mark = bpf_map_lookup_elem(&tc_params_map, &key);
|
|
||||||
if (!clash_mark)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (skb->mark == *clash_mark)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (eth->h_proto == bpf_htons(ETH_P_IP)) {
|
|
||||||
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
|
||||||
if ((void *)(iph + 1) > data_end)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
if (iph->protocol == IPPROTO_ICMP)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
__be32 daddr = iph->daddr;
|
|
||||||
|
|
||||||
if (is_lan_ip(daddr))
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
// if (iph->protocol == IPPROTO_TCP) {
|
|
||||||
// struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
|
||||||
// if ((void *)(tcph + 1) > data_end)
|
|
||||||
// return TC_ACT_OK;
|
|
||||||
//
|
|
||||||
// __u16 source = bpf_ntohs(tcph->source);
|
|
||||||
// if (source == 22 || source == 80 || source == 443 || source == 8080 || source == 8443 || source == 9090 || (source >= 7890 && source <= 7895))
|
|
||||||
// return TC_ACT_OK;
|
|
||||||
// } else if (iph->protocol == IPPROTO_UDP) {
|
|
||||||
// struct udphdr *udph = (struct udphdr *)(iph + 1);
|
|
||||||
// if ((void *)(udph + 1) > data_end)
|
|
||||||
// return TC_ACT_OK;
|
|
||||||
//
|
|
||||||
// __u16 source = bpf_ntohs(udph->source);
|
|
||||||
// if (source == 53 || (source >= 135 && source <= 139))
|
|
||||||
// return TC_ACT_OK;
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
|
|
||||||
key = 1;
|
|
||||||
tun_ifindex = bpf_map_lookup_elem(&tc_params_map, &key);
|
|
||||||
if (!tun_ifindex)
|
|
||||||
return TC_ACT_OK;
|
|
||||||
|
|
||||||
//return bpf_redirect(*tun_ifindex, BPF_F_INGRESS); // __bpf_rx_skb
|
|
||||||
return bpf_redirect(*tun_ifindex, 0); // __bpf_tx_skb / __dev_xmit_skb
|
|
||||||
}
|
|
||||||
|
|
||||||
char _license[] SEC("license") = "GPL";
|
|
@ -1,13 +0,0 @@
|
|||||||
package byteorder
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NetIPv4ToHost32 converts an net.IP to a uint32 in host byte order. ip
|
|
||||||
// must be a IPv4 address, otherwise the function will panic.
|
|
||||||
func NetIPv4ToHost32(ip net.IP) uint32 {
|
|
||||||
ipv4 := ip.To4()
|
|
||||||
_ = ipv4[3] // Assert length of ipv4.
|
|
||||||
return Native.Uint32(ipv4)
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
|
||||||
|
|
||||||
package byteorder
|
|
||||||
|
|
||||||
import "encoding/binary"
|
|
||||||
|
|
||||||
var Native binary.ByteOrder = binary.BigEndian
|
|
||||||
|
|
||||||
func HostToNetwork16(u uint16) uint16 { return u }
|
|
||||||
func HostToNetwork32(u uint32) uint32 { return u }
|
|
||||||
func NetworkToHost16(u uint16) uint16 { return u }
|
|
||||||
func NetworkToHost32(u uint32) uint32 { return u }
|
|
@ -1,15 +0,0 @@
|
|||||||
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
|
||||||
|
|
||||||
package byteorder
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"math/bits"
|
|
||||||
)
|
|
||||||
|
|
||||||
var Native binary.ByteOrder = binary.LittleEndian
|
|
||||||
|
|
||||||
func HostToNetwork16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
|
||||||
func HostToNetwork32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
|
||||||
func NetworkToHost16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
|
||||||
func NetworkToHost32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
|
@ -1,33 +0,0 @@
|
|||||||
package ebpf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
|
||||||
|
|
||||||
type TcEBpfProgram struct {
|
|
||||||
pros []C.EBpf
|
|
||||||
rawNICs []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TcEBpfProgram) RawNICs() []string {
|
|
||||||
return t.rawNICs
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TcEBpfProgram) Close() {
|
|
||||||
for _, p := range t.pros {
|
|
||||||
p.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *TcEBpfProgram) Lookup(srcAddrPort netip.AddrPort) (addr socks5.Addr, err error) {
|
|
||||||
for _, p := range t.pros {
|
|
||||||
addr, err = p.Lookup(srcAddrPort)
|
|
||||||
if err == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
@ -1,138 +0,0 @@
|
|||||||
//go:build !android
|
|
||||||
|
|
||||||
package ebpf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/vishvananda/netlink"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cmd"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/ebpf/redir"
|
|
||||||
"github.com/Dreamacro/clash/component/ebpf/tc"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetAutoDetectInterface() (string, error) {
|
|
||||||
routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, route := range routes {
|
|
||||||
if route.Dst == nil {
|
|
||||||
lk, err := netlink.LinkByIndex(route.LinkIndex)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
if lk.Type() == "tuntap" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
return lk.Attrs().Name, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", fmt.Errorf("interface not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTcEBpfProgram new redirect to tun ebpf program
|
|
||||||
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
|
||||||
tunIface, err := netlink.LinkByName(tunName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("lookup network iface %q: %w", tunName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tunIndex := uint32(tunIface.Attrs().Index)
|
|
||||||
|
|
||||||
dialer.DefaultRoutingMark.Store(C.ClashTrafficMark)
|
|
||||||
|
|
||||||
ifMark := uint32(dialer.DefaultRoutingMark.Load())
|
|
||||||
|
|
||||||
var pros []C.EBpf
|
|
||||||
for _, ifaceName := range ifaceNames {
|
|
||||||
iface, err := netlink.LinkByName(ifaceName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
|
||||||
}
|
|
||||||
if iface.Attrs().OperState != netlink.OperUp {
|
|
||||||
return nil, fmt.Errorf("network iface %q is down", ifaceName)
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := iface.Attrs()
|
|
||||||
index := attrs.Index
|
|
||||||
|
|
||||||
tcPro := tc.NewEBpfTc(ifaceName, index, ifMark, tunIndex)
|
|
||||||
if err = tcPro.Start(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pros = append(pros, tcPro)
|
|
||||||
}
|
|
||||||
|
|
||||||
systemSetting(ifaceNames...)
|
|
||||||
|
|
||||||
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRedirEBpfProgram new auto redirect ebpf program
|
|
||||||
func NewRedirEBpfProgram(ifaceNames []string, redirPort uint16, defaultRouteInterfaceName string) (*TcEBpfProgram, error) {
|
|
||||||
defaultRouteInterface, err := netlink.LinkByName(defaultRouteInterfaceName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("lookup network iface %q: %w", defaultRouteInterfaceName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
defaultRouteIndex := uint32(defaultRouteInterface.Attrs().Index)
|
|
||||||
|
|
||||||
var pros []C.EBpf
|
|
||||||
for _, ifaceName := range ifaceNames {
|
|
||||||
iface, err := netlink.LinkByName(ifaceName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := iface.Attrs()
|
|
||||||
index := attrs.Index
|
|
||||||
|
|
||||||
addrs, err := netlink.AddrList(iface, netlink.FAMILY_V4)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("lookup network iface %q address: %w", ifaceName, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(addrs) == 0 {
|
|
||||||
return nil, fmt.Errorf("network iface %q does not contain any ipv4 addresses", ifaceName)
|
|
||||||
}
|
|
||||||
|
|
||||||
address, _ := netip.AddrFromSlice(addrs[0].IP)
|
|
||||||
redirAddrPort := netip.AddrPortFrom(address, redirPort)
|
|
||||||
|
|
||||||
redirPro := redir.NewEBpfRedirect(ifaceName, index, 0, defaultRouteIndex, redirAddrPort)
|
|
||||||
if err = redirPro.Start(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pros = append(pros, redirPro)
|
|
||||||
}
|
|
||||||
|
|
||||||
systemSetting(ifaceNames...)
|
|
||||||
|
|
||||||
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func systemSetting(ifaceNames ...string) {
|
|
||||||
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.ip_forward=1")
|
|
||||||
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.forwarding=1")
|
|
||||||
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_local=1")
|
|
||||||
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_redirects=1")
|
|
||||||
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.rp_filter=0")
|
|
||||||
|
|
||||||
for _, ifaceName := range ifaceNames {
|
|
||||||
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.forwarding=1", ifaceName))
|
|
||||||
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_local=1", ifaceName))
|
|
||||||
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_redirects=1", ifaceName))
|
|
||||||
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.rp_filter=0", ifaceName))
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
//go:build !linux || android
|
|
||||||
|
|
||||||
package ebpf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewTcEBpfProgram new ebpf tc program
|
|
||||||
func NewTcEBpfProgram(_ []string, _ string) (*TcEBpfProgram, error) {
|
|
||||||
return nil, fmt.Errorf("system not supported")
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewRedirEBpfProgram new ebpf redirect program
|
|
||||||
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
|
||||||
return nil, fmt.Errorf("system not supported")
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetAutoDetectInterface() (string, error) {
|
|
||||||
return "", fmt.Errorf("system not supported")
|
|
||||||
}
|
|
@ -1,216 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package redir
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
"github.com/cilium/ebpf/rlimit"
|
|
||||||
"github.com/vishvananda/netlink"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/redir.c
|
|
||||||
|
|
||||||
const (
|
|
||||||
mapKey1 uint32 = 0
|
|
||||||
mapKey2 uint32 = 1
|
|
||||||
mapKey3 uint32 = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
type EBpfRedirect struct {
|
|
||||||
objs io.Closer
|
|
||||||
originMap *ebpf.Map
|
|
||||||
qdisc netlink.Qdisc
|
|
||||||
filter netlink.Filter
|
|
||||||
filterEgress netlink.Filter
|
|
||||||
|
|
||||||
ifName string
|
|
||||||
ifIndex int
|
|
||||||
ifMark uint32
|
|
||||||
rtIndex uint32
|
|
||||||
redirIp uint32
|
|
||||||
redirPort uint16
|
|
||||||
|
|
||||||
bpfPath string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEBpfRedirect(ifName string, ifIndex int, ifMark uint32, routeIndex uint32, redirAddrPort netip.AddrPort) *EBpfRedirect {
|
|
||||||
return &EBpfRedirect{
|
|
||||||
ifName: ifName,
|
|
||||||
ifIndex: ifIndex,
|
|
||||||
ifMark: ifMark,
|
|
||||||
rtIndex: routeIndex,
|
|
||||||
redirIp: binary.BigEndian.Uint32(redirAddrPort.Addr().AsSlice()),
|
|
||||||
redirPort: redirAddrPort.Port(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfRedirect) Start() error {
|
|
||||||
if err := rlimit.RemoveMemlock(); err != nil {
|
|
||||||
return fmt.Errorf("remove memory lock: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
|
||||||
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
|
||||||
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var objs bpfObjects
|
|
||||||
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
|
||||||
Maps: ebpf.MapOptions{
|
|
||||||
PinPath: e.bpfPath,
|
|
||||||
},
|
|
||||||
}); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("loading objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.objs = &objs
|
|
||||||
e.originMap = objs.bpfMaps.PairOriginalDstMap
|
|
||||||
|
|
||||||
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey1, e.rtIndex, ebpf.UpdateAny); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("storing objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey2, e.redirIp, ebpf.UpdateAny); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("storing objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey3, uint32(e.redirPort), ebpf.UpdateAny); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("storing objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := netlink.QdiscAttrs{
|
|
||||||
LinkIndex: e.ifIndex,
|
|
||||||
Handle: netlink.MakeHandle(0xffff, 0),
|
|
||||||
Parent: netlink.HANDLE_CLSACT,
|
|
||||||
}
|
|
||||||
|
|
||||||
qdisc := &netlink.GenericQdisc{
|
|
||||||
QdiscAttrs: attrs,
|
|
||||||
QdiscType: "clsact",
|
|
||||||
}
|
|
||||||
|
|
||||||
e.qdisc = qdisc
|
|
||||||
|
|
||||||
if err := netlink.QdiscAdd(qdisc); err != nil {
|
|
||||||
if os.IsExist(err) {
|
|
||||||
_ = netlink.QdiscDel(qdisc)
|
|
||||||
err = netlink.QdiscAdd(qdisc)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
filterAttrs := netlink.FilterAttrs{
|
|
||||||
LinkIndex: e.ifIndex,
|
|
||||||
Parent: netlink.HANDLE_MIN_INGRESS,
|
|
||||||
Handle: netlink.MakeHandle(0, 1),
|
|
||||||
Protocol: unix.ETH_P_IP,
|
|
||||||
Priority: 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
filter := &netlink.BpfFilter{
|
|
||||||
FilterAttrs: filterAttrs,
|
|
||||||
Fd: objs.bpfPrograms.TcRedirIngressFunc.FD(),
|
|
||||||
Name: "clash-redir-ingress-" + e.ifName,
|
|
||||||
DirectAction: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := netlink.FilterAdd(filter); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("cannot attach ebpf object to filter ingress: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.filter = filter
|
|
||||||
|
|
||||||
filterAttrsEgress := netlink.FilterAttrs{
|
|
||||||
LinkIndex: e.ifIndex,
|
|
||||||
Parent: netlink.HANDLE_MIN_EGRESS,
|
|
||||||
Handle: netlink.MakeHandle(0, 1),
|
|
||||||
Protocol: unix.ETH_P_IP,
|
|
||||||
Priority: 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
filterEgress := &netlink.BpfFilter{
|
|
||||||
FilterAttrs: filterAttrsEgress,
|
|
||||||
Fd: objs.bpfPrograms.TcRedirEgressFunc.FD(),
|
|
||||||
Name: "clash-redir-egress-" + e.ifName,
|
|
||||||
DirectAction: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := netlink.FilterAdd(filterEgress); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("cannot attach ebpf object to filter egress: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.filterEgress = filterEgress
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfRedirect) Close() {
|
|
||||||
if e.filter != nil {
|
|
||||||
_ = netlink.FilterDel(e.filter)
|
|
||||||
}
|
|
||||||
if e.filterEgress != nil {
|
|
||||||
_ = netlink.FilterDel(e.filterEgress)
|
|
||||||
}
|
|
||||||
if e.qdisc != nil {
|
|
||||||
_ = netlink.QdiscDel(e.qdisc)
|
|
||||||
}
|
|
||||||
if e.objs != nil {
|
|
||||||
_ = e.objs.Close()
|
|
||||||
}
|
|
||||||
_ = os.Remove(filepath.Join(e.bpfPath, "redir_params_map"))
|
|
||||||
_ = os.Remove(filepath.Join(e.bpfPath, "pair_original_dst_map"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfRedirect) Lookup(srcAddrPort netip.AddrPort) (socks5.Addr, error) {
|
|
||||||
rAddr := srcAddrPort.Addr().Unmap()
|
|
||||||
if rAddr.Is6() {
|
|
||||||
return nil, fmt.Errorf("remote address is ipv6")
|
|
||||||
}
|
|
||||||
|
|
||||||
srcIp := binary.BigEndian.Uint32(rAddr.AsSlice())
|
|
||||||
scrPort := srcAddrPort.Port()
|
|
||||||
|
|
||||||
key := bpfRedirInfo{
|
|
||||||
Sip: byteorder.HostToNetwork32(srcIp),
|
|
||||||
Sport: byteorder.HostToNetwork16(scrPort),
|
|
||||||
Dip: byteorder.HostToNetwork32(e.redirIp),
|
|
||||||
Dport: byteorder.HostToNetwork16(e.redirPort),
|
|
||||||
}
|
|
||||||
|
|
||||||
origin := bpfOriginInfo{}
|
|
||||||
|
|
||||||
err := e.originMap.Lookup(key, &origin)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := make([]byte, net.IPv4len+3)
|
|
||||||
addr[0] = socks5.AtypIPv4
|
|
||||||
|
|
||||||
binary.BigEndian.PutUint32(addr[1:1+net.IPv4len], byteorder.NetworkToHost32(origin.Ip)) // big end
|
|
||||||
binary.BigEndian.PutUint16(addr[1+net.IPv4len:3+net.IPv4len], byteorder.NetworkToHost16(origin.Port)) // big end
|
|
||||||
return addr, nil
|
|
||||||
}
|
|
@ -1,138 +0,0 @@
|
|||||||
// Code generated by bpf2go; DO NOT EDIT.
|
|
||||||
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
|
||||||
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
|
||||||
|
|
||||||
package redir
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
)
|
|
||||||
|
|
||||||
type bpfOriginInfo struct {
|
|
||||||
Ip uint32
|
|
||||||
Port uint16
|
|
||||||
Pad uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
type bpfRedirInfo struct {
|
|
||||||
Sip uint32
|
|
||||||
Dip uint32
|
|
||||||
Sport uint16
|
|
||||||
Dport uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpf returns the embedded CollectionSpec for bpf.
|
|
||||||
func loadBpf() (*ebpf.CollectionSpec, error) {
|
|
||||||
reader := bytes.NewReader(_BpfBytes)
|
|
||||||
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't load bpf: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpfObjects loads bpf and converts it into a struct.
|
|
||||||
//
|
|
||||||
// The following types are suitable as obj argument:
|
|
||||||
//
|
|
||||||
// *bpfObjects
|
|
||||||
// *bpfPrograms
|
|
||||||
// *bpfMaps
|
|
||||||
//
|
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
|
||||||
spec, err := loadBpf()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec.LoadAndAssign(obj, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfSpecs struct {
|
|
||||||
bpfProgramSpecs
|
|
||||||
bpfMapSpecs
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfProgramSpecs struct {
|
|
||||||
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
|
||||||
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfMapSpecs struct {
|
|
||||||
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
|
||||||
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfObjects contains all objects after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfObjects struct {
|
|
||||||
bpfPrograms
|
|
||||||
bpfMaps
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *bpfObjects) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
&o.bpfPrograms,
|
|
||||||
&o.bpfMaps,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMaps contains all maps after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfMaps struct {
|
|
||||||
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
|
||||||
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *bpfMaps) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
m.PairOriginalDstMap,
|
|
||||||
m.RedirParamsMap,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfPrograms struct {
|
|
||||||
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
|
||||||
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *bpfPrograms) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
p.TcRedirEgressFunc,
|
|
||||||
p.TcRedirIngressFunc,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _BpfClose(closers ...io.Closer) error {
|
|
||||||
for _, closer := range closers {
|
|
||||||
if err := closer.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do not access this directly.
|
|
||||||
//go:embed bpf_bpfeb.o
|
|
||||||
var _BpfBytes []byte
|
|
Binary file not shown.
@ -1,138 +0,0 @@
|
|||||||
// Code generated by bpf2go; DO NOT EDIT.
|
|
||||||
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
|
||||||
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
|
||||||
|
|
||||||
package redir
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
)
|
|
||||||
|
|
||||||
type bpfOriginInfo struct {
|
|
||||||
Ip uint32
|
|
||||||
Port uint16
|
|
||||||
Pad uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
type bpfRedirInfo struct {
|
|
||||||
Sip uint32
|
|
||||||
Dip uint32
|
|
||||||
Sport uint16
|
|
||||||
Dport uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpf returns the embedded CollectionSpec for bpf.
|
|
||||||
func loadBpf() (*ebpf.CollectionSpec, error) {
|
|
||||||
reader := bytes.NewReader(_BpfBytes)
|
|
||||||
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't load bpf: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpfObjects loads bpf and converts it into a struct.
|
|
||||||
//
|
|
||||||
// The following types are suitable as obj argument:
|
|
||||||
//
|
|
||||||
// *bpfObjects
|
|
||||||
// *bpfPrograms
|
|
||||||
// *bpfMaps
|
|
||||||
//
|
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
|
||||||
spec, err := loadBpf()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec.LoadAndAssign(obj, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfSpecs struct {
|
|
||||||
bpfProgramSpecs
|
|
||||||
bpfMapSpecs
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfProgramSpecs struct {
|
|
||||||
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
|
||||||
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfMapSpecs struct {
|
|
||||||
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
|
||||||
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfObjects contains all objects after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfObjects struct {
|
|
||||||
bpfPrograms
|
|
||||||
bpfMaps
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *bpfObjects) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
&o.bpfPrograms,
|
|
||||||
&o.bpfMaps,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMaps contains all maps after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfMaps struct {
|
|
||||||
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
|
||||||
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *bpfMaps) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
m.PairOriginalDstMap,
|
|
||||||
m.RedirParamsMap,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfPrograms struct {
|
|
||||||
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
|
||||||
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *bpfPrograms) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
p.TcRedirEgressFunc,
|
|
||||||
p.TcRedirIngressFunc,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _BpfClose(closers ...io.Closer) error {
|
|
||||||
for _, closer := range closers {
|
|
||||||
if err := closer.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do not access this directly.
|
|
||||||
//go:embed bpf_bpfel.o
|
|
||||||
var _BpfBytes []byte
|
|
Binary file not shown.
@ -1,119 +0,0 @@
|
|||||||
// Code generated by bpf2go; DO NOT EDIT.
|
|
||||||
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
|
||||||
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
|
||||||
|
|
||||||
package tc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
)
|
|
||||||
|
|
||||||
// loadBpf returns the embedded CollectionSpec for bpf.
|
|
||||||
func loadBpf() (*ebpf.CollectionSpec, error) {
|
|
||||||
reader := bytes.NewReader(_BpfBytes)
|
|
||||||
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't load bpf: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpfObjects loads bpf and converts it into a struct.
|
|
||||||
//
|
|
||||||
// The following types are suitable as obj argument:
|
|
||||||
//
|
|
||||||
// *bpfObjects
|
|
||||||
// *bpfPrograms
|
|
||||||
// *bpfMaps
|
|
||||||
//
|
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
|
||||||
spec, err := loadBpf()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec.LoadAndAssign(obj, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfSpecs struct {
|
|
||||||
bpfProgramSpecs
|
|
||||||
bpfMapSpecs
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfProgramSpecs struct {
|
|
||||||
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfMapSpecs struct {
|
|
||||||
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfObjects contains all objects after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfObjects struct {
|
|
||||||
bpfPrograms
|
|
||||||
bpfMaps
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *bpfObjects) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
&o.bpfPrograms,
|
|
||||||
&o.bpfMaps,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMaps contains all maps after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfMaps struct {
|
|
||||||
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *bpfMaps) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
m.TcParamsMap,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfPrograms struct {
|
|
||||||
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *bpfPrograms) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
p.TcTunFunc,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _BpfClose(closers ...io.Closer) error {
|
|
||||||
for _, closer := range closers {
|
|
||||||
if err := closer.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do not access this directly.
|
|
||||||
//go:embed bpf_bpfeb.o
|
|
||||||
var _BpfBytes []byte
|
|
Binary file not shown.
@ -1,119 +0,0 @@
|
|||||||
// Code generated by bpf2go; DO NOT EDIT.
|
|
||||||
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
|
||||||
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
|
||||||
|
|
||||||
package tc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
)
|
|
||||||
|
|
||||||
// loadBpf returns the embedded CollectionSpec for bpf.
|
|
||||||
func loadBpf() (*ebpf.CollectionSpec, error) {
|
|
||||||
reader := bytes.NewReader(_BpfBytes)
|
|
||||||
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't load bpf: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadBpfObjects loads bpf and converts it into a struct.
|
|
||||||
//
|
|
||||||
// The following types are suitable as obj argument:
|
|
||||||
//
|
|
||||||
// *bpfObjects
|
|
||||||
// *bpfPrograms
|
|
||||||
// *bpfMaps
|
|
||||||
//
|
|
||||||
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
|
||||||
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
|
||||||
spec, err := loadBpf()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return spec.LoadAndAssign(obj, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfSpecs struct {
|
|
||||||
bpfProgramSpecs
|
|
||||||
bpfMapSpecs
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfSpecs contains programs before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfProgramSpecs struct {
|
|
||||||
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed ebpf.CollectionSpec.Assign.
|
|
||||||
type bpfMapSpecs struct {
|
|
||||||
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfObjects contains all objects after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfObjects struct {
|
|
||||||
bpfPrograms
|
|
||||||
bpfMaps
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *bpfObjects) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
&o.bpfPrograms,
|
|
||||||
&o.bpfMaps,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfMaps contains all maps after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfMaps struct {
|
|
||||||
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *bpfMaps) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
m.TcParamsMap,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
|
||||||
//
|
|
||||||
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
|
||||||
type bpfPrograms struct {
|
|
||||||
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *bpfPrograms) Close() error {
|
|
||||||
return _BpfClose(
|
|
||||||
p.TcTunFunc,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func _BpfClose(closers ...io.Closer) error {
|
|
||||||
for _, closer := range closers {
|
|
||||||
if err := closer.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do not access this directly.
|
|
||||||
//go:embed bpf_bpfel.o
|
|
||||||
var _BpfBytes []byte
|
|
Binary file not shown.
@ -1,147 +0,0 @@
|
|||||||
//go:build linux
|
|
||||||
|
|
||||||
package tc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"github.com/cilium/ebpf"
|
|
||||||
"github.com/cilium/ebpf/rlimit"
|
|
||||||
"github.com/vishvananda/netlink"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/tc.c
|
|
||||||
|
|
||||||
const (
|
|
||||||
mapKey1 uint32 = 0
|
|
||||||
mapKey2 uint32 = 1
|
|
||||||
)
|
|
||||||
|
|
||||||
type EBpfTC struct {
|
|
||||||
objs io.Closer
|
|
||||||
qdisc netlink.Qdisc
|
|
||||||
filter netlink.Filter
|
|
||||||
|
|
||||||
ifName string
|
|
||||||
ifIndex int
|
|
||||||
ifMark uint32
|
|
||||||
tunIfIndex uint32
|
|
||||||
|
|
||||||
bpfPath string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEBpfTc(ifName string, ifIndex int, ifMark uint32, tunIfIndex uint32) *EBpfTC {
|
|
||||||
return &EBpfTC{
|
|
||||||
ifName: ifName,
|
|
||||||
ifIndex: ifIndex,
|
|
||||||
ifMark: ifMark,
|
|
||||||
tunIfIndex: tunIfIndex,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfTC) Start() error {
|
|
||||||
if err := rlimit.RemoveMemlock(); err != nil {
|
|
||||||
return fmt.Errorf("remove memory lock: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
|
||||||
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
|
||||||
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var objs bpfObjects
|
|
||||||
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
|
||||||
Maps: ebpf.MapOptions{
|
|
||||||
PinPath: e.bpfPath,
|
|
||||||
},
|
|
||||||
}); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("loading objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.objs = &objs
|
|
||||||
|
|
||||||
if err := objs.bpfMaps.TcParamsMap.Update(mapKey1, e.ifMark, ebpf.UpdateAny); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("storing objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := objs.bpfMaps.TcParamsMap.Update(mapKey2, e.tunIfIndex, ebpf.UpdateAny); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("storing objects: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := netlink.QdiscAttrs{
|
|
||||||
LinkIndex: e.ifIndex,
|
|
||||||
Handle: netlink.MakeHandle(0xffff, 0),
|
|
||||||
Parent: netlink.HANDLE_CLSACT,
|
|
||||||
}
|
|
||||||
|
|
||||||
qdisc := &netlink.GenericQdisc{
|
|
||||||
QdiscAttrs: attrs,
|
|
||||||
QdiscType: "clsact",
|
|
||||||
}
|
|
||||||
|
|
||||||
e.qdisc = qdisc
|
|
||||||
|
|
||||||
if err := netlink.QdiscAdd(qdisc); err != nil {
|
|
||||||
if os.IsExist(err) {
|
|
||||||
_ = netlink.QdiscDel(qdisc)
|
|
||||||
err = netlink.QdiscAdd(qdisc)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
filterAttrs := netlink.FilterAttrs{
|
|
||||||
LinkIndex: e.ifIndex,
|
|
||||||
Parent: netlink.HANDLE_MIN_EGRESS,
|
|
||||||
Handle: netlink.MakeHandle(0, 1),
|
|
||||||
Protocol: unix.ETH_P_ALL,
|
|
||||||
Priority: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
filter := &netlink.BpfFilter{
|
|
||||||
FilterAttrs: filterAttrs,
|
|
||||||
Fd: objs.bpfPrograms.TcTunFunc.FD(),
|
|
||||||
Name: "clash-tc-" + e.ifName,
|
|
||||||
DirectAction: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := netlink.FilterAdd(filter); err != nil {
|
|
||||||
e.Close()
|
|
||||||
return fmt.Errorf("cannot attach ebpf object to filter: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
e.filter = filter
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfTC) Close() {
|
|
||||||
if e.filter != nil {
|
|
||||||
_ = netlink.FilterDel(e.filter)
|
|
||||||
}
|
|
||||||
if e.qdisc != nil {
|
|
||||||
_ = netlink.QdiscDel(e.qdisc)
|
|
||||||
}
|
|
||||||
if e.objs != nil {
|
|
||||||
_ = e.objs.Close()
|
|
||||||
}
|
|
||||||
_ = os.Remove(filepath.Join(e.bpfPath, "tc_params_map"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *EBpfTC) Lookup(_ netip.AddrPort) (socks5.Addr, error) {
|
|
||||||
return nil, fmt.Errorf("not supported")
|
|
||||||
}
|
|
@ -166,7 +166,7 @@ func New(options Options) (*Pool, error) {
|
|||||||
var (
|
var (
|
||||||
hostAddr = options.IPNet.Masked().Addr()
|
hostAddr = options.IPNet.Masked().Addr()
|
||||||
gateway = hostAddr.Next()
|
gateway = hostAddr.Next()
|
||||||
first = gateway.Next().Next().Next() // default start with 198.18.0.4
|
first = gateway.Next().Next()
|
||||||
last = nnip.UnMasked(*options.IPNet)
|
last = nnip.UnMasked(*options.IPNet)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -62,16 +62,16 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, pool.Lookup("foo.com") == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
assert.True(t, pool.Gateway() == netip.AddrFrom4([4]byte{192, 168, 0, 1}))
|
||||||
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
assert.True(t, pool.Broadcast() == netip.AddrFrom4([4]byte{192, 168, 0, 15}))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
assert.True(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 4})))
|
||||||
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 6})))
|
assert.False(t, pool.Exist(netip.AddrFrom4([4]byte{192, 168, 0, 5})))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("::1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,16 +90,16 @@ func TestPool_BasicV6(t *testing.T) {
|
|||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
bar, exist := pool.LookBack(last)
|
bar, exist := pool.LookBack(last)
|
||||||
|
|
||||||
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, first == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
||||||
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
assert.True(t, pool.Lookup("foo.com") == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8803"))
|
||||||
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805"))
|
assert.True(t, last == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804"))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
assert.True(t, pool.Gateway() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8801"))
|
||||||
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
assert.True(t, pool.Broadcast() == netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8bff"))
|
||||||
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
assert.Equal(t, pool.IPNet().String(), ipnet.String())
|
||||||
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
assert.True(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8804")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8806")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("2001:4860:4860:0000:0000:0000:0000:8805")))
|
||||||
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
assert.False(t, pool.Exist(netip.MustParseAddr("127.0.0.1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -116,7 +116,7 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
for _, pool := range pools {
|
for _, pool := range pools {
|
||||||
foo := pool.Lookup("foo.com")
|
foo := pool.Lookup("foo.com")
|
||||||
bar := pool.Lookup("bar.com")
|
bar := pool.Lookup("bar.com")
|
||||||
for i := 0; i < 9; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
pool.Lookup(fmt.Sprintf("%d.com", i))
|
pool.Lookup(fmt.Sprintf("%d.com", i))
|
||||||
}
|
}
|
||||||
baz := pool.Lookup("baz.com")
|
baz := pool.Lookup("baz.com")
|
||||||
@ -198,8 +198,8 @@ func TestPool_Clone(t *testing.T) {
|
|||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
assert.True(t, first == netip.AddrFrom4([4]byte{192, 168, 0, 3}))
|
||||||
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 5}))
|
assert.True(t, last == netip.AddrFrom4([4]byte{192, 168, 0, 4}))
|
||||||
|
|
||||||
newPool, _ := New(Options{
|
newPool, _ := New(Options{
|
||||||
IPNet: &ipnet,
|
IPNet: &ipnet,
|
||||||
|
@ -3,7 +3,6 @@ package geodata
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
@ -15,7 +14,7 @@ type loader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||||
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
return l.LoadGeoSiteWithAttr("geosite.dat", list)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
||||||
@ -30,7 +29,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
||||||
}
|
}
|
||||||
|
|
||||||
domains, err := l.LoadSiteByPath(file, list)
|
domains, err := l.LoadSite(file, list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -59,7 +58,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
return l.LoadIPByPath(C.GeoipName, country)
|
return l.LoadIP("geoip.dat", country)
|
||||||
}
|
}
|
||||||
|
|
||||||
var loaders map[string]func() LoaderImplementation
|
var loaders map[string]func() LoaderImplementation
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user