Compare commits
35 Commits
Author | SHA1 | Date | |
---|---|---|---|
8c7c8f4374 | |||
65a8e8f59c | |||
5497adaba1 | |||
aaf08dadff | |||
557297ac9a | |||
77a1e3a653 | |||
27e1d6cdae | |||
91c22b16bf | |||
fc5c9b931b | |||
c231fd1466 | |||
fbb27b84d1 | |||
e0c5a85314 | |||
2fa1a5c4b9 | |||
06d75da257 | |||
09d49bac95 | |||
3360839fe3 | |||
c1285adbf8 | |||
9d2fc976e2 | |||
7f41f94fff | |||
d1f0dac302 | |||
afb3e00067 | |||
9a31ad6151 | |||
09cc6b69e3 | |||
8603ac40a1 | |||
b384449717 | |||
da7ffc0da9 | |||
5dd94c8298 | |||
412b44a981 | |||
aef4dd3fe7 | |||
6a92c6af4e | |||
e010940b61 | |||
2c9a4d276a | |||
4dfba73e5c | |||
c282d662ca | |||
b3d7594813 |
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
|
|
30
.github/workflows/codeql-analysis.yml
vendored
Normal file
30
.github/workflows/codeql-analysis.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
name: CodeQL
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master, dev]
|
||||||
|
|
||||||
|
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
|
80
.github/workflows/docker.yml
vendored
Normal file
80
.github/workflows/docker.yml
vendored
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
name: Publish Docker Image
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
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
|
53
.github/workflows/release.yml
vendored
53
.github/workflows/release.yml
vendored
@ -1,14 +1,14 @@
|
|||||||
name: Release
|
name: Release
|
||||||
on: [push]
|
on: [push]
|
||||||
jobs:
|
jobs:
|
||||||
Feature-build:
|
build:
|
||||||
if: ${{ !contains(github.event.head_commit.message, '[Skip CI]') }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Get latest go version
|
- name: Get latest go version
|
||||||
id: version
|
id: version
|
||||||
run: |
|
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')
|
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
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v2
|
||||||
with:
|
with:
|
||||||
@ -20,52 +20,27 @@ jobs:
|
|||||||
- name: Cache go module
|
- name: Cache go module
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v2
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: |
|
||||||
|
~/go/pkg/mod
|
||||||
|
~/.cache/go-build
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-go-
|
${{ runner.os }}-go-
|
||||||
# - name: Get dependencies, run test
|
|
||||||
# run: |
|
- name: Get dependencies, run test
|
||||||
# go test ./...
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
if: success()
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
env:
|
env:
|
||||||
NAME: Clash.Meta
|
NAME: clash
|
||||||
BINDIR: bin
|
BINDIR: bin
|
||||||
run: make -j releases
|
run: make -j releases
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: alpha
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1
|
|
||||||
with:
|
|
||||||
tag_name: v1.10.0
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Release
|
- name: Upload Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
if: ${{ env.GIT_BRANCH == 'Meta' && success() }}
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
with:
|
with:
|
||||||
tag: ${{ github.ref }}
|
|
||||||
tag_name: v1.10.0
|
|
||||||
files: bin/*
|
files: bin/*
|
||||||
prerelease: false
|
draft: true
|
||||||
|
|
||||||
- name: send telegram message on push
|
|
||||||
uses: appleboy/telegram-action@master
|
|
||||||
with:
|
|
||||||
to: ${{ secrets.TTELEGRAM_CHAT_ID }}
|
|
||||||
token: ${{ secrets.TELEGRAM_TOKEN }}
|
|
||||||
message: |
|
|
||||||
${{ github.actor }} created commit:
|
|
||||||
Commit message: ${{ github.event.commits[0].message }}
|
|
||||||
|
|
||||||
Repository: ${{ github.repository }}
|
|
||||||
|
|
||||||
See changes: https://github.com/${{ github.repository }}/commit/${{github.sha}}
|
|
||||||
|
18
.github/workflows/stale.yml
vendored
Normal file
18
.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
|
||||||
|
name: Mark stale issues and pull requests
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "30 1 * * *"
|
||||||
|
|
||||||
|
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
|
|
87
Makefile
87
Makefile
@ -1,6 +1,5 @@
|
|||||||
NAME=Clash.Meta
|
NAME=clash
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git rev-parse --abbrev-ref HEAD)
|
|
||||||
VERSION=$(shell git describe --tags || echo "unknown version")
|
VERSION=$(shell git describe --tags || echo "unknown version")
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -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)" \
|
||||||
@ -8,70 +7,57 @@ GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clas
|
|||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64v1 \
|
darwin-amd64 \
|
||||||
darwin-amd64v2 \
|
darwin-amd64-v3 \
|
||||||
darwin-amd64v3 \
|
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64v1 \
|
linux-386 \
|
||||||
linux-amd64v2 \
|
linux-amd64 \
|
||||||
linux-amd64v3 \
|
linux-amd64-v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
linux-arm64 \
|
linux-armv8 \
|
||||||
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-amd64v1 \
|
windows-amd64 \
|
||||||
windows-amd64v2 \
|
windows-amd64-v3 \
|
||||||
windows-amd64v3 \
|
|
||||||
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:
|
||||||
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
$(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v3:
|
darwin-amd64:
|
||||||
|
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v2:
|
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v3:
|
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-amd64v2:
|
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
linux-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(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)-$@
|
||||||
|
|
||||||
@ -81,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-armv8:
|
||||||
|
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)-$@
|
||||||
|
|
||||||
@ -99,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,15 +103,12 @@ freebsd-arm64:
|
|||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v3:
|
windows-amd64:
|
||||||
|
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v2:
|
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
|
||||||
|
|
||||||
windows-amd64v1:
|
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(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,11 +129,12 @@ all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
|||||||
|
|
||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
vet:
|
|
||||||
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 $(BINDIR)/*
|
280
README.md
280
README.md
@ -1,20 +1,23 @@
|
|||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
<img src="Meta.png" alt="Meta Kennel" width="200">
|
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
||||||
<br>Meta Kernel<br>
|
<br>Clash<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h3 align="center">Another Clash Kernel.</h3>
|
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||||
|
</a>
|
||||||
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
<a href="https://github.com/Dreamacro/clash/releases">
|
||||||
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
|
||||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@ -29,267 +32,26 @@
|
|||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
|
## Premium Features
|
||||||
|
|
||||||
|
- TUN mode on macOS, Linux and Windows. [Doc](https://github.com/Dreamacro/clash/wiki/premium-core-features#tun-device)
|
||||||
|
- Match your tunnel by [Script](https://github.com/Dreamacro/clash/wiki/premium-core-features#script)
|
||||||
|
- [Rule Provider](https://github.com/Dreamacro/clash/wiki/premium-core-features#rule-providers)
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
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
|
## Premium Release
|
||||||
|
[Release](https://github.com/Dreamacro/clash/releases/tag/premium)
|
||||||
### DNS configuration
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
|
||||||
|
|
||||||
Restore `Redir remote resolution`.
|
|
||||||
|
|
||||||
Support resolve ip with a `Proxy Tunnel`.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxy-groups:
|
|
||||||
|
|
||||||
- name: DNS
|
|
||||||
type: url-test
|
|
||||||
use:
|
|
||||||
- HK
|
|
||||||
url: http://cp.cloudflare.com
|
|
||||||
interval: 180
|
|
||||||
lazy: true
|
|
||||||
```
|
|
||||||
```yaml
|
|
||||||
dns:
|
|
||||||
enable: true
|
|
||||||
use-hosts: true
|
|
||||||
ipv6: false
|
|
||||||
enhanced-mode: redir-host
|
|
||||||
fake-ip-range: 198.18.0.1/16
|
|
||||||
listen: 127.0.0.1:6868
|
|
||||||
default-nameserver:
|
|
||||||
- 119.29.29.29
|
|
||||||
- 114.114.114.114
|
|
||||||
nameserver:
|
|
||||||
- https://doh.pub/dns-query
|
|
||||||
- tls://223.5.5.5:853
|
|
||||||
fallback:
|
|
||||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
|
||||||
- 'tls://8.8.4.4:853#DNS'
|
|
||||||
fallback-filter:
|
|
||||||
geoip: false
|
|
||||||
geosite:
|
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
|
||||||
domain:
|
|
||||||
- +.example.com
|
|
||||||
ipcidr:
|
|
||||||
- 0.0.0.0/32
|
|
||||||
```
|
|
||||||
|
|
||||||
### TUN configuration
|
|
||||||
|
|
||||||
Supports macOS, Linux and Windows.
|
|
||||||
|
|
||||||
Built-in [Wintun](https://www.wintun.net) driver.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# Enable the TUN listener
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: gvisor # only gvisor
|
|
||||||
dns-hijack:
|
|
||||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
|
||||||
auto-route: true # auto set global route
|
|
||||||
```
|
|
||||||
### Rules configuration
|
|
||||||
- Support rule `GEOSITE`.
|
|
||||||
- Support rule-providers `RULE-SET`.
|
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
|
||||||
- Support `network` condition for all rules.
|
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
|
||||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
|
||||||
```yaml
|
|
||||||
rules:
|
|
||||||
|
|
||||||
# network(tcp/udp) condition for all rules
|
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
|
||||||
|
|
||||||
# rule GEOSITE
|
|
||||||
- GEOSITE,category-ads-all,REJECT
|
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
|
||||||
- GEOSITE,apple@cn,DIRECT
|
|
||||||
- GEOSITE,apple-cn,DIRECT
|
|
||||||
- GEOSITE,microsoft@cn,DIRECT
|
|
||||||
- GEOSITE,facebook,PROXY
|
|
||||||
- GEOSITE,youtube,PROXY
|
|
||||||
- GEOSITE,geolocation-cn,DIRECT
|
|
||||||
- GEOSITE,geolocation-!cn,PROXY
|
|
||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
|
||||||
- GEOIP,private,DIRECT,no-resolve
|
|
||||||
- GEOIP,cn,DIRECT
|
|
||||||
|
|
||||||
- MATCH,PROXY
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### Proxies configuration
|
|
||||||
|
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
|
||||||
|
|
||||||
Support `Policy Group Filter`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
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
|
|
||||||
proxies:
|
|
||||||
- name: "vless"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
servername: example.com # AKA SNI
|
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
- name: "vless-ws"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: ws
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
ws-opts:
|
|
||||||
path: /path
|
|
||||||
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
|
||||||
|
|
||||||
- name: "vless-grpc"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: grpc
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
grpc-opts:
|
|
||||||
grpc-service-name: grpcname
|
|
||||||
```
|
|
||||||
|
|
||||||
### IPTABLES configuration
|
|
||||||
Work on Linux OS who's supported `iptables`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# Enable the TPROXY listener
|
|
||||||
tproxy-port: 9898
|
|
||||||
|
|
||||||
iptables:
|
|
||||||
enable: true # default is false
|
|
||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
### General installation guide for Linux
|
|
||||||
+ Create user given name `clash-meta`
|
|
||||||
|
|
||||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
|
||||||
|
|
||||||
+ 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]
|
|
||||||
Description=Clash-Meta Daemon, Another Clash Kernel.
|
|
||||||
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=clash-meta
|
|
||||||
Group=clash-meta
|
|
||||||
LimitNPROC=500
|
|
||||||
LimitNOFILE=1000000
|
|
||||||
CapabilityBoundingSet=cap_net_admin
|
|
||||||
AmbientCapabilities=cap_net_admin
|
|
||||||
Restart=always
|
|
||||||
ExecStartPre=/usr/bin/sleep 1s
|
|
||||||
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
```
|
|
||||||
Launch clashd on system startup with:
|
|
||||||
```shell
|
|
||||||
$ systemctl enable Clash-Meta
|
|
||||||
```
|
|
||||||
Launch clashd immediately with:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ systemctl start Clash-Meta
|
|
||||||
```
|
|
||||||
|
|
||||||
### Display Process name
|
|
||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
|
||||||
|
|
||||||
To display process name in GUI please use [Dashboard For Meta](https://github.com/Clash-Mini/Dashboard).
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## 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
|
||||||
|
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
@ -17,8 +16,6 @@ import (
|
|||||||
"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
|
history *queue.Queue
|
||||||
@ -40,11 +37,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...)
|
||||||
wasCancel := false
|
p.alive.Store(err == nil)
|
||||||
if err != nil {
|
|
||||||
wasCancel = strings.Contains(err.Error(), "operation was canceled")
|
|
||||||
}
|
|
||||||
p.alive.Store(err == nil || wasCancel)
|
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,8 +114,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
|
||||||
@ -159,19 +150,11 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
defer client.CloseIdleConnections()
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if unifiedDelay {
|
|
||||||
start = time.Now()
|
|
||||||
resp, err = client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
@ -201,10 +184,9 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
addr = C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
Host: u.Hostname(),
|
||||||
Host: u.Hostname(),
|
DstIP: nil,
|
||||||
DstIP: nil,
|
DstPort: port,
|
||||||
DstPort: port,
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -20,26 +20,3 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
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 ip, port, err := parseAddr(dst); err == nil {
|
|
||||||
metadata.DstPort = port
|
|
||||||
if host == "" {
|
|
||||||
metadata.DstIP = ip
|
|
||||||
if ip.To4() == nil {
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
} else {
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
|
||||||
|
@ -11,9 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
AddrType: int(target[0]),
|
|
||||||
}
|
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
@ -44,21 +42,13 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
host = strings.TrimRight(host, ".")
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
AddrType: C.AtypDomainName,
|
Host: host,
|
||||||
Host: host,
|
DstIP: nil,
|
||||||
DstIP: nil,
|
DstPort: port,
|
||||||
DstPort: port,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
if ip != nil {
|
|
||||||
switch {
|
|
||||||
case ip.To4() == nil:
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
default:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -14,7 +14,6 @@ type Direct struct {
|
|||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -25,7 +24,6 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.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
|
||||||
@ -46,23 +44,3 @@ func NewDirect() *Direct {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCompatible() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "COMPATIBLE",
|
|
||||||
tp: C.Compatible,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPass() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "Pass",
|
|
||||||
tp: C.Pass,
|
|
||||||
udp: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -10,11 +10,10 @@ import (
|
|||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
||||||
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/Dreamacro/go-shadowsocks2/core"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
|
@ -8,12 +8,11 @@ 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 {
|
||||||
@ -92,6 +91,12 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
|
// SSR protocol compatibility
|
||||||
|
// https://github.com/Dreamacro/clash/pull/2056
|
||||||
|
if option.Cipher == "none" {
|
||||||
|
option.Cipher = "dummy"
|
||||||
|
}
|
||||||
|
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
cipher := option.Cipher
|
||||||
password := option.Password
|
password := option.Password
|
||||||
@ -103,13 +108,14 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
ivSize int
|
ivSize int
|
||||||
key []byte
|
key []byte
|
||||||
)
|
)
|
||||||
|
|
||||||
if option.Cipher == "dummy" {
|
if option.Cipher == "dummy" {
|
||||||
ivSize = 0
|
ivSize = 0
|
||||||
key = core.Kdf(option.Password, 16)
|
key = core.Kdf(option.Password, 16)
|
||||||
} else {
|
} else {
|
||||||
ciph, ok := coreCiph.(*core.StreamCipher)
|
ciph, ok := coreCiph.(*core.StreamCipher)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("%s is not dummy or a supported stream cipher in ssr", cipher)
|
return nil, fmt.Errorf("%s is not none or a supported stream cipher in ssr", cipher)
|
||||||
}
|
}
|
||||||
ivSize = ciph.IVSize()
|
ivSize = ciph.IVSize()
|
||||||
key = ciph.Key
|
key = ciph.Key
|
||||||
|
@ -12,7 +12,6 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
@ -41,8 +40,6 @@ type TrojanOption struct {
|
|||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
||||||
@ -85,11 +82,6 @@ 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)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 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
|
||||||
}
|
}
|
||||||
@ -103,12 +95,6 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = t.instance.PresetXTLSConn(c)
|
|
||||||
if err != nil {
|
|
||||||
c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
c.Close()
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -174,17 +160,6 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ALPN: option.ALPN,
|
ALPN: option.ALPN,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
|
||||||
option.Flow = option.Flow[:16]
|
|
||||||
switch option.Flow {
|
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
|
||||||
tOption.Flow = option.Flow
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
@ -221,12 +196,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
|
||||||
} else {
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
t.gunTLSConfig = tlsConfig
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
|
@ -2,11 +2,8 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/tls"
|
|
||||||
xtls "github.com/xtls/go"
|
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
@ -14,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)
|
||||||
@ -27,26 +18,13 @@ 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)
|
addrType := metadata.AddrType()
|
||||||
|
aType := uint8(addrType)
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch metadata.AddrType {
|
switch addrType {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
len := uint8(len(metadata.Host))
|
len := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
@ -67,7 +45,7 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveProxyServerHost(host)
|
ip, err := resolver.ResolveIP(host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -1,446 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// max packet length
|
|
||||||
maxLength = 1024 << 3
|
|
||||||
)
|
|
||||||
|
|
||||||
type Vless struct {
|
|
||||||
*Base
|
|
||||||
client *vless.Client
|
|
||||||
option *VlessOption
|
|
||||||
|
|
||||||
// for gun mux
|
|
||||||
gunTLSConfig *tls.Config
|
|
||||||
gunConfig *gun.Config
|
|
||||||
transport *http2.Transport
|
|
||||||
}
|
|
||||||
|
|
||||||
type VlessOption struct {
|
|
||||||
BasicOption
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Server string `proxy:"server"`
|
|
||||||
Port int `proxy:"port"`
|
|
||||||
UUID string `proxy:"uuid"`
|
|
||||||
Flow string `proxy:"flow,omitempty"`
|
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
|
||||||
Network string `proxy:"network,omitempty"`
|
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
|
||||||
switch v.option.Network {
|
|
||||||
case "ws":
|
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
|
||||||
Host: host,
|
|
||||||
Port: port,
|
|
||||||
Path: v.option.WSOpts.Path,
|
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
|
||||||
header.Add(key, value)
|
|
||||||
}
|
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
|
||||||
|
|
||||||
wsOpts.TLS = true
|
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
|
||||||
MinVersion: tls.VersionTLS12,
|
|
||||||
ServerName: host,
|
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
|
||||||
if v.option.ServerName != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = host
|
|
||||||
}
|
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
|
||||||
case "http":
|
|
||||||
// readability first, so just copy default TLS logic
|
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
|
||||||
httpOpts := &vmess.HTTPConfig{
|
|
||||||
Host: host,
|
|
||||||
Method: v.option.HTTPOpts.Method,
|
|
||||||
Path: v.option.HTTPOpts.Path,
|
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
|
||||||
}
|
|
||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
|
||||||
case "h2":
|
|
||||||
c, err = v.streamTLSOrXTLSConn(c, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
h2Opts := &vmess.H2Config{
|
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
|
||||||
Path: v.option.HTTP2Opts.Path,
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
|
||||||
case "grpc":
|
|
||||||
if v.isXTLSEnabled() {
|
|
||||||
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
} else {
|
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// default tcp network
|
|
||||||
// handle TLS And XTLS
|
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
|
||||||
|
|
||||||
if v.isXTLSEnabled() {
|
|
||||||
xtlsOpts := vless.XTLSConfig{
|
|
||||||
Host: host,
|
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
|
||||||
}
|
|
||||||
|
|
||||||
if isH2 {
|
|
||||||
xtlsOpts.NextProtos = []string{"h2"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
|
||||||
xtlsOpts.Host = v.option.ServerName
|
|
||||||
}
|
|
||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
|
||||||
|
|
||||||
} else if v.option.TLS {
|
|
||||||
tlsOpts := vmess.TLSConfig{
|
|
||||||
Host: host,
|
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
|
||||||
}
|
|
||||||
|
|
||||||
if isH2 {
|
|
||||||
tlsOpts.NextProtos = []string{"h2"}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
|
||||||
tlsOpts.Host = v.option.ServerName
|
|
||||||
}
|
|
||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
|
||||||
}
|
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) isXTLSEnabled() bool {
|
|
||||||
return v.client.Addons != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
|
||||||
// gun transport
|
|
||||||
if v.transport != nil && len(opts) == 0 {
|
|
||||||
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
return NewConn(c, v), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
// vless use stream-oriented udp with a special address, so we 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 c net.Conn
|
|
||||||
// gun transport
|
|
||||||
if v.transport != nil && len(opts) == 0 {
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
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 {
|
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|
||||||
var addrType byte
|
|
||||||
var addr []byte
|
|
||||||
switch metadata.AddrType {
|
|
||||||
case C.AtypIPv4:
|
|
||||||
addrType = byte(vless.AtypIPv4)
|
|
||||||
addr = make([]byte, net.IPv4len)
|
|
||||||
copy(addr[:], metadata.DstIP.To4())
|
|
||||||
case C.AtypIPv6:
|
|
||||||
addrType = byte(vless.AtypIPv6)
|
|
||||||
addr = make([]byte, net.IPv6len)
|
|
||||||
copy(addr[:], metadata.DstIP.To16())
|
|
||||||
case C.AtypDomainName:
|
|
||||||
addrType = byte(vless.AtypDomainName)
|
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
|
||||||
addr[0] = byte(len(metadata.Host))
|
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
|
||||||
}
|
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
|
||||||
return &vless.DstAddr{
|
|
||||||
UDP: metadata.NetWork == C.UDP,
|
|
||||||
AddrType: addrType,
|
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type vlessPacketConn struct {
|
|
||||||
net.Conn
|
|
||||||
rAddr net.Addr
|
|
||||||
remain int
|
|
||||||
mux sync.Mutex
|
|
||||||
cache [2]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) writePacket(payload []byte) (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)
|
|
||||||
if total == 0 {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if total <= maxLength {
|
|
||||||
return c.writePacket(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := 0
|
|
||||||
|
|
||||||
for offset < total {
|
|
||||||
cursor := offset + maxLength
|
|
||||||
if cursor > total {
|
|
||||||
cursor = total
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.writePacket(b[offset:cursor])
|
|
||||||
if err != nil {
|
|
||||||
return offset + n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = cursor
|
|
||||||
if offset == total {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
c.mux.Lock()
|
|
||||||
defer c.mux.Unlock()
|
|
||||||
|
|
||||||
if c.remain > 0 {
|
|
||||||
length := len(b)
|
|
||||||
if c.remain < length {
|
|
||||||
length = c.remain
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
|
||||||
if err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain -= n
|
|
||||||
return n, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := c.Conn.Read(b[:2]); err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
|
||||||
if total == 0 {
|
|
||||||
return 0, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
length := len(b)
|
|
||||||
if length > total {
|
|
||||||
length = total
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
|
||||||
return 0, c.rAddr, errors.New("read packet error")
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain = total - length
|
|
||||||
|
|
||||||
return length, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
|
||||||
var addons *vless.Addons
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
|
||||||
option.Flow = option.Flow[:16]
|
|
||||||
switch option.Flow {
|
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
|
||||||
addons = &vless.Addons{
|
|
||||||
Flow: option.Flow,
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
client, err := vless.NewClient(option.UUID, addons, option.FlowShow)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
v := &Vless{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
|
||||||
tp: C.Vless,
|
|
||||||
udp: option.UDP,
|
|
||||||
iface: option.Interface,
|
|
||||||
},
|
|
||||||
client: client,
|
|
||||||
option: &option,
|
|
||||||
}
|
|
||||||
|
|
||||||
switch option.Network {
|
|
||||||
case "h2":
|
|
||||||
if len(option.HTTP2Opts.Host) == 0 {
|
|
||||||
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
|
||||||
}
|
|
||||||
case "grpc":
|
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
|
||||||
Host: v.option.ServerName,
|
|
||||||
}
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
|
||||||
ServerName: v.option.ServerName,
|
|
||||||
}
|
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
|
||||||
tlsConfig.ServerName = host
|
|
||||||
gunConfig.Host = host
|
|
||||||
}
|
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
|
||||||
v.gunConfig = gunConfig
|
|
||||||
if v.isXTLSEnabled() {
|
|
||||||
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
|
||||||
} else {
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return v, nil
|
|
||||||
}
|
|
@ -14,6 +14,7 @@ import (
|
|||||||
"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"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"golang.org/x/net/http2"
|
||||||
@ -47,10 +48,6 @@ type VmessOption struct {
|
|||||||
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"`
|
||||||
|
|
||||||
// TODO: compatible with VMESS WS older version configurations
|
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -80,13 +77,6 @@ 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 := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
@ -338,16 +328,16 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType() {
|
||||||
case C.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
addrType = byte(vmess.AtypIPv4)
|
addrType = byte(vmess.AtypIPv4)
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.To4())
|
copy(addr[:], metadata.DstIP.To4())
|
||||||
case C.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
addrType = byte(vmess.AtypIPv6)
|
addrType = byte(vmess.AtypIPv6)
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.To16())
|
copy(addr[:], metadata.DstIP.To16())
|
||||||
case C.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
addrType = byte(vmess.AtypDomainName)
|
addrType = byte(vmess.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))
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -13,7 +11,7 @@ const (
|
|||||||
defaultGetProxiesDuration = time.Second * 5
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
)
|
)
|
||||||
|
|
||||||
func getProvidersProxies(providers []provider.ProxyProvider, touch bool, filter string) []C.Proxy {
|
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for _, provider := range providers {
|
for _, provider := range providers {
|
||||||
if touch {
|
if touch {
|
||||||
@ -22,34 +20,5 @@ func getProvidersProxies(providers []provider.ProxyProvider, touch bool, filter
|
|||||||
proxies = append(proxies, provider.Proxies()...)
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return proxies
|
||||||
var filterReg *regexp2.Regexp = nil
|
|
||||||
var matchedProxies []C.Proxy
|
|
||||||
if len(filter) > 0 {
|
|
||||||
//filterReg = regexp.MustCompile(filter)
|
|
||||||
filterReg = regexp2.MustCompile(filter, 0)
|
|
||||||
for _, p := range proxies {
|
|
||||||
if p.Type() < 8 {
|
|
||||||
matchedProxies = append(matchedProxies, p)
|
|
||||||
}
|
|
||||||
|
|
||||||
//if filterReg.MatchString(p.Name()) {
|
|
||||||
if mat, _ := filterReg.FindStringMatch(p.Name()); mat != nil {
|
|
||||||
matchedProxies = append(matchedProxies, p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(matchedProxies) > 0 {
|
|
||||||
return matchedProxies
|
|
||||||
} else {
|
|
||||||
return append([]C.Proxy{}, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
} else {
|
|
||||||
return proxies
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -3,9 +3,6 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
@ -16,12 +13,9 @@ import (
|
|||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
filter string
|
single *singledo.Single
|
||||||
single *singledo.Single
|
providers []provider.ProxyProvider
|
||||||
providers []provider.ProxyProvider
|
|
||||||
failedTimes *atomic.Int32
|
|
||||||
failedTime *atomic.Int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -35,12 +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.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
f.onDialFailed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,41 +39,10 @@ func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(f)
|
pc.AppendToChains(f)
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
f.onDialFailed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) onDialFailed() {
|
|
||||||
if f.failedTime.Load() == -1 {
|
|
||||||
log.Warnln("%s first failed", f.Name())
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
f.failedTime.Store(now)
|
|
||||||
f.failedTimes.Store(1)
|
|
||||||
} else {
|
|
||||||
if f.failedTime.Load()-time.Now().UnixMilli() > 5*time.Second.Milliseconds() {
|
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
failedCount := f.failedTimes.Inc()
|
|
||||||
log.Warnln("%s failed count: %d", f.Name(), failedCount)
|
|
||||||
if failedCount >= 5 {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", f.Name())
|
|
||||||
for _, proxyProvider := range f.providers {
|
|
||||||
go proxyProvider.HealthCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (f *Fallback) SupportUDP() bool {
|
func (f *Fallback) SupportUDP() bool {
|
||||||
if f.disableUDP {
|
if f.disableUDP {
|
||||||
@ -97,7 +55,7 @@ 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.proxies(false) {
|
for _, proxy := range f.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
@ -116,7 +74,7 @@ func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
|
|
||||||
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := f.single.Do(func() (any, error) {
|
elm, _, _ := f.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(f.providers, touch, f.filter), nil
|
return getProvidersProxies(f.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
return elm.([]C.Proxy)
|
||||||
@ -141,11 +99,8 @@ func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
Interface: option.Interface,
|
Interface: option.Interface,
|
||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
providers: providers,
|
providers: providers,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
filter: option.Filter,
|
|
||||||
failedTimes: atomic.NewInt32(-1),
|
|
||||||
failedTime: atomic.NewInt64(-1),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,6 @@ type LoadBalance struct {
|
|||||||
*outbound.Base
|
*outbound.Base
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single
|
single *singledo.Single
|
||||||
filter string
|
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
}
|
}
|
||||||
@ -31,10 +30,8 @@ type LoadBalance struct {
|
|||||||
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 elm, ok := config["strategy"]; ok {
|
if strategy, ok := config["strategy"].(string); ok {
|
||||||
if strategy, ok := elm.(string); ok {
|
return strategy
|
||||||
return strategy
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return "consistent-hashing"
|
return "consistent-hashing"
|
||||||
}
|
}
|
||||||
@ -130,6 +127,13 @@ 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]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -142,7 +146,7 @@ func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
|
|
||||||
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := lb.single.Do(func() (any, error) {
|
elm, _, _ := lb.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(lb.providers, touch, lb.filter), nil
|
return getProvidersProxies(lb.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
return elm.([]C.Proxy)
|
||||||
@ -150,7 +154,7 @@ func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range lb.proxies(false) {
|
for _, proxy := range lb.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
@ -181,6 +185,5 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
providers: providers,
|
providers: providers,
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
filter: option.Filter,
|
|
||||||
}, 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) {
|
||||||
@ -96,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
|
||||||
|
@ -16,14 +16,13 @@ type Relay struct {
|
|||||||
*outbound.Base
|
*outbound.Base
|
||||||
single *singledo.Single
|
single *singledo.Single
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
filter string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
var proxies []C.Proxy
|
var proxies []C.Proxy
|
||||||
for _, proxy := range r.proxies(metadata, true) {
|
for _, proxy := range r.proxies(metadata, true) {
|
||||||
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
if proxy.Type() != C.Direct {
|
||||||
proxies = append(proxies, proxy)
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -69,7 +68,7 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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.rawProxies(false) {
|
for _, proxy := range r.rawProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
@ -81,7 +80,7 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := r.single.Do(func() (any, error) {
|
elm, _, _ := r.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(r.providers, touch, r.filter), nil
|
return getProvidersProxies(r.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
return elm.([]C.Proxy)
|
||||||
@ -111,6 +110,5 @@ func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Re
|
|||||||
}),
|
}),
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
providers: providers,
|
providers: providers,
|
||||||
filter: option.Filter,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,6 @@ type Selector struct {
|
|||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single
|
single *singledo.Single
|
||||||
selected string
|
selected string
|
||||||
filter string
|
|
||||||
providers []provider.ProxyProvider
|
providers []provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,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 getProvidersProxies(s.providers, false, s.filter) {
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,7 +66,7 @@ func (s *Selector) Now() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
func (s *Selector) Set(name string) error {
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false, s.filter) {
|
for _, proxy := range getProvidersProxies(s.providers, false) {
|
||||||
if proxy.Name() == name {
|
if proxy.Name() == name {
|
||||||
s.selected = name
|
s.selected = name
|
||||||
s.single.Reset()
|
s.single.Reset()
|
||||||
@ -79,13 +78,13 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
elm, _, _ := s.single.Do(func() (any, error) {
|
elm, _, _ := s.single.Do(func() (any, error) {
|
||||||
proxies := getProvidersProxies(s.providers, touch, s.filter)
|
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, nil
|
return proxy, nil
|
||||||
@ -99,6 +98,7 @@ func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
Base: outbound.NewBase(outbound.BaseOption{
|
||||||
Name: option.Name,
|
Name: option.Name,
|
||||||
@ -108,8 +108,7 @@ func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider)
|
|||||||
}),
|
}),
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
providers: providers,
|
providers: providers,
|
||||||
selected: "COMPATIBLE",
|
selected: selected,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
filter: option.Filter,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,8 +3,6 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"go.uber.org/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
@ -24,15 +22,12 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
filter string
|
single *singledo.Single
|
||||||
single *singledo.Single
|
fastSingle *singledo.Single
|
||||||
fastSingle *singledo.Single
|
providers []provider.ProxyProvider
|
||||||
providers []provider.ProxyProvider
|
|
||||||
failedTimes *atomic.Int32
|
|
||||||
failedTime *atomic.Int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
@ -44,10 +39,6 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
u.onDialFailed()
|
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -57,22 +48,18 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
u.onDialFailed()
|
|
||||||
}
|
}
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
||||||
elm, _, _ := u.single.Do(func() (any, error) {
|
elm, _, _ := u.single.Do(func() (any, error) {
|
||||||
return getProvidersProxies(u.providers, touch, u.filter), nil
|
return getProvidersProxies(u.providers, touch), nil
|
||||||
})
|
})
|
||||||
|
|
||||||
return elm.([]C.Proxy)
|
return elm.([]C.Proxy)
|
||||||
@ -123,7 +110,7 @@ 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.proxies(false) {
|
for _, proxy := range u.proxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
@ -134,40 +121,12 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) onDialFailed() {
|
|
||||||
if u.failedTime.Load() == -1 {
|
|
||||||
log.Warnln("%s first failed", u.Name())
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
u.failedTime.Store(now)
|
|
||||||
u.failedTimes.Store(1)
|
|
||||||
} else {
|
|
||||||
if u.failedTime.Load()-time.Now().UnixMilli() > 5*1000 {
|
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
failedCount := u.failedTimes.Inc()
|
|
||||||
log.Warnln("%s failed count: %d", u.Name(), failedCount)
|
|
||||||
if failedCount >= 5 {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", u.Name())
|
|
||||||
for _, proxyProvider := range u.providers {
|
|
||||||
go proxyProvider.HealthCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
opts := []urlTestOption{}
|
opts := []urlTestOption{}
|
||||||
|
|
||||||
// tolerance
|
// tolerance
|
||||||
if elm, ok := config["tolerance"]; ok {
|
if tolerance, ok := config["tolerance"].(int); ok {
|
||||||
if tolerance, ok := elm.(int); ok {
|
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
||||||
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
@ -181,13 +140,10 @@ func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, o
|
|||||||
Interface: option.Interface,
|
Interface: option.Interface,
|
||||||
RoutingMark: option.RoutingMark,
|
RoutingMark: option.RoutingMark,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle(defaultGetProxiesDuration),
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
fastSingle: singledo.NewSingle(time.Second * 10),
|
fastSingle: singledo.NewSingle(time.Second * 10),
|
||||||
providers: providers,
|
providers: providers,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
filter: option.Filter,
|
|
||||||
failedTimes: atomic.NewInt32(-1),
|
|
||||||
failedTime: atomic.NewInt64(-1),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
@ -18,27 +18,24 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
if ip == nil {
|
if ip == nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypDomainName,
|
Host: host,
|
||||||
Host: host,
|
DstIP: nil,
|
||||||
DstIP: nil,
|
DstPort: port,
|
||||||
DstPort: port,
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
} else if ip4 := ip.To4(); ip4 != nil {
|
} else if ip4 := ip.To4(); ip4 != nil {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
Host: "",
|
||||||
Host: "",
|
DstIP: ip4,
|
||||||
DstIP: ip4,
|
DstPort: port,
|
||||||
DstPort: port,
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv6,
|
Host: "",
|
||||||
Host: "",
|
DstIP: ip,
|
||||||
DstIP: ip,
|
DstPort: port,
|
||||||
DstPort: port,
|
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -60,13 +60,6 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
|
||||||
vlessOption := &outbound.VlessOption{}
|
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewVless(*vlessOption)
|
|
||||||
case "snell":
|
case "snell":
|
||||||
snellOption := &outbound.SnellOption{}
|
snellOption := &outbound.SnellOption{}
|
||||||
err = decoder.Decode(mapping, snellOption)
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
@ -31,13 +31,7 @@ type HealthCheck struct {
|
|||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go func() {
|
go hc.check()
|
||||||
t := time.NewTicker(30 * time.Second)
|
|
||||||
<-t.C
|
|
||||||
t.Stop()
|
|
||||||
hc.check()
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
|
@ -4,7 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/dlclark/regexp2"
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -12,7 +12,7 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -40,8 +40,7 @@ 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(),
|
||||||
//TODO maybe error because year value overflow
|
"updatedAt": pp.updatedAt,
|
||||||
"updatedAt": pp.updatedAt,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,10 +67,6 @@ func (pp *proxySetProvider) Initial() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pp.onUpdate(elm)
|
pp.onUpdate(elm)
|
||||||
if pp.healthCheck.auto() {
|
|
||||||
go pp.healthCheck.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,12 +97,15 @@ func stopProxyProvider(pd *ProxySetProvider) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
//filterReg, err := regexp.Compile(filter)
|
filterReg, err := regexp.Compile(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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
pd := &proxySetProvider{
|
pd := &proxySetProvider{
|
||||||
proxies: []C.Proxy{},
|
proxies: []C.Proxy{},
|
||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
@ -131,9 +129,7 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
name, ok := mapping["name"]
|
if name, ok := mapping["name"].(string); ok && len(filter) > 0 && !filterReg.MatchString(name) {
|
||||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
|
||||||
if ok && len(filter) > 0 && mat == nil {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
@ -194,10 +190,6 @@ func (cp *compatibleProvider) Update() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Initial() error {
|
func (cp *compatibleProvider) Initial() error {
|
||||||
if cp.healthCheck.auto() {
|
|
||||||
go cp.healthCheck.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -227,6 +219,10 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
return nil, errors.New("provider need one proxy at least")
|
return nil, errors.New("provider need one proxy at least")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
pd := &compatibleProvider{
|
pd := &compatibleProvider{
|
||||||
name: name,
|
name: name,
|
||||||
proxies: proxies,
|
proxies: proxies,
|
||||||
|
@ -2,8 +2,6 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -11,7 +9,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
netHttp "github.com/Dreamacro/clash/common/net"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -58,8 +56,6 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
||||||
req.Header.Set("user-agent", netHttp.UA)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -78,21 +74,14 @@ func (h *HTTPVehicle) Read() ([]byte, error) {
|
|||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
conn := inner.HandleTcp(address, uri.Hostname())
|
return dialer.DialContext(ctx, network, address)
|
||||||
return conn, nil
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
client := http.Client{Transport: transport}
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
|
return nil, err
|
||||||
return dialer.DialContext(ctx, network, address)
|
|
||||||
}
|
|
||||||
resp, err = client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
9
common/cache/lrucache.go
vendored
9
common/cache/lrucache.go
vendored
@ -216,15 +216,6 @@ func (c *LruCache) deleteElement(le *list.Element) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *LruCache) Clear() error {
|
|
||||||
c.mu.Lock()
|
|
||||||
|
|
||||||
c.cache = make(map[any]*list.Element)
|
|
||||||
|
|
||||||
c.mu.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
key any
|
key any
|
||||||
value any
|
value any
|
||||||
|
@ -1,36 +0,0 @@
|
|||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os/exec"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ExecCmd(cmdStr string) (string, error) {
|
|
||||||
args := splitArgs(cmdStr)
|
|
||||||
|
|
||||||
var cmd *exec.Cmd
|
|
||||||
if len(args) == 1 {
|
|
||||||
cmd = exec.Command(args[0])
|
|
||||||
} else {
|
|
||||||
cmd = exec.Command(args[0], args[1:]...)
|
|
||||||
|
|
||||||
}
|
|
||||||
prepareBackgroundCommand(cmd)
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
|
||||||
}
|
|
||||||
return string(out), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitArgs(cmd string) []string {
|
|
||||||
args := strings.Split(cmd, " ")
|
|
||||||
|
|
||||||
// use in pipeline
|
|
||||||
if len(args) > 2 && strings.ContainsAny(cmd, "|") {
|
|
||||||
suffix := strings.Join(args[2:], " ")
|
|
||||||
args = append(args[:2], suffix)
|
|
||||||
}
|
|
||||||
return args
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
//go:build !windows
|
|
||||||
|
|
||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os/exec"
|
|
||||||
)
|
|
||||||
|
|
||||||
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
|
||||||
|
|
||||||
}
|
|
@ -1,40 +0,0 @@
|
|||||||
package cmd
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestSplitArgs(t *testing.T) {
|
|
||||||
args := splitArgs("ls")
|
|
||||||
args1 := splitArgs("ls -la")
|
|
||||||
args2 := splitArgs("bash -c ls")
|
|
||||||
args3 := splitArgs("bash -c ls -lahF | grep 'cmd'")
|
|
||||||
|
|
||||||
assert.Equal(t, 1, len(args))
|
|
||||||
assert.Equal(t, 2, len(args1))
|
|
||||||
assert.Equal(t, 3, len(args2))
|
|
||||||
assert.Equal(t, 3, len(args3))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecCmd(t *testing.T) {
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
_, err := ExecCmd("dir")
|
|
||||||
assert.Nil(t, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := ExecCmd("ls")
|
|
||||||
_, err1 := ExecCmd("ls -la")
|
|
||||||
_, err2 := ExecCmd("bash -c ls")
|
|
||||||
_, err3 := ExecCmd("bash -c ls -la")
|
|
||||||
_, err4 := ExecCmd("bash -c ls -la | grep 'cmd'")
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Nil(t, err1)
|
|
||||||
assert.Nil(t, err2)
|
|
||||||
assert.Nil(t, err3)
|
|
||||||
assert.Nil(t, err4)
|
|
||||||
}
|
|
@ -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,5 +0,0 @@
|
|||||||
package net
|
|
||||||
|
|
||||||
const (
|
|
||||||
UA = "Clash"
|
|
||||||
)
|
|
24
common/net/relay.go
Normal file
24
common/net/relay.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Relay copies between left and right bidirectionally.
|
||||||
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
|
ch := make(chan error)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
|
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
|
||||||
|
leftConn.SetReadDeadline(time.Now())
|
||||||
|
ch <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
|
||||||
|
rightConn.SetReadDeadline(time.Now())
|
||||||
|
<-ch
|
||||||
|
}
|
@ -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
|
|
||||||
}
|
|
@ -52,8 +52,8 @@ func (alloc *Allocator) Put(buf []byte) error {
|
|||||||
return errors.New("allocator Put() incorrect buffer size")
|
return errors.New("allocator Put() incorrect buffer size")
|
||||||
}
|
}
|
||||||
|
|
||||||
//lint:ignore SA6002 ignore temporarily
|
|
||||||
//nolint
|
//nolint
|
||||||
|
//lint:ignore SA6002 ignore temporarily
|
||||||
alloc.buffers[bits].Put(buf)
|
alloc.buffers[bits].Put(buf)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,6 @@ type Result struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Do single.Do likes sync.singleFlight
|
// Do single.Do likes sync.singleFlight
|
||||||
//lint:ignore ST1008 it likes sync.singleFlight
|
|
||||||
func (s *Single) Do(fn func() (any, error)) (v any, err error, shared bool) {
|
func (s *Single) Do(fn func() (any, error)) (v any, err error, shared bool) {
|
||||||
s.mux.Lock()
|
s.mux.Lock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
@ -159,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
|
|||||||
for valSlice.Len() <= i {
|
for valSlice.Len() <= i {
|
||||||
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
|
||||||
}
|
}
|
||||||
currentField := valSlice.Index(i)
|
|
||||||
|
|
||||||
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
fieldName := fmt.Sprintf("%s[%d]", name, i)
|
||||||
|
if currentData == nil {
|
||||||
|
// in weakly type mode, null will convert to zero value
|
||||||
|
if d.option.WeaklyTypedInput {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// in non-weakly type mode, null will convert to nil if element's zero value is nil, otherwise return an error
|
||||||
|
if elemKind := valElemType.Kind(); elemKind == reflect.Map || elemKind == reflect.Slice {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("'%s' can not be null", fieldName)
|
||||||
|
}
|
||||||
|
currentField := valSlice.Index(i)
|
||||||
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
if err := d.decode(fieldName, currentData, currentField); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -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)
|
||||||
|
}
|
||||||
|
@ -9,19 +9,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
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) {
|
||||||
opt := &option{
|
|
||||||
interfaceName: DefaultInterface.Load(),
|
|
||||||
routingMark: int(DefaultRoutingMark.Load()),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range DefaultOptions {
|
|
||||||
o(opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, o := range options {
|
|
||||||
o(opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
@ -32,25 +19,17 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
var ip net.IP
|
var ip net.IP
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "udp4":
|
case "tcp4", "udp4":
|
||||||
if !opt.direct {
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
if !opt.direct {
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
return dialContext(ctx, network, ip, port, options)
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return dualStackDialContext(ctx, network, address, opt)
|
return dualStackDialContext(ctx, network, address, options)
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("network invalid")
|
return nil, errors.New("network invalid")
|
||||||
}
|
}
|
||||||
@ -88,7 +67,20 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination net.IP, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination net.IP, port string, options []Option) (net.Conn, error) {
|
||||||
|
opt := &option{
|
||||||
|
interfaceName: DefaultInterface.Load(),
|
||||||
|
routingMark: int(DefaultRoutingMark.Load()),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range DefaultOptions {
|
||||||
|
o(opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range options {
|
||||||
|
o(opt)
|
||||||
|
}
|
||||||
|
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
|
||||||
@ -102,7 +94,7 @@ func dialContext(ctx context.Context, network string, destination net.IP, port s
|
|||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
func dualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
func dualStackDialContext(ctx context.Context, network, address string, options []Option) (net.Conn, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -121,7 +113,7 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
results := make(chan dialResult)
|
results := make(chan dialResult)
|
||||||
var primary, fallback dialResult
|
var primary, fallback dialResult
|
||||||
|
|
||||||
startRacer := func(ctx context.Context, network, host string, direct bool, ipv6 bool) {
|
startRacer := func(ctx context.Context, network, host string, ipv6 bool) {
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
@ -135,28 +127,20 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
|
|
||||||
var ip net.IP
|
var ip net.IP
|
||||||
if ipv6 {
|
if ipv6 {
|
||||||
if !direct {
|
ip, result.error = resolver.ResolveIPv6(host)
|
||||||
ip, result.error = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
if !direct {
|
ip, result.error = resolver.ResolveIPv4(host)
|
||||||
ip, result.error = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, result.error = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if result.error != nil {
|
if result.error != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
result.resolved = true
|
result.resolved = true
|
||||||
|
|
||||||
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
result.Conn, result.error = dialContext(ctx, network, ip, port, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
go startRacer(ctx, network+"4", host, opt.direct, false)
|
go startRacer(ctx, network+"4", host, false)
|
||||||
go startRacer(ctx, network+"6", host, opt.direct, true)
|
go startRacer(ctx, network+"6", host, true)
|
||||||
|
|
||||||
for res := range results {
|
for res := range results {
|
||||||
if res.error == nil {
|
if res.error == nil {
|
||||||
|
@ -31,13 +31,13 @@ func bindMarkToControl(mark int, chain controlFn) controlFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.Control(func(fd uintptr) {
|
var innerErr error
|
||||||
switch network {
|
err = c.Control(func(fd uintptr) {
|
||||||
case "tcp4", "udp4":
|
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
||||||
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
case "tcp6", "udp6":
|
|
||||||
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
if innerErr != nil {
|
||||||
|
err = innerErr
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,7 +12,6 @@ type option struct {
|
|||||||
interfaceName string
|
interfaceName string
|
||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
direct bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -34,9 +33,3 @@ func WithRoutingMark(mark int) Option {
|
|||||||
opt.routingMark = mark
|
opt.routingMark = mark
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithDirect() Option {
|
|
||||||
return func(opt *option) {
|
|
||||||
opt.direct = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
// We must use this DialContext to query DNS
|
|
||||||
// when using net default resolver.
|
|
||||||
net.DefaultResolver.PreferGo = true
|
|
||||||
net.DefaultResolver.Dial = resolverDialContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolverDialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
d := &net.Dialer{}
|
|
||||||
|
|
||||||
interfaceName := DefaultInterface.Load()
|
|
||||||
|
|
||||||
if interfaceName != "" {
|
|
||||||
dstIP := net.ParseIP(address)
|
|
||||||
if dstIP != nil {
|
|
||||||
bindIfaceToDialer(interfaceName, d, network, dstIP)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return d.DialContext(ctx, network, address)
|
|
||||||
}
|
|
@ -53,8 +53,3 @@ func (c *cachefileStore) Exist(ip net.IP) bool {
|
|||||||
// CloneTo implements store.CloneTo
|
// CloneTo implements store.CloneTo
|
||||||
// already persistence
|
// already persistence
|
||||||
func (c *cachefileStore) CloneTo(store store) {}
|
func (c *cachefileStore) CloneTo(store store) {}
|
||||||
|
|
||||||
// FlushFakeIP implements store.FlushFakeIP
|
|
||||||
func (c *cachefileStore) FlushFakeIP() error {
|
|
||||||
return c.cache.FlushFakeIP()
|
|
||||||
}
|
|
||||||
|
@ -67,8 +67,3 @@ func (m *memoryStore) CloneTo(store store) {
|
|||||||
m.cache.CloneTo(ms.cache)
|
m.cache.CloneTo(ms.cache)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FlushFakeIP implements store.FlushFakeIP
|
|
||||||
func (m *memoryStore) FlushFakeIP() error {
|
|
||||||
return m.cache.Clear()
|
|
||||||
}
|
|
||||||
|
@ -18,20 +18,18 @@ type store interface {
|
|||||||
DelByIP(ip net.IP)
|
DelByIP(ip net.IP)
|
||||||
Exist(ip net.IP) bool
|
Exist(ip net.IP) bool
|
||||||
CloneTo(store)
|
CloneTo(store)
|
||||||
FlushFakeIP() error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pool is a implementation about fake ip generator without storage
|
// Pool is a implementation about fake ip generator without storage
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
max uint32
|
max uint32
|
||||||
min uint32
|
min uint32
|
||||||
gateway uint32
|
gateway uint32
|
||||||
broadcast uint32
|
offset uint32
|
||||||
offset uint32
|
mux sync.Mutex
|
||||||
mux sync.Mutex
|
host *trie.DomainTrie
|
||||||
host *trie.DomainTrie
|
ipnet *net.IPNet
|
||||||
ipnet *net.IPNet
|
store store
|
||||||
store store
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup return a fake ip with host
|
// Lookup return a fake ip with host
|
||||||
@ -84,11 +82,6 @@ func (p *Pool) Gateway() net.IP {
|
|||||||
return uintToIP(p.gateway)
|
return uintToIP(p.gateway)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Broadcast return broadcast ip
|
|
||||||
func (p *Pool) Broadcast() net.IP {
|
|
||||||
return uintToIP(p.broadcast)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPNet return raw ipnet
|
// IPNet return raw ipnet
|
||||||
func (p *Pool) IPNet() *net.IPNet {
|
func (p *Pool) IPNet() *net.IPNet {
|
||||||
return p.ipnet
|
return p.ipnet
|
||||||
@ -121,10 +114,6 @@ func (p *Pool) get(host string) net.IP {
|
|||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pool) FlushFakeIP() error {
|
|
||||||
return p.store.FlushFakeIP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func ipToUint(ip net.IP) uint32 {
|
func ipToUint(ip net.IP) uint32 {
|
||||||
v := uint32(ip[0]) << 24
|
v := uint32(ip[0]) << 24
|
||||||
v += uint32(ip[1]) << 16
|
v += uint32(ip[1]) << 16
|
||||||
@ -152,10 +141,10 @@ type Options struct {
|
|||||||
|
|
||||||
// New return Pool instance
|
// New return Pool instance
|
||||||
func New(options Options) (*Pool, error) {
|
func New(options Options) (*Pool, error) {
|
||||||
min := ipToUint(options.IPNet.IP) + 3
|
min := ipToUint(options.IPNet.IP) + 2
|
||||||
|
|
||||||
ones, bits := options.IPNet.Mask.Size()
|
ones, bits := options.IPNet.Mask.Size()
|
||||||
total := 1<<uint(bits-ones) - 4
|
total := 1<<uint(bits-ones) - 2
|
||||||
|
|
||||||
if total <= 0 {
|
if total <= 0 {
|
||||||
return nil, errors.New("ipnet don't have valid ip")
|
return nil, errors.New("ipnet don't have valid ip")
|
||||||
@ -163,12 +152,11 @@ func New(options Options) (*Pool, error) {
|
|||||||
|
|
||||||
max := min + uint32(total) - 1
|
max := min + uint32(total) - 1
|
||||||
pool := &Pool{
|
pool := &Pool{
|
||||||
min: min,
|
min: min,
|
||||||
max: max,
|
max: max,
|
||||||
gateway: min - 2,
|
gateway: min - 1,
|
||||||
broadcast: max + 1,
|
host: options.Host,
|
||||||
host: options.Host,
|
ipnet: options.IPNet,
|
||||||
ipnet: options.IPNet,
|
|
||||||
}
|
}
|
||||||
if options.Persistence {
|
if options.Persistence {
|
||||||
pool.store = &cachefileStore{
|
pool.store = &cachefileStore{
|
||||||
|
@ -49,7 +49,7 @@ func createCachefileStore(options Options) (*Pool, string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_Basic(t *testing.T) {
|
func TestPool_Basic(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.0/28")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
IPNet: ipnet,
|
IPNet: ipnet,
|
||||||
Size: 10,
|
Size: 10,
|
||||||
@ -62,22 +62,21 @@ 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.Equal(net.IP{192, 168, 0, 3}))
|
assert.True(t, first.Equal(net.IP{192, 168, 0, 2}))
|
||||||
assert.Equal(t, pool.Lookup("foo.com"), net.IP{192, 168, 0, 3})
|
assert.Equal(t, pool.Lookup("foo.com"), net.IP{192, 168, 0, 2})
|
||||||
assert.True(t, last.Equal(net.IP{192, 168, 0, 4}))
|
assert.True(t, last.Equal(net.IP{192, 168, 0, 3}))
|
||||||
assert.True(t, exist)
|
assert.True(t, exist)
|
||||||
assert.Equal(t, bar, "bar.com")
|
assert.Equal(t, bar, "bar.com")
|
||||||
assert.Equal(t, pool.Gateway(), net.IP{192, 168, 0, 1})
|
assert.Equal(t, pool.Gateway(), net.IP{192, 168, 0, 1})
|
||||||
assert.Equal(t, pool.Broadcast(), net.IP{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(net.IP{192, 168, 0, 4}))
|
assert.True(t, pool.Exist(net.IP{192, 168, 0, 3}))
|
||||||
assert.False(t, pool.Exist(net.IP{192, 168, 0, 5}))
|
assert.False(t, pool.Exist(net.IP{192, 168, 0, 4}))
|
||||||
assert.False(t, pool.Exist(net.ParseIP("::1")))
|
assert.False(t, pool.Exist(net.ParseIP("::1")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_CycleUsed(t *testing.T) {
|
func TestPool_CycleUsed(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.16/28")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
IPNet: ipnet,
|
IPNet: ipnet,
|
||||||
Size: 10,
|
Size: 10,
|
||||||
@ -88,7 +87,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 < 3; 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")
|
||||||
@ -99,7 +98,7 @@ func TestPool_CycleUsed(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_Skip(t *testing.T) {
|
func TestPool_Skip(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
||||||
tree := trie.New()
|
tree := trie.New()
|
||||||
tree.Insert("example.com", tree)
|
tree.Insert("example.com", tree)
|
||||||
pools, tempfile, err := createPools(Options{
|
pools, tempfile, err := createPools(Options{
|
||||||
@ -170,8 +169,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.Equal(net.IP{192, 168, 0, 3}))
|
assert.True(t, first.Equal(net.IP{192, 168, 0, 2}))
|
||||||
assert.True(t, last.Equal(net.IP{192, 168, 0, 4}))
|
assert.True(t, last.Equal(net.IP{192, 168, 0, 3}))
|
||||||
|
|
||||||
newPool, _ := New(Options{
|
newPool, _ := New(Options{
|
||||||
IPNet: ipnet,
|
IPNet: ipnet,
|
||||||
@ -193,59 +192,3 @@ func TestPool_Error(t *testing.T) {
|
|||||||
|
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPool_FlushFileCache(t *testing.T) {
|
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/28")
|
|
||||||
pools, tempfile, err := createPools(Options{
|
|
||||||
IPNet: ipnet,
|
|
||||||
Size: 10,
|
|
||||||
})
|
|
||||||
assert.Nil(t, err)
|
|
||||||
defer os.Remove(tempfile)
|
|
||||||
|
|
||||||
for _, pool := range pools {
|
|
||||||
foo := pool.Lookup("foo.com")
|
|
||||||
bar := pool.Lookup("baz.com")
|
|
||||||
bax := pool.Lookup("baz.com")
|
|
||||||
fox := pool.Lookup("foo.com")
|
|
||||||
|
|
||||||
err = pool.FlushFakeIP()
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
baz := pool.Lookup("foo.com")
|
|
||||||
next := pool.Lookup("baz.com")
|
|
||||||
nero := pool.Lookup("foo.com")
|
|
||||||
|
|
||||||
assert.Equal(t, foo, fox)
|
|
||||||
assert.NotEqual(t, foo, baz)
|
|
||||||
assert.Equal(t, bar, bax)
|
|
||||||
assert.NotEqual(t, bar, next)
|
|
||||||
assert.Equal(t, baz, nero)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPool_FlushMemoryCache(t *testing.T) {
|
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/28")
|
|
||||||
pool, _ := New(Options{
|
|
||||||
IPNet: ipnet,
|
|
||||||
Size: 10,
|
|
||||||
})
|
|
||||||
|
|
||||||
foo := pool.Lookup("foo.com")
|
|
||||||
bar := pool.Lookup("baz.com")
|
|
||||||
bax := pool.Lookup("baz.com")
|
|
||||||
fox := pool.Lookup("foo.com")
|
|
||||||
|
|
||||||
err := pool.FlushFakeIP()
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
baz := pool.Lookup("foo.com")
|
|
||||||
next := pool.Lookup("baz.com")
|
|
||||||
nero := pool.Lookup("foo.com")
|
|
||||||
|
|
||||||
assert.Equal(t, foo, fox)
|
|
||||||
assert.NotEqual(t, foo, baz)
|
|
||||||
assert.Equal(t, bar, bax)
|
|
||||||
assert.NotEqual(t, bar, next)
|
|
||||||
assert.Equal(t, baz, nero)
|
|
||||||
}
|
|
||||||
|
@ -1,51 +0,0 @@
|
|||||||
package geodata
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type AttributeList struct {
|
|
||||||
matcher []AttributeMatcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func (al *AttributeList) Match(domain *router.Domain) bool {
|
|
||||||
for _, matcher := range al.matcher {
|
|
||||||
if !matcher.Match(domain) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (al *AttributeList) IsEmpty() bool {
|
|
||||||
return len(al.matcher) == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseAttrs(attrs []string) *AttributeList {
|
|
||||||
al := new(AttributeList)
|
|
||||||
for _, attr := range attrs {
|
|
||||||
trimmedAttr := strings.ToLower(strings.TrimSpace(attr))
|
|
||||||
if len(trimmedAttr) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
al.matcher = append(al.matcher, BooleanMatcher(trimmedAttr))
|
|
||||||
}
|
|
||||||
return al
|
|
||||||
}
|
|
||||||
|
|
||||||
type AttributeMatcher interface {
|
|
||||||
Match(*router.Domain) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type BooleanMatcher string
|
|
||||||
|
|
||||||
func (m BooleanMatcher) Match(domain *router.Domain) bool {
|
|
||||||
for _, attr := range domain.Attribute {
|
|
||||||
if strings.EqualFold(attr.GetKey(), string(m)) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
@ -1,87 +0,0 @@
|
|||||||
package geodata
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
type loader struct {
|
|
||||||
LoaderImplementation
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
|
||||||
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
|
||||||
parts := strings.Split(siteWithAttr, "@")
|
|
||||||
if len(parts) == 0 {
|
|
||||||
return nil, errors.New("empty rule")
|
|
||||||
}
|
|
||||||
list := strings.TrimSpace(parts[0])
|
|
||||||
attrVal := parts[1:]
|
|
||||||
|
|
||||||
if len(list) == 0 {
|
|
||||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
|
|
||||||
domains, err := l.LoadSite(file, list)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
attrs := parseAttrs(attrVal)
|
|
||||||
if attrs.IsEmpty() {
|
|
||||||
if strings.Contains(siteWithAttr, "@") {
|
|
||||||
log.Warnln("empty attribute list: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
return domains, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
filteredDomains := make([]*router.Domain, 0, len(domains))
|
|
||||||
hasAttrMatched := false
|
|
||||||
for _, domain := range domains {
|
|
||||||
if attrs.Match(domain) {
|
|
||||||
hasAttrMatched = true
|
|
||||||
filteredDomains = append(filteredDomains, domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hasAttrMatched {
|
|
||||||
log.Warnln("attribute match no rule: geosite: %s", siteWithAttr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return filteredDomains, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
|
||||||
return l.LoadIP(C.GeoipName, country)
|
|
||||||
}
|
|
||||||
|
|
||||||
var loaders map[string]func() LoaderImplementation
|
|
||||||
|
|
||||||
func RegisterGeoDataLoaderImplementationCreator(name string, loader func() LoaderImplementation) {
|
|
||||||
if loaders == nil {
|
|
||||||
loaders = map[string]func() LoaderImplementation{}
|
|
||||||
}
|
|
||||||
loaders[name] = loader
|
|
||||||
}
|
|
||||||
|
|
||||||
func getGeoDataLoaderImplementation(name string) (LoaderImplementation, error) {
|
|
||||||
if geoLoader, ok := loaders[name]; ok {
|
|
||||||
return geoLoader(), nil
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("unable to locate GeoData loader %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetGeoDataLoader(name string) (Loader, error) {
|
|
||||||
loadImpl, err := getGeoDataLoaderImplementation(name)
|
|
||||||
if err == nil {
|
|
||||||
return &loader{loadImpl}, nil
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
@ -1,17 +0,0 @@
|
|||||||
package geodata
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type LoaderImplementation interface {
|
|
||||||
LoadSite(filename, list string) ([]*router.Domain, error)
|
|
||||||
LoadIP(filename, country string) ([]*router.CIDR, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Loader interface {
|
|
||||||
LoaderImplementation
|
|
||||||
LoadGeoSite(list string) ([]*router.Domain, error)
|
|
||||||
LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error)
|
|
||||||
LoadGeoIP(country string) ([]*router.CIDR, error)
|
|
||||||
}
|
|
@ -1,142 +0,0 @@
|
|||||||
package memconservative
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"google.golang.org/protobuf/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GeoIPCache map[string]*router.GeoIP
|
|
||||||
|
|
||||||
func (g GeoIPCache) Has(key string) bool {
|
|
||||||
return !(g.Get(key) == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoIPCache) Get(key string) *router.GeoIP {
|
|
||||||
if g == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return g[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoIPCache) Set(key string, value *router.GeoIP) {
|
|
||||||
if g == nil {
|
|
||||||
g = make(map[string]*router.GeoIP)
|
|
||||||
}
|
|
||||||
g[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
|
||||||
asset := C.Path.GetAssetLocation(filename)
|
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
|
||||||
if g.Has(idx) {
|
|
||||||
return g.Get(idx), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
geoipBytes, err := Decode(asset, code)
|
|
||||||
switch err {
|
|
||||||
case nil:
|
|
||||||
var geoip router.GeoIP
|
|
||||||
if err := proto.Unmarshal(geoipBytes, &geoip); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
g.Set(idx, &geoip)
|
|
||||||
return &geoip, nil
|
|
||||||
|
|
||||||
case errCodeNotFound:
|
|
||||||
return nil, fmt.Errorf("country code %s%s%s", code, " not found in ", filename)
|
|
||||||
|
|
||||||
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
|
||||||
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
|
||||||
log.Warnln("failed to decode geoip file: %s%s", filename, ", fallback to the original ReadFile method")
|
|
||||||
geoipBytes, err = os.ReadFile(asset)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var geoipList router.GeoIPList
|
|
||||||
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for _, geoip := range geoipList.GetEntry() {
|
|
||||||
if strings.EqualFold(code, geoip.GetCountryCode()) {
|
|
||||||
g.Set(idx, geoip)
|
|
||||||
return geoip, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("country code %s%s%s", code, " not found in ", filename)
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoSiteCache map[string]*router.GeoSite
|
|
||||||
|
|
||||||
func (g GeoSiteCache) Has(key string) bool {
|
|
||||||
return !(g.Get(key) == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoSiteCache) Get(key string) *router.GeoSite {
|
|
||||||
if g == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return g[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoSiteCache) Set(key string, value *router.GeoSite) {
|
|
||||||
if g == nil {
|
|
||||||
g = make(map[string]*router.GeoSite)
|
|
||||||
}
|
|
||||||
g[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
|
||||||
asset := C.Path.GetAssetLocation(filename)
|
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
|
||||||
if g.Has(idx) {
|
|
||||||
return g.Get(idx), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
geositeBytes, err := Decode(asset, code)
|
|
||||||
switch err {
|
|
||||||
case nil:
|
|
||||||
var geosite router.GeoSite
|
|
||||||
if err := proto.Unmarshal(geositeBytes, &geosite); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
g.Set(idx, &geosite)
|
|
||||||
return &geosite, nil
|
|
||||||
|
|
||||||
case errCodeNotFound:
|
|
||||||
return nil, fmt.Errorf("list %s%s%s", code, " not found in ", filename)
|
|
||||||
|
|
||||||
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
|
|
||||||
errInvalidGeodataFile, errInvalidGeodataVarintLength:
|
|
||||||
log.Warnln("failed to decode geoip file: %s%s", filename, ", fallback to the original ReadFile method")
|
|
||||||
geositeBytes, err = os.ReadFile(asset)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var geositeList router.GeoSiteList
|
|
||||||
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for _, geosite := range geositeList.GetEntry() {
|
|
||||||
if strings.EqualFold(code, geosite.GetCountryCode()) {
|
|
||||||
g.Set(idx, geosite)
|
|
||||||
return geosite, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("list %s%s%s", code, " not found in ", filename)
|
|
||||||
}
|
|
@ -1,107 +0,0 @@
|
|||||||
package memconservative
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"google.golang.org/protobuf/encoding/protowire"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
errFailedToReadBytes = errors.New("failed to read bytes")
|
|
||||||
errFailedToReadExpectedLenBytes = errors.New("failed to read expected length of bytes")
|
|
||||||
errInvalidGeodataFile = errors.New("invalid geodata file")
|
|
||||||
errInvalidGeodataVarintLength = errors.New("invalid geodata varint length")
|
|
||||||
errCodeNotFound = errors.New("code not found")
|
|
||||||
)
|
|
||||||
|
|
||||||
func emitBytes(f io.ReadSeeker, code string) ([]byte, error) {
|
|
||||||
count := 1
|
|
||||||
isInner := false
|
|
||||||
tempContainer := make([]byte, 0, 5)
|
|
||||||
|
|
||||||
var result []byte
|
|
||||||
var advancedN uint64 = 1
|
|
||||||
var geoDataVarintLength, codeVarintLength, varintLenByteLen uint64 = 0, 0, 0
|
|
||||||
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
container := make([]byte, advancedN)
|
|
||||||
bytesRead, err := f.Read(container)
|
|
||||||
if err == io.EOF {
|
|
||||||
return nil, errCodeNotFound
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, errFailedToReadBytes
|
|
||||||
}
|
|
||||||
if bytesRead != len(container) {
|
|
||||||
return nil, errFailedToReadExpectedLenBytes
|
|
||||||
}
|
|
||||||
|
|
||||||
switch count {
|
|
||||||
case 1, 3: // data type ((field_number << 3) | wire_type)
|
|
||||||
if container[0] != 10 { // byte `0A` equals to `10` in decimal
|
|
||||||
return nil, errInvalidGeodataFile
|
|
||||||
}
|
|
||||||
advancedN = 1
|
|
||||||
count++
|
|
||||||
case 2, 4: // data length
|
|
||||||
tempContainer = append(tempContainer, container...)
|
|
||||||
if container[0] > 127 { // max one-byte-length byte `7F`(0FFF FFFF) equals to `127` in decimal
|
|
||||||
advancedN = 1
|
|
||||||
goto Loop
|
|
||||||
}
|
|
||||||
lenVarint, n := protowire.ConsumeVarint(tempContainer)
|
|
||||||
if n < 0 {
|
|
||||||
return nil, errInvalidGeodataVarintLength
|
|
||||||
}
|
|
||||||
tempContainer = nil
|
|
||||||
if !isInner {
|
|
||||||
isInner = true
|
|
||||||
geoDataVarintLength = lenVarint
|
|
||||||
advancedN = 1
|
|
||||||
} else {
|
|
||||||
isInner = false
|
|
||||||
codeVarintLength = lenVarint
|
|
||||||
varintLenByteLen = uint64(n)
|
|
||||||
advancedN = codeVarintLength
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
case 5: // data value
|
|
||||||
if strings.EqualFold(string(container), code) {
|
|
||||||
count++
|
|
||||||
offset := -(1 + int64(varintLenByteLen) + int64(codeVarintLength))
|
|
||||||
_, _ = f.Seek(offset, 1) // back to the start of GeoIP or GeoSite varint
|
|
||||||
advancedN = geoDataVarintLength // the number of bytes to be read in next round
|
|
||||||
} else {
|
|
||||||
count = 1
|
|
||||||
offset := int64(geoDataVarintLength) - int64(codeVarintLength) - int64(varintLenByteLen) - 1
|
|
||||||
_, _ = f.Seek(offset, 1) // skip the unmatched GeoIP or GeoSite varint
|
|
||||||
advancedN = 1 // the next round will be the start of another GeoIPList or GeoSiteList
|
|
||||||
}
|
|
||||||
case 6: // matched GeoIP or GeoSite varint
|
|
||||||
result = container
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Decode(filename, code string) ([]byte, error) {
|
|
||||||
f, err := os.Open(filename)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
|
||||||
}
|
|
||||||
defer func(f *os.File) {
|
|
||||||
_ = f.Close()
|
|
||||||
}(f)
|
|
||||||
|
|
||||||
geoBytes, err := emitBytes(f, code)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return geoBytes, nil
|
|
||||||
}
|
|
@ -1,40 +0,0 @@
|
|||||||
package memconservative
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata"
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type memConservativeLoader struct {
|
|
||||||
geoipcache GeoIPCache
|
|
||||||
geositecache GeoSiteCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memConservativeLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
|
||||||
defer runtime.GC()
|
|
||||||
geoip, err := m.geoipcache.Unmarshal(filename, country)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to decode geodata file: %s, base error: %s", filename, err.Error())
|
|
||||||
}
|
|
||||||
return geoip.Cidr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *memConservativeLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
|
||||||
defer runtime.GC()
|
|
||||||
geosite, err := m.geositecache.Unmarshal(filename, list)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to decode geodata file: %s, base error: %s", filename, err.Error())
|
|
||||||
}
|
|
||||||
return geosite.Domain, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newMemConservativeLoader() geodata.LoaderImplementation {
|
|
||||||
return &memConservativeLoader{make(map[string]*router.GeoIP), make(map[string]*router.GeoSite)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
geodata.RegisterGeoDataLoaderImplementationCreator("memconservative", newMemConservativeLoader)
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
// Modified from: https://github.com/v2fly/v2ray-core/tree/master/infra/conf/geodata
|
|
||||||
// License: MIT
|
|
||||||
|
|
||||||
package geodata
|
|
@ -1,350 +0,0 @@
|
|||||||
package router
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/strmatcher"
|
|
||||||
)
|
|
||||||
|
|
||||||
var matcherTypeMap = map[Domain_Type]strmatcher.Type{
|
|
||||||
Domain_Plain: strmatcher.Substr,
|
|
||||||
Domain_Regex: strmatcher.Regex,
|
|
||||||
Domain_Domain: strmatcher.Domain,
|
|
||||||
Domain_Full: strmatcher.Full,
|
|
||||||
}
|
|
||||||
|
|
||||||
func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) {
|
|
||||||
matcherType, f := matcherTypeMap[domain.Type]
|
|
||||||
if !f {
|
|
||||||
return nil, fmt.Errorf("unsupported domain type %v", domain.Type)
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher, err := matcherType.New(domain.Value)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to create domain matcher, base error: %s", err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return matcher, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type DomainMatcher struct {
|
|
||||||
matchers strmatcher.IndexMatcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
|
|
||||||
g := strmatcher.NewMphMatcherGroup()
|
|
||||||
for _, d := range domains {
|
|
||||||
matcherType, f := matcherTypeMap[d.Type]
|
|
||||||
if !f {
|
|
||||||
return nil, fmt.Errorf("unsupported domain type %v", d.Type)
|
|
||||||
}
|
|
||||||
_, err := g.AddPattern(d.Value, matcherType)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
g.Build()
|
|
||||||
return &DomainMatcher{
|
|
||||||
matchers: g,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDomainMatcher new domain matcher.
|
|
||||||
func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
|
|
||||||
g := new(strmatcher.MatcherGroup)
|
|
||||||
for _, d := range domains {
|
|
||||||
m, err := domainToMatcher(d)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
g.Add(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &DomainMatcher{
|
|
||||||
matchers: g,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *DomainMatcher) ApplyDomain(domain string) bool {
|
|
||||||
return len(m.matchers.Match(strings.ToLower(domain))) > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// CIDRList is an alias of []*CIDR to provide sort.Interface.
|
|
||||||
type CIDRList []*CIDR
|
|
||||||
|
|
||||||
// Len implements sort.Interface.
|
|
||||||
func (l *CIDRList) Len() int {
|
|
||||||
return len(*l)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Less implements sort.Interface.
|
|
||||||
func (l *CIDRList) Less(i int, j int) bool {
|
|
||||||
ci := (*l)[i]
|
|
||||||
cj := (*l)[j]
|
|
||||||
|
|
||||||
if len(ci.Ip) < len(cj.Ip) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(ci.Ip) > len(cj.Ip) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for k := 0; k < len(ci.Ip); k++ {
|
|
||||||
if ci.Ip[k] < cj.Ip[k] {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if ci.Ip[k] > cj.Ip[k] {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ci.Prefix < cj.Prefix
|
|
||||||
}
|
|
||||||
|
|
||||||
// Swap implements sort.Interface.
|
|
||||||
func (l *CIDRList) Swap(i int, j int) {
|
|
||||||
(*l)[i], (*l)[j] = (*l)[j], (*l)[i]
|
|
||||||
}
|
|
||||||
|
|
||||||
type ipv6 struct {
|
|
||||||
a uint64
|
|
||||||
b uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoIPMatcher struct {
|
|
||||||
countryCode string
|
|
||||||
reverseMatch bool
|
|
||||||
ip4 []uint32
|
|
||||||
prefix4 []uint8
|
|
||||||
ip6 []ipv6
|
|
||||||
prefix6 []uint8
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalize4(ip uint32, prefix uint8) uint32 {
|
|
||||||
return (ip >> (32 - prefix)) << (32 - prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalize6(ip ipv6, prefix uint8) ipv6 {
|
|
||||||
if prefix <= 64 {
|
|
||||||
ip.a = (ip.a >> (64 - prefix)) << (64 - prefix)
|
|
||||||
ip.b = 0
|
|
||||||
} else {
|
|
||||||
ip.b = (ip.b >> (128 - prefix)) << (128 - prefix)
|
|
||||||
}
|
|
||||||
return ip
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *GeoIPMatcher) Init(cidrs []*CIDR) error {
|
|
||||||
ip4Count := 0
|
|
||||||
ip6Count := 0
|
|
||||||
|
|
||||||
for _, cidr := range cidrs {
|
|
||||||
ip := cidr.Ip
|
|
||||||
switch len(ip) {
|
|
||||||
case 4:
|
|
||||||
ip4Count++
|
|
||||||
case 16:
|
|
||||||
ip6Count++
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("unexpect ip length: %d", len(ip))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cidrList := CIDRList(cidrs)
|
|
||||||
sort.Sort(&cidrList)
|
|
||||||
|
|
||||||
m.ip4 = make([]uint32, 0, ip4Count)
|
|
||||||
m.prefix4 = make([]uint8, 0, ip4Count)
|
|
||||||
m.ip6 = make([]ipv6, 0, ip6Count)
|
|
||||||
m.prefix6 = make([]uint8, 0, ip6Count)
|
|
||||||
|
|
||||||
for _, cidr := range cidrs {
|
|
||||||
ip := cidr.Ip
|
|
||||||
prefix := uint8(cidr.Prefix)
|
|
||||||
switch len(ip) {
|
|
||||||
case 4:
|
|
||||||
m.ip4 = append(m.ip4, normalize4(binary.BigEndian.Uint32(ip), prefix))
|
|
||||||
m.prefix4 = append(m.prefix4, prefix)
|
|
||||||
case 16:
|
|
||||||
ip6 := ipv6{
|
|
||||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
|
||||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
|
||||||
}
|
|
||||||
ip6 = normalize6(ip6, prefix)
|
|
||||||
|
|
||||||
m.ip6 = append(m.ip6, ip6)
|
|
||||||
m.prefix6 = append(m.prefix6, prefix)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *GeoIPMatcher) SetReverseMatch(isReverseMatch bool) {
|
|
||||||
m.reverseMatch = isReverseMatch
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *GeoIPMatcher) match4(ip uint32) bool {
|
|
||||||
if len(m.ip4) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip < m.ip4[0] {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
size := uint32(len(m.ip4))
|
|
||||||
l := uint32(0)
|
|
||||||
r := size
|
|
||||||
for l < r {
|
|
||||||
x := ((l + r) >> 1)
|
|
||||||
if ip < m.ip4[x] {
|
|
||||||
r = x
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
nip := normalize4(ip, m.prefix4[x])
|
|
||||||
if nip == m.ip4[x] {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
l = x + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
return l > 0 && normalize4(ip, m.prefix4[l-1]) == m.ip4[l-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
func less6(a ipv6, b ipv6) bool {
|
|
||||||
return a.a < b.a || (a.a == b.a && a.b < b.b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *GeoIPMatcher) match6(ip ipv6) bool {
|
|
||||||
if len(m.ip6) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if less6(ip, m.ip6[0]) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
size := uint32(len(m.ip6))
|
|
||||||
l := uint32(0)
|
|
||||||
r := size
|
|
||||||
for l < r {
|
|
||||||
x := (l + r) / 2
|
|
||||||
if less6(ip, m.ip6[x]) {
|
|
||||||
r = x
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if normalize6(ip, m.prefix6[x]) == m.ip6[x] {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
l = x + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
return l > 0 && normalize6(ip, m.prefix6[l-1]) == m.ip6[l-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Match returns true if the given ip is included by the GeoIP.
|
|
||||||
func (m *GeoIPMatcher) Match(ip net.IP) bool {
|
|
||||||
switch len(ip) {
|
|
||||||
case 4:
|
|
||||||
if m.reverseMatch {
|
|
||||||
return !m.match4(binary.BigEndian.Uint32(ip))
|
|
||||||
}
|
|
||||||
return m.match4(binary.BigEndian.Uint32(ip))
|
|
||||||
case 16:
|
|
||||||
if m.reverseMatch {
|
|
||||||
return !m.match6(ipv6{
|
|
||||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
|
||||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return m.match6(ipv6{
|
|
||||||
a: binary.BigEndian.Uint64(ip[0:8]),
|
|
||||||
b: binary.BigEndian.Uint64(ip[8:16]),
|
|
||||||
})
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GeoIPMatcherContainer is a container for GeoIPMatchers. It keeps unique copies of GeoIPMatcher by country code.
|
|
||||||
type GeoIPMatcherContainer struct {
|
|
||||||
matchers []*GeoIPMatcher
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add adds a new GeoIP set into the container.
|
|
||||||
// If the country code of GeoIP is not empty, GeoIPMatcherContainer will try to find an existing one, instead of adding a new one.
|
|
||||||
func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
|
|
||||||
if len(geoip.CountryCode) > 0 {
|
|
||||||
for _, m := range c.matchers {
|
|
||||||
if m.countryCode == geoip.CountryCode && m.reverseMatch == geoip.ReverseMatch {
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
m := &GeoIPMatcher{
|
|
||||||
countryCode: geoip.CountryCode,
|
|
||||||
reverseMatch: geoip.ReverseMatch,
|
|
||||||
}
|
|
||||||
if err := m.Init(geoip.Cidr); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(geoip.CountryCode) > 0 {
|
|
||||||
c.matchers = append(c.matchers, m)
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var globalGeoIPContainer GeoIPMatcherContainer
|
|
||||||
|
|
||||||
type MultiGeoIPMatcher struct {
|
|
||||||
matchers []*GeoIPMatcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGeoIPMatcher(geoip *GeoIP) (*GeoIPMatcher, error) {
|
|
||||||
matcher, err := globalGeoIPContainer.Add(geoip)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return matcher, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *MultiGeoIPMatcher) ApplyIp(ip net.IP) bool {
|
|
||||||
|
|
||||||
for _, matcher := range m.matchers {
|
|
||||||
if matcher.Match(ip) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMultiGeoIPMatcher(geoips []*GeoIP) (*MultiGeoIPMatcher, error) {
|
|
||||||
var matchers []*GeoIPMatcher
|
|
||||||
for _, geoip := range geoips {
|
|
||||||
matcher, err := globalGeoIPContainer.Add(geoip)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
matchers = append(matchers, matcher)
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher := &MultiGeoIPMatcher{
|
|
||||||
matchers: matchers,
|
|
||||||
}
|
|
||||||
|
|
||||||
return matcher, nil
|
|
||||||
}
|
|
@ -1,725 +0,0 @@
|
|||||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// protoc-gen-go v1.28.0
|
|
||||||
// protoc v3.19.1
|
|
||||||
// source: component/geodata/router/config.proto
|
|
||||||
|
|
||||||
package router
|
|
||||||
|
|
||||||
import (
|
|
||||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
|
||||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
|
||||||
reflect "reflect"
|
|
||||||
sync "sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Verify that this generated code is sufficiently up-to-date.
|
|
||||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
|
||||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
|
||||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Type of domain value.
|
|
||||||
type Domain_Type int32
|
|
||||||
|
|
||||||
const (
|
|
||||||
// The value is used as is.
|
|
||||||
Domain_Plain Domain_Type = 0
|
|
||||||
// The value is used as a regular expression.
|
|
||||||
Domain_Regex Domain_Type = 1
|
|
||||||
// The value is a root domain.
|
|
||||||
Domain_Domain Domain_Type = 2
|
|
||||||
// The value is a domain.
|
|
||||||
Domain_Full Domain_Type = 3
|
|
||||||
)
|
|
||||||
|
|
||||||
// Enum value maps for Domain_Type.
|
|
||||||
var (
|
|
||||||
Domain_Type_name = map[int32]string{
|
|
||||||
0: "Plain",
|
|
||||||
1: "Regex",
|
|
||||||
2: "Domain",
|
|
||||||
3: "Full",
|
|
||||||
}
|
|
||||||
Domain_Type_value = map[string]int32{
|
|
||||||
"Plain": 0,
|
|
||||||
"Regex": 1,
|
|
||||||
"Domain": 2,
|
|
||||||
"Full": 3,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func (x Domain_Type) Enum() *Domain_Type {
|
|
||||||
p := new(Domain_Type)
|
|
||||||
*p = x
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x Domain_Type) String() string {
|
|
||||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Domain_Type) Descriptor() protoreflect.EnumDescriptor {
|
|
||||||
return file_component_geodata_router_config_proto_enumTypes[0].Descriptor()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Domain_Type) Type() protoreflect.EnumType {
|
|
||||||
return &file_component_geodata_router_config_proto_enumTypes[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x Domain_Type) Number() protoreflect.EnumNumber {
|
|
||||||
return protoreflect.EnumNumber(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use Domain_Type.Descriptor instead.
|
|
||||||
func (Domain_Type) EnumDescriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{0, 0}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Domain for routing decision.
|
|
||||||
type Domain struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
// Domain matching type.
|
|
||||||
Type Domain_Type `protobuf:"varint,1,opt,name=type,proto3,enum=clash.component.geodata.router.Domain_Type" json:"type,omitempty"`
|
|
||||||
// Domain value.
|
|
||||||
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
|
|
||||||
// Attributes of this domain. May be used for filtering.
|
|
||||||
Attribute []*Domain_Attribute `protobuf:"bytes,3,rep,name=attribute,proto3" json:"attribute,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain) Reset() {
|
|
||||||
*x = Domain{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[0]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*Domain) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *Domain) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[0]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use Domain.ProtoReflect.Descriptor instead.
|
|
||||||
func (*Domain) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain) GetType() Domain_Type {
|
|
||||||
if x != nil {
|
|
||||||
return x.Type
|
|
||||||
}
|
|
||||||
return Domain_Plain
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain) GetValue() string {
|
|
||||||
if x != nil {
|
|
||||||
return x.Value
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain) GetAttribute() []*Domain_Attribute {
|
|
||||||
if x != nil {
|
|
||||||
return x.Attribute
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// IP for routing decision, in CIDR form.
|
|
||||||
type CIDR struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
// IP address, should be either 4 or 16 bytes.
|
|
||||||
Ip []byte `protobuf:"bytes,1,opt,name=ip,proto3" json:"ip,omitempty"`
|
|
||||||
// Number of leading ones in the network mask.
|
|
||||||
Prefix uint32 `protobuf:"varint,2,opt,name=prefix,proto3" json:"prefix,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *CIDR) Reset() {
|
|
||||||
*x = CIDR{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[1]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *CIDR) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*CIDR) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *CIDR) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[1]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use CIDR.ProtoReflect.Descriptor instead.
|
|
||||||
func (*CIDR) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{1}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *CIDR) GetIp() []byte {
|
|
||||||
if x != nil {
|
|
||||||
return x.Ip
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *CIDR) GetPrefix() uint32 {
|
|
||||||
if x != nil {
|
|
||||||
return x.Prefix
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoIP struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"`
|
|
||||||
Cidr []*CIDR `protobuf:"bytes,2,rep,name=cidr,proto3" json:"cidr,omitempty"`
|
|
||||||
ReverseMatch bool `protobuf:"varint,3,opt,name=reverse_match,json=reverseMatch,proto3" json:"reverse_match,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIP) Reset() {
|
|
||||||
*x = GeoIP{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[2]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIP) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*GeoIP) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *GeoIP) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[2]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use GeoIP.ProtoReflect.Descriptor instead.
|
|
||||||
func (*GeoIP) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{2}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIP) GetCountryCode() string {
|
|
||||||
if x != nil {
|
|
||||||
return x.CountryCode
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIP) GetCidr() []*CIDR {
|
|
||||||
if x != nil {
|
|
||||||
return x.Cidr
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIP) GetReverseMatch() bool {
|
|
||||||
if x != nil {
|
|
||||||
return x.ReverseMatch
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoIPList struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
Entry []*GeoIP `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIPList) Reset() {
|
|
||||||
*x = GeoIPList{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[3]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIPList) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*GeoIPList) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *GeoIPList) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[3]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use GeoIPList.ProtoReflect.Descriptor instead.
|
|
||||||
func (*GeoIPList) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{3}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoIPList) GetEntry() []*GeoIP {
|
|
||||||
if x != nil {
|
|
||||||
return x.Entry
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoSite struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"`
|
|
||||||
Domain []*Domain `protobuf:"bytes,2,rep,name=domain,proto3" json:"domain,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSite) Reset() {
|
|
||||||
*x = GeoSite{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[4]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSite) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*GeoSite) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *GeoSite) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[4]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use GeoSite.ProtoReflect.Descriptor instead.
|
|
||||||
func (*GeoSite) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{4}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSite) GetCountryCode() string {
|
|
||||||
if x != nil {
|
|
||||||
return x.CountryCode
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSite) GetDomain() []*Domain {
|
|
||||||
if x != nil {
|
|
||||||
return x.Domain
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type GeoSiteList struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
Entry []*GeoSite `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSiteList) Reset() {
|
|
||||||
*x = GeoSiteList{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[5]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSiteList) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*GeoSiteList) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *GeoSiteList) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[5]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use GeoSiteList.ProtoReflect.Descriptor instead.
|
|
||||||
func (*GeoSiteList) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{5}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *GeoSiteList) GetEntry() []*GeoSite {
|
|
||||||
if x != nil {
|
|
||||||
return x.Entry
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain_Attribute struct {
|
|
||||||
state protoimpl.MessageState
|
|
||||||
sizeCache protoimpl.SizeCache
|
|
||||||
unknownFields protoimpl.UnknownFields
|
|
||||||
|
|
||||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
|
||||||
// Types that are assignable to TypedValue:
|
|
||||||
// *Domain_Attribute_BoolValue
|
|
||||||
// *Domain_Attribute_IntValue
|
|
||||||
TypedValue isDomain_Attribute_TypedValue `protobuf_oneof:"typed_value"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) Reset() {
|
|
||||||
*x = Domain_Attribute{}
|
|
||||||
if protoimpl.UnsafeEnabled {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[6]
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) String() string {
|
|
||||||
return protoimpl.X.MessageStringOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*Domain_Attribute) ProtoMessage() {}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) ProtoReflect() protoreflect.Message {
|
|
||||||
mi := &file_component_geodata_router_config_proto_msgTypes[6]
|
|
||||||
if protoimpl.UnsafeEnabled && x != nil {
|
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
|
||||||
if ms.LoadMessageInfo() == nil {
|
|
||||||
ms.StoreMessageInfo(mi)
|
|
||||||
}
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return mi.MessageOf(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use Domain_Attribute.ProtoReflect.Descriptor instead.
|
|
||||||
func (*Domain_Attribute) Descriptor() ([]byte, []int) {
|
|
||||||
return file_component_geodata_router_config_proto_rawDescGZIP(), []int{0, 0}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) GetKey() string {
|
|
||||||
if x != nil {
|
|
||||||
return x.Key
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Domain_Attribute) GetTypedValue() isDomain_Attribute_TypedValue {
|
|
||||||
if m != nil {
|
|
||||||
return m.TypedValue
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) GetBoolValue() bool {
|
|
||||||
if x, ok := x.GetTypedValue().(*Domain_Attribute_BoolValue); ok {
|
|
||||||
return x.BoolValue
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *Domain_Attribute) GetIntValue() int64 {
|
|
||||||
if x, ok := x.GetTypedValue().(*Domain_Attribute_IntValue); ok {
|
|
||||||
return x.IntValue
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
type isDomain_Attribute_TypedValue interface {
|
|
||||||
isDomain_Attribute_TypedValue()
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain_Attribute_BoolValue struct {
|
|
||||||
BoolValue bool `protobuf:"varint,2,opt,name=bool_value,json=boolValue,proto3,oneof"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Domain_Attribute_IntValue struct {
|
|
||||||
IntValue int64 `protobuf:"varint,3,opt,name=int_value,json=intValue,proto3,oneof"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*Domain_Attribute_BoolValue) isDomain_Attribute_TypedValue() {}
|
|
||||||
|
|
||||||
func (*Domain_Attribute_IntValue) isDomain_Attribute_TypedValue() {}
|
|
||||||
|
|
||||||
var File_component_geodata_router_config_proto protoreflect.FileDescriptor
|
|
||||||
|
|
||||||
var file_component_geodata_router_config_proto_rawDesc = []byte{
|
|
||||||
0x0a, 0x25, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2f, 0x67, 0x65, 0x6f, 0x64,
|
|
||||||
0x61, 0x74, 0x61, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69,
|
|
||||||
0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63,
|
|
||||||
0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61,
|
|
||||||
0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x22, 0xd1, 0x02, 0x0a, 0x06, 0x44, 0x6f, 0x6d, 0x61,
|
|
||||||
0x69, 0x6e, 0x12, 0x3f, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e,
|
|
||||||
0x32, 0x2b, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65,
|
|
||||||
0x6e, 0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65,
|
|
||||||
0x72, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74,
|
|
||||||
0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01,
|
|
||||||
0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x4e, 0x0a, 0x09, 0x61, 0x74, 0x74,
|
|
||||||
0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x63,
|
|
||||||
0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x67,
|
|
||||||
0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x44, 0x6f,
|
|
||||||
0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x09,
|
|
||||||
0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x1a, 0x6c, 0x0a, 0x09, 0x41, 0x74, 0x74,
|
|
||||||
0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20,
|
|
||||||
0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x1f, 0x0a, 0x0a, 0x62, 0x6f, 0x6f, 0x6c,
|
|
||||||
0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x48, 0x00, 0x52, 0x09,
|
|
||||||
0x62, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1d, 0x0a, 0x09, 0x69, 0x6e, 0x74,
|
|
||||||
0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x48, 0x00, 0x52, 0x08,
|
|
||||||
0x69, 0x6e, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0d, 0x0a, 0x0b, 0x74, 0x79, 0x70, 0x65,
|
|
||||||
0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x32, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12,
|
|
||||||
0x09, 0x0a, 0x05, 0x50, 0x6c, 0x61, 0x69, 0x6e, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x52, 0x65,
|
|
||||||
0x67, 0x65, 0x78, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x10,
|
|
||||||
0x02, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x75, 0x6c, 0x6c, 0x10, 0x03, 0x22, 0x2e, 0x0a, 0x04, 0x43,
|
|
||||||
0x49, 0x44, 0x52, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52,
|
|
||||||
0x02, 0x69, 0x70, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x02, 0x20,
|
|
||||||
0x01, 0x28, 0x0d, 0x52, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x22, 0x89, 0x01, 0x0a, 0x05,
|
|
||||||
0x47, 0x65, 0x6f, 0x49, 0x50, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79,
|
|
||||||
0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x63, 0x6f, 0x75,
|
|
||||||
0x6e, 0x74, 0x72, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x38, 0x0a, 0x04, 0x63, 0x69, 0x64, 0x72,
|
|
||||||
0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63,
|
|
||||||
0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61,
|
|
||||||
0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x43, 0x49, 0x44, 0x52, 0x52, 0x04, 0x63, 0x69,
|
|
||||||
0x64, 0x72, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x76, 0x65, 0x72, 0x73, 0x65, 0x5f, 0x6d, 0x61,
|
|
||||||
0x74, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x72, 0x65, 0x76, 0x65, 0x72,
|
|
||||||
0x73, 0x65, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x22, 0x48, 0x0a, 0x09, 0x47, 0x65, 0x6f, 0x49, 0x50,
|
|
||||||
0x4c, 0x69, 0x73, 0x74, 0x12, 0x3b, 0x0a, 0x05, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x01, 0x20,
|
|
||||||
0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70,
|
|
||||||
0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f,
|
|
||||||
0x75, 0x74, 0x65, 0x72, 0x2e, 0x47, 0x65, 0x6f, 0x49, 0x50, 0x52, 0x05, 0x65, 0x6e, 0x74, 0x72,
|
|
||||||
0x79, 0x22, 0x6c, 0x0a, 0x07, 0x47, 0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x12, 0x21, 0x0a, 0x0c,
|
|
||||||
0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01,
|
|
||||||
0x28, 0x09, 0x52, 0x0b, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x12,
|
|
||||||
0x3e, 0x0a, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32,
|
|
||||||
0x26, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e,
|
|
||||||
0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72,
|
|
||||||
0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x52, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x22,
|
|
||||||
0x4c, 0x0a, 0x0b, 0x47, 0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x3d,
|
|
||||||
0x0a, 0x05, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e,
|
|
||||||
0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e,
|
|
||||||
0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x47,
|
|
||||||
0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x52, 0x05, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x42, 0x7c, 0x0a,
|
|
||||||
0x22, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x68, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x6f,
|
|
||||||
0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x6f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x72, 0x6f, 0x75,
|
|
||||||
0x74, 0x65, 0x72, 0x50, 0x01, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f,
|
|
||||||
0x6d, 0x2f, 0x44, 0x72, 0x65, 0x61, 0x6d, 0x61, 0x63, 0x72, 0x6f, 0x2f, 0x63, 0x6c, 0x61, 0x73,
|
|
||||||
0x68, 0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2f, 0x67, 0x65, 0x6f, 0x64,
|
|
||||||
0x61, 0x74, 0x61, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0xaa, 0x02, 0x1e, 0x43, 0x6c, 0x61,
|
|
||||||
0x73, 0x68, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2e, 0x47, 0x65, 0x6f,
|
|
||||||
0x64, 0x61, 0x74, 0x61, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f,
|
|
||||||
0x74, 0x6f, 0x33,
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
file_component_geodata_router_config_proto_rawDescOnce sync.Once
|
|
||||||
file_component_geodata_router_config_proto_rawDescData = file_component_geodata_router_config_proto_rawDesc
|
|
||||||
)
|
|
||||||
|
|
||||||
func file_component_geodata_router_config_proto_rawDescGZIP() []byte {
|
|
||||||
file_component_geodata_router_config_proto_rawDescOnce.Do(func() {
|
|
||||||
file_component_geodata_router_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_component_geodata_router_config_proto_rawDescData)
|
|
||||||
})
|
|
||||||
return file_component_geodata_router_config_proto_rawDescData
|
|
||||||
}
|
|
||||||
|
|
||||||
var file_component_geodata_router_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
|
||||||
var file_component_geodata_router_config_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
|
||||||
var file_component_geodata_router_config_proto_goTypes = []interface{}{
|
|
||||||
(Domain_Type)(0), // 0: clash.component.geodata.router.Domain.Type
|
|
||||||
(*Domain)(nil), // 1: clash.component.geodata.router.Domain
|
|
||||||
(*CIDR)(nil), // 2: clash.component.geodata.router.CIDR
|
|
||||||
(*GeoIP)(nil), // 3: clash.component.geodata.router.GeoIP
|
|
||||||
(*GeoIPList)(nil), // 4: clash.component.geodata.router.GeoIPList
|
|
||||||
(*GeoSite)(nil), // 5: clash.component.geodata.router.GeoSite
|
|
||||||
(*GeoSiteList)(nil), // 6: clash.component.geodata.router.GeoSiteList
|
|
||||||
(*Domain_Attribute)(nil), // 7: clash.component.geodata.router.Domain.Attribute
|
|
||||||
}
|
|
||||||
var file_component_geodata_router_config_proto_depIdxs = []int32{
|
|
||||||
0, // 0: clash.component.geodata.router.Domain.type:type_name -> clash.component.geodata.router.Domain.Type
|
|
||||||
7, // 1: clash.component.geodata.router.Domain.attribute:type_name -> clash.component.geodata.router.Domain.Attribute
|
|
||||||
2, // 2: clash.component.geodata.router.GeoIP.cidr:type_name -> clash.component.geodata.router.CIDR
|
|
||||||
3, // 3: clash.component.geodata.router.GeoIPList.entry:type_name -> clash.component.geodata.router.GeoIP
|
|
||||||
1, // 4: clash.component.geodata.router.GeoSite.domain:type_name -> clash.component.geodata.router.Domain
|
|
||||||
5, // 5: clash.component.geodata.router.GeoSiteList.entry:type_name -> clash.component.geodata.router.GeoSite
|
|
||||||
6, // [6:6] is the sub-list for method output_type
|
|
||||||
6, // [6:6] is the sub-list for method input_type
|
|
||||||
6, // [6:6] is the sub-list for extension type_name
|
|
||||||
6, // [6:6] is the sub-list for extension extendee
|
|
||||||
0, // [0:6] is the sub-list for field type_name
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() { file_component_geodata_router_config_proto_init() }
|
|
||||||
func file_component_geodata_router_config_proto_init() {
|
|
||||||
if File_component_geodata_router_config_proto != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !protoimpl.UnsafeEnabled {
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*Domain); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*CIDR); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*GeoIP); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*GeoIPList); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*GeoSite); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*GeoSiteList); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
|
|
||||||
switch v := v.(*Domain_Attribute); i {
|
|
||||||
case 0:
|
|
||||||
return &v.state
|
|
||||||
case 1:
|
|
||||||
return &v.sizeCache
|
|
||||||
case 2:
|
|
||||||
return &v.unknownFields
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file_component_geodata_router_config_proto_msgTypes[6].OneofWrappers = []interface{}{
|
|
||||||
(*Domain_Attribute_BoolValue)(nil),
|
|
||||||
(*Domain_Attribute_IntValue)(nil),
|
|
||||||
}
|
|
||||||
type x struct{}
|
|
||||||
out := protoimpl.TypeBuilder{
|
|
||||||
File: protoimpl.DescBuilder{
|
|
||||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
|
||||||
RawDescriptor: file_component_geodata_router_config_proto_rawDesc,
|
|
||||||
NumEnums: 1,
|
|
||||||
NumMessages: 7,
|
|
||||||
NumExtensions: 0,
|
|
||||||
NumServices: 0,
|
|
||||||
},
|
|
||||||
GoTypes: file_component_geodata_router_config_proto_goTypes,
|
|
||||||
DependencyIndexes: file_component_geodata_router_config_proto_depIdxs,
|
|
||||||
EnumInfos: file_component_geodata_router_config_proto_enumTypes,
|
|
||||||
MessageInfos: file_component_geodata_router_config_proto_msgTypes,
|
|
||||||
}.Build()
|
|
||||||
File_component_geodata_router_config_proto = out.File
|
|
||||||
file_component_geodata_router_config_proto_rawDesc = nil
|
|
||||||
file_component_geodata_router_config_proto_goTypes = nil
|
|
||||||
file_component_geodata_router_config_proto_depIdxs = nil
|
|
||||||
}
|
|
@ -1,68 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package clash.component.geodata.router;
|
|
||||||
option csharp_namespace = "Clash.Component.Geodata.Router";
|
|
||||||
option go_package = "github.com/Dreamacro/clash/component/geodata/router";
|
|
||||||
option java_package = "com.clash.component.geodata.router";
|
|
||||||
option java_multiple_files = true;
|
|
||||||
|
|
||||||
// Domain for routing decision.
|
|
||||||
message Domain {
|
|
||||||
// Type of domain value.
|
|
||||||
enum Type {
|
|
||||||
// The value is used as is.
|
|
||||||
Plain = 0;
|
|
||||||
// The value is used as a regular expression.
|
|
||||||
Regex = 1;
|
|
||||||
// The value is a root domain.
|
|
||||||
Domain = 2;
|
|
||||||
// The value is a domain.
|
|
||||||
Full = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Domain matching type.
|
|
||||||
Type type = 1;
|
|
||||||
|
|
||||||
// Domain value.
|
|
||||||
string value = 2;
|
|
||||||
|
|
||||||
message Attribute {
|
|
||||||
string key = 1;
|
|
||||||
|
|
||||||
oneof typed_value {
|
|
||||||
bool bool_value = 2;
|
|
||||||
int64 int_value = 3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attributes of this domain. May be used for filtering.
|
|
||||||
repeated Attribute attribute = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
// IP for routing decision, in CIDR form.
|
|
||||||
message CIDR {
|
|
||||||
// IP address, should be either 4 or 16 bytes.
|
|
||||||
bytes ip = 1;
|
|
||||||
|
|
||||||
// Number of leading ones in the network mask.
|
|
||||||
uint32 prefix = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GeoIP {
|
|
||||||
string country_code = 1;
|
|
||||||
repeated CIDR cidr = 2;
|
|
||||||
bool reverse_match = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GeoIPList {
|
|
||||||
repeated GeoIP entry = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GeoSite {
|
|
||||||
string country_code = 1;
|
|
||||||
repeated Domain domain = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message GeoSiteList {
|
|
||||||
repeated GeoSite entry = 1;
|
|
||||||
}
|
|
@ -1,84 +0,0 @@
|
|||||||
package standard
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata"
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"google.golang.org/protobuf/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ReadFile(path string) ([]byte, error) {
|
|
||||||
reader, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer func(reader *os.File) {
|
|
||||||
_ = reader.Close()
|
|
||||||
}(reader)
|
|
||||||
|
|
||||||
return io.ReadAll(reader)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ReadAsset(file string) ([]byte, error) {
|
|
||||||
return ReadFile(C.Path.GetAssetLocation(file))
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadIP(filename, country string) ([]*router.CIDR, error) {
|
|
||||||
geoipBytes, err := ReadAsset(filename)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
|
||||||
}
|
|
||||||
var geoipList router.GeoIPList
|
|
||||||
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, geoip := range geoipList.Entry {
|
|
||||||
if strings.EqualFold(geoip.CountryCode, country) {
|
|
||||||
return geoip.Cidr, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("country not found in %s%s%s", filename, ": ", country)
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadSite(filename, list string) ([]*router.Domain, error) {
|
|
||||||
geositeBytes, err := ReadAsset(filename)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to open file: %s, base error: %s", filename, err.Error())
|
|
||||||
}
|
|
||||||
var geositeList router.GeoSiteList
|
|
||||||
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, site := range geositeList.Entry {
|
|
||||||
if strings.EqualFold(site.CountryCode, list) {
|
|
||||||
return site.Domain, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("list not found in %s%s%s", filename, ": ", list)
|
|
||||||
}
|
|
||||||
|
|
||||||
type standardLoader struct{}
|
|
||||||
|
|
||||||
func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) {
|
|
||||||
return loadSite(filename, list)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d standardLoader) LoadIP(filename, country string) ([]*router.CIDR, error) {
|
|
||||||
return loadIP(filename, country)
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
geodata.RegisterGeoDataLoaderImplementationCreator("standard", func() geodata.LoaderImplementation {
|
|
||||||
return standardLoader{}
|
|
||||||
})
|
|
||||||
}
|
|
@ -1,241 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
import (
|
|
||||||
"container/list"
|
|
||||||
)
|
|
||||||
|
|
||||||
const validCharCount = 53
|
|
||||||
|
|
||||||
type MatchType struct {
|
|
||||||
matchType Type
|
|
||||||
exist bool
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
TrieEdge bool = true
|
|
||||||
FailEdge bool = false
|
|
||||||
)
|
|
||||||
|
|
||||||
type Edge struct {
|
|
||||||
edgeType bool
|
|
||||||
nextNode int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ACAutomaton struct {
|
|
||||||
trie [][validCharCount]Edge
|
|
||||||
fail []int
|
|
||||||
exists []MatchType
|
|
||||||
count int
|
|
||||||
}
|
|
||||||
|
|
||||||
func newNode() [validCharCount]Edge {
|
|
||||||
var s [validCharCount]Edge
|
|
||||||
for i := range s {
|
|
||||||
s[i] = Edge{
|
|
||||||
edgeType: FailEdge,
|
|
||||||
nextNode: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
var char2Index = []int{
|
|
||||||
'A': 0,
|
|
||||||
'a': 0,
|
|
||||||
'B': 1,
|
|
||||||
'b': 1,
|
|
||||||
'C': 2,
|
|
||||||
'c': 2,
|
|
||||||
'D': 3,
|
|
||||||
'd': 3,
|
|
||||||
'E': 4,
|
|
||||||
'e': 4,
|
|
||||||
'F': 5,
|
|
||||||
'f': 5,
|
|
||||||
'G': 6,
|
|
||||||
'g': 6,
|
|
||||||
'H': 7,
|
|
||||||
'h': 7,
|
|
||||||
'I': 8,
|
|
||||||
'i': 8,
|
|
||||||
'J': 9,
|
|
||||||
'j': 9,
|
|
||||||
'K': 10,
|
|
||||||
'k': 10,
|
|
||||||
'L': 11,
|
|
||||||
'l': 11,
|
|
||||||
'M': 12,
|
|
||||||
'm': 12,
|
|
||||||
'N': 13,
|
|
||||||
'n': 13,
|
|
||||||
'O': 14,
|
|
||||||
'o': 14,
|
|
||||||
'P': 15,
|
|
||||||
'p': 15,
|
|
||||||
'Q': 16,
|
|
||||||
'q': 16,
|
|
||||||
'R': 17,
|
|
||||||
'r': 17,
|
|
||||||
'S': 18,
|
|
||||||
's': 18,
|
|
||||||
'T': 19,
|
|
||||||
't': 19,
|
|
||||||
'U': 20,
|
|
||||||
'u': 20,
|
|
||||||
'V': 21,
|
|
||||||
'v': 21,
|
|
||||||
'W': 22,
|
|
||||||
'w': 22,
|
|
||||||
'X': 23,
|
|
||||||
'x': 23,
|
|
||||||
'Y': 24,
|
|
||||||
'y': 24,
|
|
||||||
'Z': 25,
|
|
||||||
'z': 25,
|
|
||||||
'!': 26,
|
|
||||||
'$': 27,
|
|
||||||
'&': 28,
|
|
||||||
'\'': 29,
|
|
||||||
'(': 30,
|
|
||||||
')': 31,
|
|
||||||
'*': 32,
|
|
||||||
'+': 33,
|
|
||||||
',': 34,
|
|
||||||
';': 35,
|
|
||||||
'=': 36,
|
|
||||||
':': 37,
|
|
||||||
'%': 38,
|
|
||||||
'-': 39,
|
|
||||||
'.': 40,
|
|
||||||
'_': 41,
|
|
||||||
'~': 42,
|
|
||||||
'0': 43,
|
|
||||||
'1': 44,
|
|
||||||
'2': 45,
|
|
||||||
'3': 46,
|
|
||||||
'4': 47,
|
|
||||||
'5': 48,
|
|
||||||
'6': 49,
|
|
||||||
'7': 50,
|
|
||||||
'8': 51,
|
|
||||||
'9': 52,
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewACAutomaton() *ACAutomaton {
|
|
||||||
ac := new(ACAutomaton)
|
|
||||||
ac.trie = append(ac.trie, newNode())
|
|
||||||
ac.fail = append(ac.fail, 0)
|
|
||||||
ac.exists = append(ac.exists, MatchType{
|
|
||||||
matchType: Full,
|
|
||||||
exist: false,
|
|
||||||
})
|
|
||||||
return ac
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ac *ACAutomaton) Add(domain string, t Type) {
|
|
||||||
node := 0
|
|
||||||
for i := len(domain) - 1; i >= 0; i-- {
|
|
||||||
idx := char2Index[domain[i]]
|
|
||||||
if ac.trie[node][idx].nextNode == 0 {
|
|
||||||
ac.count++
|
|
||||||
if len(ac.trie) < ac.count+1 {
|
|
||||||
ac.trie = append(ac.trie, newNode())
|
|
||||||
ac.fail = append(ac.fail, 0)
|
|
||||||
ac.exists = append(ac.exists, MatchType{
|
|
||||||
matchType: Full,
|
|
||||||
exist: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
ac.trie[node][idx] = Edge{
|
|
||||||
edgeType: TrieEdge,
|
|
||||||
nextNode: ac.count,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
node = ac.trie[node][idx].nextNode
|
|
||||||
}
|
|
||||||
ac.exists[node] = MatchType{
|
|
||||||
matchType: t,
|
|
||||||
exist: true,
|
|
||||||
}
|
|
||||||
switch t {
|
|
||||||
case Domain:
|
|
||||||
ac.exists[node] = MatchType{
|
|
||||||
matchType: Full,
|
|
||||||
exist: true,
|
|
||||||
}
|
|
||||||
idx := char2Index['.']
|
|
||||||
if ac.trie[node][idx].nextNode == 0 {
|
|
||||||
ac.count++
|
|
||||||
if len(ac.trie) < ac.count+1 {
|
|
||||||
ac.trie = append(ac.trie, newNode())
|
|
||||||
ac.fail = append(ac.fail, 0)
|
|
||||||
ac.exists = append(ac.exists, MatchType{
|
|
||||||
matchType: Full,
|
|
||||||
exist: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
ac.trie[node][idx] = Edge{
|
|
||||||
edgeType: TrieEdge,
|
|
||||||
nextNode: ac.count,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
node = ac.trie[node][idx].nextNode
|
|
||||||
ac.exists[node] = MatchType{
|
|
||||||
matchType: t,
|
|
||||||
exist: true,
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ac *ACAutomaton) Build() {
|
|
||||||
queue := list.New()
|
|
||||||
for i := 0; i < validCharCount; i++ {
|
|
||||||
if ac.trie[0][i].nextNode != 0 {
|
|
||||||
queue.PushBack(ac.trie[0][i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for {
|
|
||||||
front := queue.Front()
|
|
||||||
if front == nil {
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
node := front.Value.(Edge).nextNode
|
|
||||||
queue.Remove(front)
|
|
||||||
for i := 0; i < validCharCount; i++ {
|
|
||||||
if ac.trie[node][i].nextNode != 0 {
|
|
||||||
ac.fail[ac.trie[node][i].nextNode] = ac.trie[ac.fail[node]][i].nextNode
|
|
||||||
queue.PushBack(ac.trie[node][i])
|
|
||||||
} else {
|
|
||||||
ac.trie[node][i] = Edge{
|
|
||||||
edgeType: FailEdge,
|
|
||||||
nextNode: ac.trie[ac.fail[node]][i].nextNode,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ac *ACAutomaton) Match(s string) bool {
|
|
||||||
node := 0
|
|
||||||
fullMatch := true
|
|
||||||
// 1. the match string is all through trie edge. FULL MATCH or DOMAIN
|
|
||||||
// 2. the match string is through a fail edge. NOT FULL MATCH
|
|
||||||
// 2.1 Through a fail edge, but there exists a valid node. SUBSTR
|
|
||||||
for i := len(s) - 1; i >= 0; i-- {
|
|
||||||
idx := char2Index[s[i]]
|
|
||||||
fullMatch = fullMatch && ac.trie[node][idx].edgeType
|
|
||||||
node = ac.trie[node][idx].nextNode
|
|
||||||
switch ac.exists[node].matchType {
|
|
||||||
case Substr:
|
|
||||||
return true
|
|
||||||
case Domain:
|
|
||||||
if fullMatch {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fullMatch && ac.exists[node].exist
|
|
||||||
}
|
|
@ -1,98 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
func breakDomain(domain string) []string {
|
|
||||||
return strings.Split(domain, ".")
|
|
||||||
}
|
|
||||||
|
|
||||||
type node struct {
|
|
||||||
values []uint32
|
|
||||||
sub map[string]*node
|
|
||||||
}
|
|
||||||
|
|
||||||
// DomainMatcherGroup is a IndexMatcher for a large set of Domain matchers.
|
|
||||||
// Visible for testing only.
|
|
||||||
type DomainMatcherGroup struct {
|
|
||||||
root *node
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *DomainMatcherGroup) Add(domain string, value uint32) {
|
|
||||||
if g.root == nil {
|
|
||||||
g.root = new(node)
|
|
||||||
}
|
|
||||||
|
|
||||||
current := g.root
|
|
||||||
parts := breakDomain(domain)
|
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
|
||||||
part := parts[i]
|
|
||||||
if current.sub == nil {
|
|
||||||
current.sub = make(map[string]*node)
|
|
||||||
}
|
|
||||||
next := current.sub[part]
|
|
||||||
if next == nil {
|
|
||||||
next = new(node)
|
|
||||||
current.sub[part] = next
|
|
||||||
}
|
|
||||||
current = next
|
|
||||||
}
|
|
||||||
|
|
||||||
current.values = append(current.values, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *DomainMatcherGroup) addMatcher(m domainMatcher, value uint32) {
|
|
||||||
g.Add(string(m), value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *DomainMatcherGroup) Match(domain string) []uint32 {
|
|
||||||
if domain == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
current := g.root
|
|
||||||
if current == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
nextPart := func(idx int) int {
|
|
||||||
for i := idx - 1; i >= 0; i-- {
|
|
||||||
if domain[i] == '.' {
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
matches := [][]uint32{}
|
|
||||||
idx := len(domain)
|
|
||||||
for {
|
|
||||||
if idx == -1 || current.sub == nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
nidx := nextPart(idx)
|
|
||||||
part := domain[nidx+1 : idx]
|
|
||||||
next := current.sub[part]
|
|
||||||
if next == nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
current = next
|
|
||||||
idx = nidx
|
|
||||||
if len(current.values) > 0 {
|
|
||||||
matches = append(matches, current.values)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch len(matches) {
|
|
||||||
case 0:
|
|
||||||
return nil
|
|
||||||
case 1:
|
|
||||||
return matches[0]
|
|
||||||
default:
|
|
||||||
result := []uint32{}
|
|
||||||
for idx := range matches {
|
|
||||||
// Insert reversely, the subdomain that matches further ranks higher
|
|
||||||
result = append(result, matches[len(matches)-1-idx]...)
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,25 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
type FullMatcherGroup struct {
|
|
||||||
matchers map[string][]uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *FullMatcherGroup) Add(domain string, value uint32) {
|
|
||||||
if g.matchers == nil {
|
|
||||||
g.matchers = make(map[string][]uint32)
|
|
||||||
}
|
|
||||||
|
|
||||||
g.matchers[domain] = append(g.matchers[domain], value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *FullMatcherGroup) addMatcher(m fullMatcher, value uint32) {
|
|
||||||
g.Add(string(m), value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *FullMatcherGroup) Match(str string) []uint32 {
|
|
||||||
if g.matchers == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return g.matchers[str]
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fullMatcher string
|
|
||||||
|
|
||||||
func (m fullMatcher) Match(s string) bool {
|
|
||||||
return string(m) == s
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fullMatcher) String() string {
|
|
||||||
return "full:" + string(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
type substrMatcher string
|
|
||||||
|
|
||||||
func (m substrMatcher) Match(s string) bool {
|
|
||||||
return strings.Contains(s, string(m))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m substrMatcher) String() string {
|
|
||||||
return "keyword:" + string(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
type domainMatcher string
|
|
||||||
|
|
||||||
func (m domainMatcher) Match(s string) bool {
|
|
||||||
pattern := string(m)
|
|
||||||
if !strings.HasSuffix(s, pattern) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return len(s) == len(pattern) || s[len(s)-len(pattern)-1] == '.'
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m domainMatcher) String() string {
|
|
||||||
return "domain:" + string(m)
|
|
||||||
}
|
|
||||||
|
|
||||||
type regexMatcher struct {
|
|
||||||
pattern *regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *regexMatcher) Match(s string) bool {
|
|
||||||
return m.pattern.MatchString(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *regexMatcher) String() string {
|
|
||||||
return "regexp:" + m.pattern.String()
|
|
||||||
}
|
|
@ -1,304 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
import (
|
|
||||||
"math/bits"
|
|
||||||
"regexp"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PrimeRK is the prime base used in Rabin-Karp algorithm.
|
|
||||||
const PrimeRK = 16777619
|
|
||||||
|
|
||||||
// calculate the rolling murmurHash of given string
|
|
||||||
func RollingHash(s string) uint32 {
|
|
||||||
h := uint32(0)
|
|
||||||
for i := len(s) - 1; i >= 0; i-- {
|
|
||||||
h = h*PrimeRK + uint32(s[i])
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
// A MphMatcherGroup is divided into three parts:
|
|
||||||
// 1. `full` and `domain` patterns are matched by Rabin-Karp algorithm and minimal perfect hash table;
|
|
||||||
// 2. `substr` patterns are matched by ac automaton;
|
|
||||||
// 3. `regex` patterns are matched with the regex library.
|
|
||||||
type MphMatcherGroup struct {
|
|
||||||
ac *ACAutomaton
|
|
||||||
otherMatchers []matcherEntry
|
|
||||||
rules []string
|
|
||||||
level0 []uint32
|
|
||||||
level0Mask int
|
|
||||||
level1 []uint32
|
|
||||||
level1Mask int
|
|
||||||
count uint32
|
|
||||||
ruleMap *map[string]uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *MphMatcherGroup) AddFullOrDomainPattern(pattern string, t Type) {
|
|
||||||
h := RollingHash(pattern)
|
|
||||||
switch t {
|
|
||||||
case Domain:
|
|
||||||
(*g.ruleMap)["."+pattern] = h*PrimeRK + uint32('.')
|
|
||||||
fallthrough
|
|
||||||
case Full:
|
|
||||||
(*g.ruleMap)[pattern] = h
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMphMatcherGroup() *MphMatcherGroup {
|
|
||||||
return &MphMatcherGroup{
|
|
||||||
ac: nil,
|
|
||||||
otherMatchers: nil,
|
|
||||||
rules: nil,
|
|
||||||
level0: nil,
|
|
||||||
level0Mask: 0,
|
|
||||||
level1: nil,
|
|
||||||
level1Mask: 0,
|
|
||||||
count: 1,
|
|
||||||
ruleMap: &map[string]uint32{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddPattern adds a pattern to MphMatcherGroup
|
|
||||||
func (g *MphMatcherGroup) AddPattern(pattern string, t Type) (uint32, error) {
|
|
||||||
switch t {
|
|
||||||
case Substr:
|
|
||||||
if g.ac == nil {
|
|
||||||
g.ac = NewACAutomaton()
|
|
||||||
}
|
|
||||||
g.ac.Add(pattern, t)
|
|
||||||
case Full, Domain:
|
|
||||||
pattern = strings.ToLower(pattern)
|
|
||||||
g.AddFullOrDomainPattern(pattern, t)
|
|
||||||
case Regex:
|
|
||||||
r, err := regexp.Compile(pattern)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
g.otherMatchers = append(g.otherMatchers, matcherEntry{
|
|
||||||
m: ®exMatcher{pattern: r},
|
|
||||||
id: g.count,
|
|
||||||
})
|
|
||||||
default:
|
|
||||||
panic("Unknown type")
|
|
||||||
}
|
|
||||||
return g.count, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build builds a minimal perfect hash table and ac automaton from insert rules
|
|
||||||
func (g *MphMatcherGroup) Build() {
|
|
||||||
if g.ac != nil {
|
|
||||||
g.ac.Build()
|
|
||||||
}
|
|
||||||
keyLen := len(*g.ruleMap)
|
|
||||||
if keyLen == 0 {
|
|
||||||
keyLen = 1
|
|
||||||
(*g.ruleMap)["empty___"] = RollingHash("empty___")
|
|
||||||
}
|
|
||||||
g.level0 = make([]uint32, nextPow2(keyLen/4))
|
|
||||||
g.level0Mask = len(g.level0) - 1
|
|
||||||
g.level1 = make([]uint32, nextPow2(keyLen))
|
|
||||||
g.level1Mask = len(g.level1) - 1
|
|
||||||
sparseBuckets := make([][]int, len(g.level0))
|
|
||||||
var ruleIdx int
|
|
||||||
for rule, hash := range *g.ruleMap {
|
|
||||||
n := int(hash) & g.level0Mask
|
|
||||||
g.rules = append(g.rules, rule)
|
|
||||||
sparseBuckets[n] = append(sparseBuckets[n], ruleIdx)
|
|
||||||
ruleIdx++
|
|
||||||
}
|
|
||||||
g.ruleMap = nil
|
|
||||||
var buckets []indexBucket
|
|
||||||
for n, vals := range sparseBuckets {
|
|
||||||
if len(vals) > 0 {
|
|
||||||
buckets = append(buckets, indexBucket{n, vals})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Sort(bySize(buckets))
|
|
||||||
|
|
||||||
occ := make([]bool, len(g.level1))
|
|
||||||
var tmpOcc []int
|
|
||||||
for _, bucket := range buckets {
|
|
||||||
seed := uint32(0)
|
|
||||||
for {
|
|
||||||
findSeed := true
|
|
||||||
tmpOcc = tmpOcc[:0]
|
|
||||||
for _, i := range bucket.vals {
|
|
||||||
n := int(strhashFallback(unsafe.Pointer(&g.rules[i]), uintptr(seed))) & g.level1Mask
|
|
||||||
if occ[n] {
|
|
||||||
for _, n := range tmpOcc {
|
|
||||||
occ[n] = false
|
|
||||||
}
|
|
||||||
seed++
|
|
||||||
findSeed = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
occ[n] = true
|
|
||||||
tmpOcc = append(tmpOcc, n)
|
|
||||||
g.level1[n] = uint32(i)
|
|
||||||
}
|
|
||||||
if findSeed {
|
|
||||||
g.level0[bucket.n] = seed
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func nextPow2(v int) int {
|
|
||||||
if v <= 1 {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
const MaxUInt = ^uint(0)
|
|
||||||
n := (MaxUInt >> bits.LeadingZeros(uint(v))) + 1
|
|
||||||
return int(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup searches for s in t and returns its index and whether it was found.
|
|
||||||
func (g *MphMatcherGroup) Lookup(h uint32, s string) bool {
|
|
||||||
i0 := int(h) & g.level0Mask
|
|
||||||
seed := g.level0[i0]
|
|
||||||
i1 := int(strhashFallback(unsafe.Pointer(&s), uintptr(seed))) & g.level1Mask
|
|
||||||
n := g.level1[i1]
|
|
||||||
return s == g.rules[int(n)]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Match implements IndexMatcher.Match.
|
|
||||||
func (g *MphMatcherGroup) Match(pattern string) []uint32 {
|
|
||||||
result := []uint32{}
|
|
||||||
hash := uint32(0)
|
|
||||||
for i := len(pattern) - 1; i >= 0; i-- {
|
|
||||||
hash = hash*PrimeRK + uint32(pattern[i])
|
|
||||||
if pattern[i] == '.' {
|
|
||||||
if g.Lookup(hash, pattern[i:]) {
|
|
||||||
result = append(result, 1)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if g.Lookup(hash, pattern) {
|
|
||||||
result = append(result, 1)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
if g.ac != nil && g.ac.Match(pattern) {
|
|
||||||
result = append(result, 1)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
for _, e := range g.otherMatchers {
|
|
||||||
if e.m.Match(pattern) {
|
|
||||||
result = append(result, e.id)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type indexBucket struct {
|
|
||||||
n int
|
|
||||||
vals []int
|
|
||||||
}
|
|
||||||
|
|
||||||
type bySize []indexBucket
|
|
||||||
|
|
||||||
func (s bySize) Len() int { return len(s) }
|
|
||||||
func (s bySize) Less(i, j int) bool { return len(s[i].vals) > len(s[j].vals) }
|
|
||||||
func (s bySize) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
|
||||||
|
|
||||||
type stringStruct struct {
|
|
||||||
str unsafe.Pointer
|
|
||||||
len int
|
|
||||||
}
|
|
||||||
|
|
||||||
func strhashFallback(a unsafe.Pointer, h uintptr) uintptr {
|
|
||||||
x := (*stringStruct)(a)
|
|
||||||
return memhashFallback(x.str, h, uintptr(x.len))
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Constants for multiplication: four random odd 64-bit numbers.
|
|
||||||
m1 = 16877499708836156737
|
|
||||||
m2 = 2820277070424839065
|
|
||||||
m3 = 9497967016996688599
|
|
||||||
m4 = 15839092249703872147
|
|
||||||
)
|
|
||||||
|
|
||||||
var hashkey = [4]uintptr{1, 1, 1, 1}
|
|
||||||
|
|
||||||
func memhashFallback(p unsafe.Pointer, seed, s uintptr) uintptr {
|
|
||||||
h := uint64(seed + s*hashkey[0])
|
|
||||||
tail:
|
|
||||||
switch {
|
|
||||||
case s == 0:
|
|
||||||
case s < 4:
|
|
||||||
h ^= uint64(*(*byte)(p))
|
|
||||||
h ^= uint64(*(*byte)(add(p, s>>1))) << 8
|
|
||||||
h ^= uint64(*(*byte)(add(p, s-1))) << 16
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
case s <= 8:
|
|
||||||
h ^= uint64(readUnaligned32(p))
|
|
||||||
h ^= uint64(readUnaligned32(add(p, s-4))) << 32
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
case s <= 16:
|
|
||||||
h ^= readUnaligned64(p)
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
h ^= readUnaligned64(add(p, s-8))
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
case s <= 32:
|
|
||||||
h ^= readUnaligned64(p)
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
h ^= readUnaligned64(add(p, 8))
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
h ^= readUnaligned64(add(p, s-16))
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
h ^= readUnaligned64(add(p, s-8))
|
|
||||||
h = rotl31(h*m1) * m2
|
|
||||||
default:
|
|
||||||
v1 := h
|
|
||||||
v2 := uint64(seed * hashkey[1])
|
|
||||||
v3 := uint64(seed * hashkey[2])
|
|
||||||
v4 := uint64(seed * hashkey[3])
|
|
||||||
for s >= 32 {
|
|
||||||
v1 ^= readUnaligned64(p)
|
|
||||||
v1 = rotl31(v1*m1) * m2
|
|
||||||
p = add(p, 8)
|
|
||||||
v2 ^= readUnaligned64(p)
|
|
||||||
v2 = rotl31(v2*m2) * m3
|
|
||||||
p = add(p, 8)
|
|
||||||
v3 ^= readUnaligned64(p)
|
|
||||||
v3 = rotl31(v3*m3) * m4
|
|
||||||
p = add(p, 8)
|
|
||||||
v4 ^= readUnaligned64(p)
|
|
||||||
v4 = rotl31(v4*m4) * m1
|
|
||||||
p = add(p, 8)
|
|
||||||
s -= 32
|
|
||||||
}
|
|
||||||
h = v1 ^ v2 ^ v3 ^ v4
|
|
||||||
goto tail
|
|
||||||
}
|
|
||||||
|
|
||||||
h ^= h >> 29
|
|
||||||
h *= m3
|
|
||||||
h ^= h >> 32
|
|
||||||
return uintptr(h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
|
|
||||||
return unsafe.Pointer(uintptr(p) + x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func readUnaligned32(p unsafe.Pointer) uint32 {
|
|
||||||
q := (*[4]byte)(p)
|
|
||||||
return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24
|
|
||||||
}
|
|
||||||
|
|
||||||
func rotl31(x uint64) uint64 {
|
|
||||||
return (x << 31) | (x >> (64 - 31))
|
|
||||||
}
|
|
||||||
|
|
||||||
func readUnaligned64(p unsafe.Pointer) uint64 {
|
|
||||||
q := (*[8]byte)(p)
|
|
||||||
return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
// Modified from: https://github.com/v2fly/v2ray-core/tree/master/common/strmatcher
|
|
||||||
// License: MIT
|
|
||||||
|
|
||||||
package strmatcher
|
|
@ -1,107 +0,0 @@
|
|||||||
package strmatcher
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Matcher is the interface to determine a string matches a pattern.
|
|
||||||
type Matcher interface {
|
|
||||||
// Match returns true if the given string matches a predefined pattern.
|
|
||||||
Match(string) bool
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Type is the type of the matcher.
|
|
||||||
type Type byte
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Full is the type of matcher that the input string must exactly equal to the pattern.
|
|
||||||
Full Type = iota
|
|
||||||
// Substr is the type of matcher that the input string must contain the pattern as a sub-string.
|
|
||||||
Substr
|
|
||||||
// Domain is the type of matcher that the input string must be a sub-domain or itself of the pattern.
|
|
||||||
Domain
|
|
||||||
// Regex is the type of matcher that the input string must matches the regular-expression pattern.
|
|
||||||
Regex
|
|
||||||
)
|
|
||||||
|
|
||||||
// New creates a new Matcher based on the given pattern.
|
|
||||||
func (t Type) New(pattern string) (Matcher, error) {
|
|
||||||
// 1. regex matching is case-sensitive
|
|
||||||
switch t {
|
|
||||||
case Full:
|
|
||||||
return fullMatcher(pattern), nil
|
|
||||||
case Substr:
|
|
||||||
return substrMatcher(pattern), nil
|
|
||||||
case Domain:
|
|
||||||
return domainMatcher(pattern), nil
|
|
||||||
case Regex:
|
|
||||||
r, err := regexp.Compile(pattern)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return ®exMatcher{
|
|
||||||
pattern: r,
|
|
||||||
}, nil
|
|
||||||
default:
|
|
||||||
panic("Unknown type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// IndexMatcher is the interface for matching with a group of matchers.
|
|
||||||
type IndexMatcher interface {
|
|
||||||
// Match returns the index of a matcher that matches the input. It returns empty array if no such matcher exists.
|
|
||||||
Match(input string) []uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
type matcherEntry struct {
|
|
||||||
m Matcher
|
|
||||||
id uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
// MatcherGroup is an implementation of IndexMatcher.
|
|
||||||
// Empty initialization works.
|
|
||||||
type MatcherGroup struct {
|
|
||||||
count uint32
|
|
||||||
fullMatcher FullMatcherGroup
|
|
||||||
domainMatcher DomainMatcherGroup
|
|
||||||
otherMatchers []matcherEntry
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add adds a new Matcher into the MatcherGroup, and returns its index. The index will never be 0.
|
|
||||||
func (g *MatcherGroup) Add(m Matcher) uint32 {
|
|
||||||
g.count++
|
|
||||||
c := g.count
|
|
||||||
|
|
||||||
switch tm := m.(type) {
|
|
||||||
case fullMatcher:
|
|
||||||
g.fullMatcher.addMatcher(tm, c)
|
|
||||||
case domainMatcher:
|
|
||||||
g.domainMatcher.addMatcher(tm, c)
|
|
||||||
default:
|
|
||||||
g.otherMatchers = append(g.otherMatchers, matcherEntry{
|
|
||||||
m: m,
|
|
||||||
id: c,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Match implements IndexMatcher.Match.
|
|
||||||
func (g *MatcherGroup) Match(pattern string) []uint32 {
|
|
||||||
result := []uint32{}
|
|
||||||
result = append(result, g.fullMatcher.Match(pattern)...)
|
|
||||||
result = append(result, g.domainMatcher.Match(pattern)...)
|
|
||||||
for _, e := range g.otherMatchers {
|
|
||||||
if e.m.Match(pattern) {
|
|
||||||
result = append(result, e.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// Size returns the number of matchers in the MatcherGroup.
|
|
||||||
func (g *MatcherGroup) Size() uint32 {
|
|
||||||
return g.count
|
|
||||||
}
|
|
@ -1,81 +0,0 @@
|
|||||||
package geodata
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var geoLoaderName = "memconservative"
|
|
||||||
|
|
||||||
// geoLoaderName = "standard"
|
|
||||||
|
|
||||||
func LoaderName() string {
|
|
||||||
return geoLoaderName
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetLoader(newLoader string) {
|
|
||||||
geoLoaderName = newLoader
|
|
||||||
}
|
|
||||||
|
|
||||||
func Verify(name string) bool {
|
|
||||||
switch name {
|
|
||||||
case C.GeositeName:
|
|
||||||
_, _, err := LoadGeoSiteMatcher("CN")
|
|
||||||
return err == nil
|
|
||||||
case C.GeoipName:
|
|
||||||
_, _, err := LoadGeoIPMatcher("CN")
|
|
||||||
return err == nil
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func LoadGeoSiteMatcher(countryCode string) (*router.DomainMatcher, int, error) {
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
domains, err := geoLoader.LoadGeoSite(countryCode)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
linear: linear algorithm
|
|
||||||
matcher, err := router.NewDomainMatcher(domains)
|
|
||||||
mph:minimal perfect hash algorithm
|
|
||||||
*/
|
|
||||||
matcher, err := router.NewMphMatcherGroup(domains)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return matcher, len(domains), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func LoadGeoIPMatcher(country string) (*router.GeoIPMatcher, int, error) {
|
|
||||||
geoLoader, err := GetGeoDataLoader(geoLoaderName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
records, err := geoLoader.LoadGeoIP(strings.ReplaceAll(country, "!", ""))
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
geoIP := &router.GeoIP{
|
|
||||||
CountryCode: country,
|
|
||||||
Cidr: records,
|
|
||||||
ReverseMatch: strings.Contains(country, "!"),
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher, err := router.NewGeoIPMatcher(geoIP)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return matcher, len(records), nil
|
|
||||||
}
|
|
@ -1,11 +1,12 @@
|
|||||||
package mmdb
|
package mmdb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/oschwald/geoip2-golang"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -34,7 +34,7 @@ func TestPool_MaxSize(t *testing.T) {
|
|||||||
size := 5
|
size := 5
|
||||||
pool := New(g, WithSize(size))
|
pool := New(g, WithSize(size))
|
||||||
|
|
||||||
var items []any
|
items := []any{}
|
||||||
|
|
||||||
for i := 0; i < size; i++ {
|
for i := 0; i < size; i++ {
|
||||||
item, _ := pool.Get()
|
item, _ := pool.Get()
|
||||||
|
@ -3,8 +3,6 @@ package process
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -21,49 +19,3 @@ const (
|
|||||||
func FindProcessName(network string, srcIP net.IP, srcPort int) (string, error) {
|
func FindProcessName(network string, srcIP net.IP, srcPort int) (string, error) {
|
||||||
return findProcessName(network, srcIP, srcPort)
|
return findProcessName(network, srcIP, srcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func ShouldFindProcess(metadata *C.Metadata) bool {
|
|
||||||
if metadata.Process != "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, ip := range localIPs {
|
|
||||||
if ip.Equal(metadata.SrcIP) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func AppendLocalIPs(ip ...net.IP) {
|
|
||||||
localIPs = append(ip, localIPs...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getLocalIPs() []net.IP {
|
|
||||||
ips := []net.IP{net.IPv4zero, net.IPv6zero}
|
|
||||||
|
|
||||||
netInterfaces, err := net.Interfaces()
|
|
||||||
if err != nil {
|
|
||||||
ips = append(ips, net.IPv4(127, 0, 0, 1), net.IPv6loopback)
|
|
||||||
return ips
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < len(netInterfaces); i++ {
|
|
||||||
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
|
|
||||||
adds, _ := netInterfaces[i].Addrs()
|
|
||||||
|
|
||||||
for _, address := range adds {
|
|
||||||
if ipNet, ok := address.(*net.IPNet); ok {
|
|
||||||
ips = append(ips, ipNet.IP)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ips
|
|
||||||
}
|
|
||||||
|
|
||||||
var localIPs []net.IP
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
localIPs = getLocalIPs()
|
|
||||||
}
|
|
||||||
|
@ -1,230 +0,0 @@
|
|||||||
package process
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"unicode"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62
|
|
||||||
var nativeEndian = func() binary.ByteOrder {
|
|
||||||
var x uint32 = 0x01020304
|
|
||||||
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
|
|
||||||
return binary.BigEndian
|
|
||||||
}
|
|
||||||
|
|
||||||
return binary.LittleEndian
|
|
||||||
}()
|
|
||||||
|
|
||||||
const (
|
|
||||||
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
|
||||||
socketDiagByFamily = 20
|
|
||||||
pathProc = "/proc"
|
|
||||||
)
|
|
||||||
|
|
||||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
|
||||||
inode, uid, err := resolveSocketByNetlink(network, ip, srcPort)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolveProcessNameByProcSearch(inode, uid)
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int32, int32, error) {
|
|
||||||
var family byte
|
|
||||||
var protocol byte
|
|
||||||
|
|
||||||
switch network {
|
|
||||||
case TCP:
|
|
||||||
protocol = syscall.IPPROTO_TCP
|
|
||||||
case UDP:
|
|
||||||
protocol = syscall.IPPROTO_UDP
|
|
||||||
default:
|
|
||||||
return 0, 0, ErrInvalidNetwork
|
|
||||||
}
|
|
||||||
|
|
||||||
if ip.To4() != nil {
|
|
||||||
family = syscall.AF_INET
|
|
||||||
} else {
|
|
||||||
family = syscall.AF_INET6
|
|
||||||
}
|
|
||||||
|
|
||||||
req := packSocketDiagRequest(family, protocol, ip, uint16(srcPort))
|
|
||||||
|
|
||||||
socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG)
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("dial netlink: %w", err)
|
|
||||||
}
|
|
||||||
defer syscall.Close(socket)
|
|
||||||
|
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 100})
|
|
||||||
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 100})
|
|
||||||
|
|
||||||
if err := syscall.Connect(socket, &syscall.SockaddrNetlink{
|
|
||||||
Family: syscall.AF_NETLINK,
|
|
||||||
Pad: 0,
|
|
||||||
Pid: 0,
|
|
||||||
Groups: 0,
|
|
||||||
}); err != nil {
|
|
||||||
return 0, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := syscall.Write(socket, req); err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("write request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
rb := pool.Get(pool.RelayBufferSize)
|
|
||||||
defer pool.Put(rb)
|
|
||||||
|
|
||||||
n, err := syscall.Read(socket, rb)
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("read response: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, fmt.Errorf("parse netlink message: %w", err)
|
|
||||||
} else if len(messages) == 0 {
|
|
||||||
return 0, 0, fmt.Errorf("unexcepted netlink response")
|
|
||||||
}
|
|
||||||
|
|
||||||
message := messages[0]
|
|
||||||
if message.Header.Type&syscall.NLMSG_ERROR != 0 {
|
|
||||||
return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR")
|
|
||||||
}
|
|
||||||
|
|
||||||
uid, inode := unpackSocketDiagResponse(&messages[0])
|
|
||||||
if uid < 0 || inode < 0 {
|
|
||||||
return 0, 0, fmt.Errorf("invalid uid(%d) or inode(%d)", uid, inode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return uid, inode, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint16) []byte {
|
|
||||||
s := make([]byte, 16)
|
|
||||||
|
|
||||||
if v4 := source.To4(); v4 != nil {
|
|
||||||
copy(s, v4)
|
|
||||||
} else {
|
|
||||||
copy(s, source)
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := make([]byte, sizeOfSocketDiagRequest)
|
|
||||||
|
|
||||||
nativeEndian.PutUint32(buf[0:4], sizeOfSocketDiagRequest)
|
|
||||||
nativeEndian.PutUint16(buf[4:6], socketDiagByFamily)
|
|
||||||
nativeEndian.PutUint16(buf[6:8], syscall.NLM_F_REQUEST|syscall.NLM_F_DUMP)
|
|
||||||
nativeEndian.PutUint32(buf[8:12], 0)
|
|
||||||
nativeEndian.PutUint32(buf[12:16], 0)
|
|
||||||
|
|
||||||
buf[16] = family
|
|
||||||
buf[17] = protocol
|
|
||||||
buf[18] = 0
|
|
||||||
buf[19] = 0
|
|
||||||
nativeEndian.PutUint32(buf[20:24], 0xFFFFFFFF)
|
|
||||||
|
|
||||||
binary.BigEndian.PutUint16(buf[24:26], sourcePort)
|
|
||||||
binary.BigEndian.PutUint16(buf[26:28], 0)
|
|
||||||
|
|
||||||
copy(buf[28:44], s)
|
|
||||||
copy(buf[44:60], net.IPv6zero)
|
|
||||||
|
|
||||||
nativeEndian.PutUint32(buf[60:64], 0)
|
|
||||||
nativeEndian.PutUint64(buf[64:72], 0xFFFFFFFFFFFFFFFF)
|
|
||||||
|
|
||||||
return buf
|
|
||||||
}
|
|
||||||
|
|
||||||
func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid int32) {
|
|
||||||
if len(msg.Data) < 72 {
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
data := msg.Data
|
|
||||||
|
|
||||||
uid = int32(nativeEndian.Uint32(data[64:68]))
|
|
||||||
inode = int32(nativeEndian.Uint32(data[68:72]))
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
|
|
||||||
files, err := os.ReadDir(pathProc)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
buffer := make([]byte, syscall.PathMax)
|
|
||||||
socket := []byte(fmt.Sprintf("socket:[%d]", inode))
|
|
||||||
|
|
||||||
for _, f := range files {
|
|
||||||
if !f.IsDir() || !isPid(f.Name()) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
info, err := f.Info()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if info.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
processPath := path.Join(pathProc, f.Name())
|
|
||||||
fdPath := path.Join(processPath, "fd")
|
|
||||||
|
|
||||||
fds, err := os.ReadDir(fdPath)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, fd := range fds {
|
|
||||||
n, err := syscall.Readlink(path.Join(fdPath, fd.Name()), buffer)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if bytes.Equal(buffer[:n], socket) {
|
|
||||||
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return splitCmdline(cmdline), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitCmdline(cmdline []byte) string {
|
|
||||||
cmdline = bytes.Trim(cmdline, " ")
|
|
||||||
|
|
||||||
idx := bytes.IndexFunc(cmdline, func(r rune) bool {
|
|
||||||
return unicode.IsControl(r) || unicode.IsSpace(r)
|
|
||||||
})
|
|
||||||
|
|
||||||
if idx == -1 {
|
|
||||||
return filepath.Base(string(cmdline))
|
|
||||||
}
|
|
||||||
return filepath.Base(string(cmdline[:idx]))
|
|
||||||
}
|
|
||||||
|
|
||||||
func isPid(s string) bool {
|
|
||||||
return strings.IndexFunc(s, func(r rune) bool {
|
|
||||||
return !unicode.IsDigit(r)
|
|
||||||
}) == -1
|
|
||||||
}
|
|
@ -69,7 +69,7 @@ func findProcessName(network string, ip net.IP, port int) (string, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ip.Equal(srcIP) && (network == TCP || !srcIP.IsUnspecified()) {
|
if !ip.Equal(srcIP) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
//go:build !android
|
|
||||||
|
|
||||||
package process
|
package process
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
@ -215,7 +215,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
|
|||||||
uintptr(1),
|
uintptr(1),
|
||||||
uintptr(unsafe.Pointer(&buf[0])),
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
uintptr(unsafe.Pointer(&size)),
|
uintptr(unsafe.Pointer(&size)),
|
||||||
0, 0)
|
)
|
||||||
if r1 == 0 {
|
if r1 == 0 {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
@ -132,17 +132,6 @@ func (c *CacheFile) GetFakeip(key []byte) []byte {
|
|||||||
return bucket.Get(key)
|
return bucket.Get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CacheFile) FlushFakeIP() error {
|
|
||||||
err := c.DB.Batch(func(t *bbolt.Tx) error {
|
|
||||||
bucket := t.Bucket(bucketFakeip)
|
|
||||||
if bucket == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return t.DeleteBucket(bucketFakeip)
|
|
||||||
})
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *CacheFile) Close() error {
|
func (c *CacheFile) Close() error {
|
||||||
return c.DB.Close()
|
return c.DB.Close()
|
||||||
}
|
}
|
||||||
|
12
component/resolver/defaults.go
Normal file
12
component/resolver/defaults.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
|
||||||
|
|
||||||
|
package resolver
|
||||||
|
|
||||||
|
import _ "unsafe"
|
||||||
|
|
||||||
|
//go:linkname defaultNS net.defaultNS
|
||||||
|
var defaultNS []string
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
defaultNS = []string{"114.114.114.114:53", "8.8.8.8:53"}
|
||||||
|
}
|
@ -10,10 +10,8 @@ type Enhancer interface {
|
|||||||
FakeIPEnabled() bool
|
FakeIPEnabled() bool
|
||||||
MappingEnabled() bool
|
MappingEnabled() bool
|
||||||
IsFakeIP(net.IP) bool
|
IsFakeIP(net.IP) bool
|
||||||
IsFakeBroadcastIP(net.IP) bool
|
|
||||||
IsExistFakeIP(net.IP) bool
|
IsExistFakeIP(net.IP) bool
|
||||||
FindHostByIP(net.IP) (string, bool)
|
FindHostByIP(net.IP) (string, bool)
|
||||||
FlushFakeIP() error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func FakeIPEnabled() bool {
|
func FakeIPEnabled() bool {
|
||||||
@ -40,14 +38,6 @@ func IsFakeIP(ip net.IP) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsFakeBroadcastIP(ip net.IP) bool {
|
|
||||||
if mapper := DefaultHostMapper; mapper != nil {
|
|
||||||
return mapper.IsFakeBroadcastIP(ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsExistFakeIP(ip net.IP) bool {
|
func IsExistFakeIP(ip net.IP) bool {
|
||||||
if mapper := DefaultHostMapper; mapper != nil {
|
if mapper := DefaultHostMapper; mapper != nil {
|
||||||
return mapper.IsExistFakeIP(ip)
|
return mapper.IsExistFakeIP(ip)
|
||||||
@ -63,10 +53,3 @@ func FindHostByIP(ip net.IP) (string, bool) {
|
|||||||
|
|
||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
func FlushFakeIP() error {
|
|
||||||
if mapper := DefaultHostMapper; mapper != nil {
|
|
||||||
return mapper.FlushFakeIP()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
@ -1,18 +0,0 @@
|
|||||||
package resolver
|
|
||||||
|
|
||||||
import D "github.com/miekg/dns"
|
|
||||||
|
|
||||||
var DefaultLocalServer LocalServer
|
|
||||||
|
|
||||||
type LocalServer interface {
|
|
||||||
ServeMsg(msg *D.Msg) (*D.Msg, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ServeMsg with a dns.Msg, return resolve dns.Msg
|
|
||||||
func ServeMsg(msg *D.Msg) (*D.Msg, error) {
|
|
||||||
if server := DefaultLocalServer; server != nil {
|
|
||||||
return server.ServeMsg(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, ErrIPNotFound
|
|
||||||
}
|
|
@ -15,9 +15,6 @@ var (
|
|||||||
// DefaultResolver aim to resolve ip
|
// DefaultResolver aim to resolve ip
|
||||||
DefaultResolver Resolver
|
DefaultResolver Resolver
|
||||||
|
|
||||||
// ProxyServerHostResolver resolve ip to proxies server host
|
|
||||||
ProxyServerHostResolver Resolver
|
|
||||||
|
|
||||||
// DisableIPv6 means don't resolve ipv6 host
|
// DisableIPv6 means don't resolve ipv6 host
|
||||||
// default value is true
|
// default value is true
|
||||||
DisableIPv6 = true
|
DisableIPv6 = true
|
||||||
@ -43,10 +40,6 @@ type Resolver interface {
|
|||||||
|
|
||||||
// ResolveIPv4 with a host, return ipv4
|
// ResolveIPv4 with a host, return ipv4
|
||||||
func ResolveIPv4(host string) (net.IP, error) {
|
func ResolveIPv4(host string) (net.IP, error) {
|
||||||
return ResolveIPv4WithResolver(host, DefaultResolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResolveIPv4WithResolver(host string, r Resolver) (net.IP, error) {
|
|
||||||
if node := DefaultHosts.Search(host); node != nil {
|
if node := DefaultHosts.Search(host); node != nil {
|
||||||
if ip := node.Data.(net.IP).To4(); ip != nil {
|
if ip := node.Data.(net.IP).To4(); ip != nil {
|
||||||
return ip, nil
|
return ip, nil
|
||||||
@ -61,32 +54,24 @@ func ResolveIPv4WithResolver(host string, r Resolver) (net.IP, error) {
|
|||||||
return nil, ErrIPVersion
|
return nil, ErrIPVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
if DefaultResolver != nil {
|
||||||
return r.ResolveIPv4(host)
|
return DefaultResolver.ResolveIPv4(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
defer cancel()
|
||||||
defer cancel()
|
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
||||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
|
if err != nil {
|
||||||
if err != nil {
|
return nil, err
|
||||||
return nil, err
|
} else if len(ipAddrs) == 0 {
|
||||||
} else if len(ipAddrs) == 0 {
|
return nil, ErrIPNotFound
|
||||||
return nil, ErrIPNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, ErrIPNotFound
|
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv6 with a host, return ipv6
|
// ResolveIPv6 with a host, return ipv6
|
||||||
func ResolveIPv6(host string) (net.IP, error) {
|
func ResolveIPv6(host string) (net.IP, error) {
|
||||||
return ResolveIPv6WithResolver(host, DefaultResolver)
|
|
||||||
}
|
|
||||||
|
|
||||||
func ResolveIPv6WithResolver(host string, r Resolver) (net.IP, error) {
|
|
||||||
if DisableIPv6 {
|
if DisableIPv6 {
|
||||||
return nil, ErrIPv6Disabled
|
return nil, ErrIPv6Disabled
|
||||||
}
|
}
|
||||||
@ -105,24 +90,20 @@ func ResolveIPv6WithResolver(host string, r Resolver) (net.IP, error) {
|
|||||||
return nil, ErrIPVersion
|
return nil, ErrIPVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
if r != nil {
|
if DefaultResolver != nil {
|
||||||
return r.ResolveIPv6(host)
|
return DefaultResolver.ResolveIPv6(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), DefaultDNSTimeout)
|
defer cancel()
|
||||||
defer cancel()
|
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
||||||
ipAddrs, err := net.DefaultResolver.LookupIP(ctx, "ip6", host)
|
if err != nil {
|
||||||
if err != nil {
|
return nil, err
|
||||||
return nil, err
|
} else if len(ipAddrs) == 0 {
|
||||||
} else if len(ipAddrs) == 0 {
|
return nil, ErrIPNotFound
|
||||||
return nil, ErrIPNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, ErrIPNotFound
|
return ipAddrs[rand.Intn(len(ipAddrs))], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
// ResolveIPWithResolver same as ResolveIP, but with a resolver
|
||||||
@ -145,43 +126,15 @@ func ResolveIPWithResolver(host string, r Resolver) (net.IP, error) {
|
|||||||
return ip, nil
|
return ip, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if DefaultResolver == nil {
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
||||||
ipAddr, err := net.ResolveIPAddr("ip", host)
|
if err != nil {
|
||||||
if err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipAddr.IP, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, ErrIPNotFound
|
return ipAddr.IP, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIP with a host, return ip
|
// ResolveIP with a host, return ip
|
||||||
func ResolveIP(host string) (net.IP, error) {
|
func ResolveIP(host string) (net.IP, error) {
|
||||||
return ResolveIPWithResolver(host, DefaultResolver)
|
return ResolveIPWithResolver(host, DefaultResolver)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveIPv4ProxyServerHost proxies server host only
|
|
||||||
func ResolveIPv4ProxyServerHost(host string) (net.IP, error) {
|
|
||||||
if ProxyServerHostResolver != nil {
|
|
||||||
return ResolveIPv4WithResolver(host, ProxyServerHostResolver)
|
|
||||||
}
|
|
||||||
return ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolveIPv6ProxyServerHost proxies server host only
|
|
||||||
func ResolveIPv6ProxyServerHost(host string) (net.IP, error) {
|
|
||||||
if ProxyServerHostResolver != nil {
|
|
||||||
return ResolveIPv6WithResolver(host, ProxyServerHostResolver)
|
|
||||||
}
|
|
||||||
return ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResolveProxyServerHost proxies server host only
|
|
||||||
func ResolveProxyServerHost(host string) (net.IP, error) {
|
|
||||||
if ProxyServerHostResolver != nil {
|
|
||||||
return ResolveIPWithResolver(host, ProxyServerHostResolver)
|
|
||||||
}
|
|
||||||
return ResolveIP(host)
|
|
||||||
}
|
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
package trie
|
|
||||||
|
|
||||||
import "errors"
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrorOverMaxValue = errors.New("the value don't over max value")
|
|
||||||
)
|
|
||||||
|
|
||||||
type IpCidrNode struct {
|
|
||||||
Mark bool
|
|
||||||
child map[uint32]*IpCidrNode
|
|
||||||
maxValue uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewIpCidrNode(mark bool, maxValue uint32) *IpCidrNode {
|
|
||||||
ipCidrNode := &IpCidrNode{
|
|
||||||
Mark: mark,
|
|
||||||
child: map[uint32]*IpCidrNode{},
|
|
||||||
maxValue: maxValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipCidrNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *IpCidrNode) addChild(value uint32) error {
|
|
||||||
if value > n.maxValue {
|
|
||||||
return ErrorOverMaxValue
|
|
||||||
}
|
|
||||||
|
|
||||||
n.child[value] = NewIpCidrNode(false, n.maxValue)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *IpCidrNode) hasChild(value uint32) bool {
|
|
||||||
return n.getChild(value) != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n *IpCidrNode) getChild(value uint32) *IpCidrNode {
|
|
||||||
if value <= n.maxValue {
|
|
||||||
return n.child[value]
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
@ -1,255 +0,0 @@
|
|||||||
package trie
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
type IPV6 bool
|
|
||||||
|
|
||||||
const (
|
|
||||||
ipv4GroupMaxValue = 0xFF
|
|
||||||
ipv6GroupMaxValue = 0xFFFF
|
|
||||||
)
|
|
||||||
|
|
||||||
type IpCidrTrie struct {
|
|
||||||
ipv4Trie *IpCidrNode
|
|
||||||
ipv6Trie *IpCidrNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewIpCidrTrie() *IpCidrTrie {
|
|
||||||
return &IpCidrTrie{
|
|
||||||
ipv4Trie: NewIpCidrNode(false, ipv4GroupMaxValue),
|
|
||||||
ipv6Trie: NewIpCidrNode(false, ipv6GroupMaxValue),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (trie *IpCidrTrie) AddIpCidr(ipCidr *net.IPNet) error {
|
|
||||||
subIpCidr, subCidr, isIpv4, err := ipCidrToSubIpCidr(ipCidr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sub := range subIpCidr {
|
|
||||||
addIpCidr(trie, isIpv4, sub, subCidr/8)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (trie *IpCidrTrie) AddIpCidrForString(ipCidr string) error {
|
|
||||||
_, ipNet, err := net.ParseCIDR(ipCidr)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return trie.AddIpCidr(ipNet)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (trie *IpCidrTrie) IsContain(ip net.IP) bool {
|
|
||||||
ip, isIpv4 := checkAndConverterIp(ip)
|
|
||||||
if ip == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
var groupValues []uint32
|
|
||||||
var ipCidrNode *IpCidrNode
|
|
||||||
|
|
||||||
if isIpv4 {
|
|
||||||
ipCidrNode = trie.ipv4Trie
|
|
||||||
for _, group := range ip {
|
|
||||||
groupValues = append(groupValues, uint32(group))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ipCidrNode = trie.ipv6Trie
|
|
||||||
for i := 0; i < len(ip); i += 2 {
|
|
||||||
groupValues = append(groupValues, getIpv6GroupValue(ip[i], ip[i+1]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return search(ipCidrNode, groupValues) != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (trie *IpCidrTrie) IsContainForString(ipString string) bool {
|
|
||||||
return trie.IsContain(net.ParseIP(ipString))
|
|
||||||
}
|
|
||||||
|
|
||||||
func ipCidrToSubIpCidr(ipNet *net.IPNet) ([]net.IP, int, bool, error) {
|
|
||||||
maskSize, _ := ipNet.Mask.Size()
|
|
||||||
var (
|
|
||||||
ipList []net.IP
|
|
||||||
newMaskSize int
|
|
||||||
isIpv4 bool
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
ip, isIpv4 := checkAndConverterIp(ipNet.IP)
|
|
||||||
ipList, newMaskSize, err = subIpCidr(ip, maskSize, isIpv4)
|
|
||||||
|
|
||||||
return ipList, newMaskSize, isIpv4, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func subIpCidr(ip net.IP, maskSize int, isIpv4 bool) ([]net.IP, int, error) {
|
|
||||||
var subIpCidrList []net.IP
|
|
||||||
groupSize := 8
|
|
||||||
if !isIpv4 {
|
|
||||||
groupSize = 16
|
|
||||||
}
|
|
||||||
|
|
||||||
if maskSize%groupSize == 0 {
|
|
||||||
return append(subIpCidrList, ip), maskSize, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
lastByteMaskSize := maskSize % 8
|
|
||||||
lastByteMaskIndex := maskSize / 8
|
|
||||||
subIpCidrNum := 0xFF >> lastByteMaskSize
|
|
||||||
for i := 0; i <= subIpCidrNum; i++ {
|
|
||||||
subIpCidr := make([]byte, len(ip))
|
|
||||||
copy(subIpCidr, ip)
|
|
||||||
subIpCidr[lastByteMaskIndex] += byte(i)
|
|
||||||
subIpCidrList = append(subIpCidrList, subIpCidr)
|
|
||||||
}
|
|
||||||
|
|
||||||
newMaskSize := (lastByteMaskIndex + 1) * 8
|
|
||||||
if !isIpv4 {
|
|
||||||
newMaskSize = (lastByteMaskIndex/2 + 1) * 16
|
|
||||||
}
|
|
||||||
|
|
||||||
return subIpCidrList, newMaskSize, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func addIpCidr(trie *IpCidrTrie, isIpv4 bool, ip net.IP, groupSize int) {
|
|
||||||
if isIpv4 {
|
|
||||||
addIpv4Cidr(trie, ip, groupSize)
|
|
||||||
} else {
|
|
||||||
addIpv6Cidr(trie, ip, groupSize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func addIpv4Cidr(trie *IpCidrTrie, ip net.IP, groupSize int) {
|
|
||||||
preNode := trie.ipv4Trie
|
|
||||||
node := preNode.getChild(uint32(ip[0]))
|
|
||||||
if node == nil {
|
|
||||||
err := preNode.addChild(uint32(ip[0]))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
node = preNode.getChild(uint32(ip[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 1; i < groupSize; i++ {
|
|
||||||
if node.Mark {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
groupValue := uint32(ip[i])
|
|
||||||
if !node.hasChild(groupValue) {
|
|
||||||
err := node.addChild(groupValue)
|
|
||||||
if err != nil {
|
|
||||||
log.Errorln(err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
preNode = node
|
|
||||||
node = node.getChild(groupValue)
|
|
||||||
if node == nil {
|
|
||||||
err := preNode.addChild(uint32(ip[i-1]))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
node = preNode.getChild(uint32(ip[i-1]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
node.Mark = true
|
|
||||||
cleanChild(node)
|
|
||||||
}
|
|
||||||
|
|
||||||
func addIpv6Cidr(trie *IpCidrTrie, ip net.IP, groupSize int) {
|
|
||||||
preNode := trie.ipv6Trie
|
|
||||||
node := preNode.getChild(getIpv6GroupValue(ip[0], ip[1]))
|
|
||||||
if node == nil {
|
|
||||||
err := preNode.addChild(getIpv6GroupValue(ip[0], ip[1]))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
node = preNode.getChild(getIpv6GroupValue(ip[0], ip[1]))
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 2; i < groupSize; i += 2 {
|
|
||||||
if node.Mark {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
groupValue := getIpv6GroupValue(ip[i], ip[i+1])
|
|
||||||
if !node.hasChild(groupValue) {
|
|
||||||
err := node.addChild(groupValue)
|
|
||||||
if err != nil {
|
|
||||||
log.Errorln(err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
preNode = node
|
|
||||||
node = node.getChild(groupValue)
|
|
||||||
if node == nil {
|
|
||||||
err := preNode.addChild(getIpv6GroupValue(ip[i-2], ip[i-1]))
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
node = preNode.getChild(getIpv6GroupValue(ip[i-2], ip[i-1]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
node.Mark = true
|
|
||||||
cleanChild(node)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getIpv6GroupValue(high, low byte) uint32 {
|
|
||||||
return (uint32(high) << 8) | uint32(low)
|
|
||||||
}
|
|
||||||
|
|
||||||
func cleanChild(node *IpCidrNode) {
|
|
||||||
for i := uint32(0); i < uint32(len(node.child)); i++ {
|
|
||||||
delete(node.child, i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func search(root *IpCidrNode, groupValues []uint32) *IpCidrNode {
|
|
||||||
node := root.getChild(groupValues[0])
|
|
||||||
if node == nil || node.Mark {
|
|
||||||
return node
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, value := range groupValues[1:] {
|
|
||||||
if !node.hasChild(value) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
node = node.getChild(value)
|
|
||||||
|
|
||||||
if node == nil || node.Mark {
|
|
||||||
return node
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// return net.IP To4 or To16 and is ipv4
|
|
||||||
func checkAndConverterIp(ip net.IP) (net.IP, bool) {
|
|
||||||
ipResult := ip.To4()
|
|
||||||
if ipResult == nil {
|
|
||||||
ipResult = ip.To16()
|
|
||||||
if ipResult == nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipResult, false
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipResult, true
|
|
||||||
}
|
|
@ -1,100 +0,0 @@
|
|||||||
package trie
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
import "github.com/stretchr/testify/assert"
|
|
||||||
|
|
||||||
func TestIpv4AddSuccess(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
err := trie.AddIpCidrForString("10.0.0.2/16")
|
|
||||||
assert.Equal(t, nil, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv4AddFail(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
err := trie.AddIpCidrForString("333.00.23.2/23")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
|
|
||||||
err = trie.AddIpCidrForString("22.3.34.2/222")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
|
|
||||||
err = trie.AddIpCidrForString("2.2.2.2")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv4Search(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
// Boundary testing
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("149.154.160.0/20"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("149.154.160.0"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("149.154.175.255"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("149.154.176.0"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("149.154.159.255"))
|
|
||||||
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("129.2.36.0/16"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("10.2.36.0/18"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("16.2.23.0/24"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("11.2.13.2/26"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("55.5.6.3/8"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("66.23.25.4/6"))
|
|
||||||
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("129.2.3.65"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("15.2.3.1"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("11.2.13.1"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("55.0.0.0"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("64.0.0.0"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("128.0.0.0"))
|
|
||||||
|
|
||||||
assert.Equal(t, false, trie.IsContain(net.ParseIP("22")))
|
|
||||||
assert.Equal(t, false, trie.IsContain(net.ParseIP("")))
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv6AddSuccess(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
err := trie.AddIpCidrForString("2001:0db8:02de:0000:0000:0000:0000:0e13/32")
|
|
||||||
assert.Equal(t, nil, err)
|
|
||||||
|
|
||||||
err = trie.AddIpCidrForString("2001:1db8:f2de::0e13/18")
|
|
||||||
assert.Equal(t, nil, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv6AddFail(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
err := trie.AddIpCidrForString("2001::25de::cade/23")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
|
|
||||||
err = trie.AddIpCidrForString("2001:0fa3:25de::cade/222")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
|
|
||||||
err = trie.AddIpCidrForString("2001:0fa3:25de::cade")
|
|
||||||
assert.IsType(t, new(net.ParseError), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIpv6Search(t *testing.T) {
|
|
||||||
trie := NewIpCidrTrie()
|
|
||||||
|
|
||||||
// Boundary testing
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2a0a:f280::/32"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2a0a:f280:0000:0000:0000:0000:0000:0000"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2a0a:f280:ffff:ffff:ffff:ffff:ffff:ffff"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("2a0a:f279:ffff:ffff:ffff:ffff:ffff:ffff"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("2a0a:f281:0000:0000:0000:0000:0000:0000"))
|
|
||||||
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23d:f001::e/128"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f002::e/12"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23d:f003::e/96"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f002::a/32"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:67c:4e8:f004::a/60"))
|
|
||||||
assert.NoError(t, trie.AddIpCidrForString("2001:b28:f23f:f005::a/64"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2001:b28:f23d:f001::e"))
|
|
||||||
assert.Equal(t, false, trie.IsContainForString("2222::fff2"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2000::ffa0"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2001:b28:f23f:f005:5662::"))
|
|
||||||
assert.Equal(t, true, trie.IsContainForString("2001:67c:4e8:9666::1213"))
|
|
||||||
|
|
||||||
assert.Equal(t, false, trie.IsContain(net.ParseIP("22233:22")))
|
|
||||||
|
|
||||||
}
|
|
474
config/config.go
474
config/config.go
@ -1,54 +1,42 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"container/list"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
R "github.com/Dreamacro/clash/rule"
|
|
||||||
RP "github.com/Dreamacro/clash/rule/provider"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/adapter/outboundgroup"
|
"github.com/Dreamacro/clash/adapter/outboundgroup"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
"github.com/Dreamacro/clash/component/auth"
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
"github.com/Dreamacro/clash/component/fakeip"
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
"github.com/Dreamacro/clash/component/geodata"
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
"github.com/Dreamacro/clash/component/trie"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
providerTypes "github.com/Dreamacro/clash/constant/provider"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
"github.com/Dreamacro/clash/listener/tun/ipstack/commons"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
R "github.com/Dreamacro/clash/rule"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// General config
|
// General config
|
||||||
type General struct {
|
type General struct {
|
||||||
Inbound
|
Inbound
|
||||||
Controller
|
Controller
|
||||||
Mode T.TunnelMode `json:"mode"`
|
Mode T.TunnelMode `json:"mode"`
|
||||||
UnifiedDelay bool
|
LogLevel log.LogLevel `json:"log-level"`
|
||||||
LogLevel log.LogLevel `json:"log-level"`
|
IPv6 bool `json:"ipv6"`
|
||||||
IPv6 bool `json:"ipv6"`
|
Interface string `json:"-"`
|
||||||
Interface string `json:"-"`
|
RoutingMark int `json:"-"`
|
||||||
RoutingMark int `json:"-"`
|
|
||||||
GeodataMode bool `json:"geodata-mode"`
|
|
||||||
GeodataLoader string `json:"geodata-loader"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inbound config
|
// Inbound
|
||||||
type Inbound struct {
|
type Inbound struct {
|
||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
SocksPort int `json:"socks-port"`
|
SocksPort int `json:"socks-port"`
|
||||||
@ -60,7 +48,7 @@ type Inbound struct {
|
|||||||
BindAddress string `json:"bind-address"`
|
BindAddress string `json:"bind-address"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Controller config
|
// Controller
|
||||||
type Controller struct {
|
type Controller struct {
|
||||||
ExternalController string `json:"-"`
|
ExternalController string `json:"-"`
|
||||||
ExternalUI string `json:"-"`
|
ExternalUI string `json:"-"`
|
||||||
@ -69,96 +57,62 @@ type Controller struct {
|
|||||||
|
|
||||||
// DNS config
|
// DNS config
|
||||||
type DNS struct {
|
type DNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
NameServer []dns.NameServer `yaml:"nameserver"`
|
NameServer []dns.NameServer `yaml:"nameserver"`
|
||||||
Fallback []dns.NameServer `yaml:"fallback"`
|
Fallback []dns.NameServer `yaml:"fallback"`
|
||||||
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
FallbackFilter FallbackFilter `yaml:"fallback-filter"`
|
||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen"`
|
||||||
EnhancedMode C.DNSMode `yaml:"enhanced-mode"`
|
EnhancedMode C.DNSMode `yaml:"enhanced-mode"`
|
||||||
DefaultNameserver []dns.NameServer `yaml:"default-nameserver"`
|
DefaultNameserver []dns.NameServer `yaml:"default-nameserver"`
|
||||||
FakeIPRange *fakeip.Pool
|
FakeIPRange *fakeip.Pool
|
||||||
Hosts *trie.DomainTrie
|
Hosts *trie.DomainTrie
|
||||||
NameServerPolicy map[string]dns.NameServer
|
NameServerPolicy map[string]dns.NameServer
|
||||||
ProxyServerNameserver []dns.NameServer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// FallbackFilter config
|
// FallbackFilter config
|
||||||
type FallbackFilter struct {
|
type FallbackFilter struct {
|
||||||
GeoIP bool `yaml:"geoip"`
|
GeoIP bool `yaml:"geoip"`
|
||||||
GeoIPCode string `yaml:"geoip-code"`
|
GeoIPCode string `yaml:"geoip-code"`
|
||||||
IPCIDR []*net.IPNet `yaml:"ipcidr"`
|
IPCIDR []*net.IPNet `yaml:"ipcidr"`
|
||||||
Domain []string `yaml:"domain"`
|
Domain []string `yaml:"domain"`
|
||||||
GeoSite []*router.DomainMatcher `yaml:"geosite"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
|
||||||
GroupsList = list.New()
|
|
||||||
ProxiesList = list.New()
|
|
||||||
ParsingProxiesCallback func(groupsList *list.List, proxiesList *list.List)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Profile config
|
// Profile config
|
||||||
type Profile struct {
|
type Profile struct {
|
||||||
StoreSelected bool `yaml:"store-selected"`
|
StoreSelected bool `yaml:"store-selected"`
|
||||||
StoreFakeIP bool `yaml:"store-fake-ip"`
|
StoreFakeIP bool `yaml:"store-fake-ip"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tun config
|
|
||||||
type Tun struct {
|
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
|
||||||
Device string `yaml:"device" json:"device"`
|
|
||||||
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
|
||||||
DNSHijack []netip.AddrPort `yaml:"dns-hijack" json:"dns-hijack"`
|
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Script config
|
|
||||||
type Script struct {
|
|
||||||
MainCode string `yaml:"code" json:"code"`
|
|
||||||
ShortcutsCode map[string]string `yaml:"shortcuts" json:"shortcuts"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPTables config
|
|
||||||
type IPTables struct {
|
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
|
||||||
InboundInterface string `yaml:"inbound-interface" json:"inbound-interface"`
|
|
||||||
Bypass []string `yaml:"bypass" json:"bypass"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Experimental config
|
// Experimental config
|
||||||
type Experimental struct{}
|
type Experimental struct{}
|
||||||
|
|
||||||
// Config is clash config manager
|
// Config is clash config manager
|
||||||
type Config struct {
|
type Config struct {
|
||||||
General *General
|
General *General
|
||||||
Tun *Tun
|
DNS *DNS
|
||||||
IPTables *IPTables
|
Experimental *Experimental
|
||||||
DNS *DNS
|
Hosts *trie.DomainTrie
|
||||||
Experimental *Experimental
|
Profile *Profile
|
||||||
Hosts *trie.DomainTrie
|
Rules []C.Rule
|
||||||
Profile *Profile
|
Users []auth.AuthUser
|
||||||
Rules []C.Rule
|
Proxies map[string]C.Proxy
|
||||||
Users []auth.AuthUser
|
Providers map[string]providerTypes.ProxyProvider
|
||||||
Proxies map[string]C.Proxy
|
|
||||||
Providers map[string]providerTypes.ProxyProvider
|
|
||||||
RuleProviders map[string]*providerTypes.RuleProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawDNS struct {
|
type RawDNS struct {
|
||||||
Enable bool `yaml:"enable"`
|
Enable bool `yaml:"enable"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
UseHosts bool `yaml:"use-hosts"`
|
UseHosts bool `yaml:"use-hosts"`
|
||||||
NameServer []string `yaml:"nameserver"`
|
NameServer []string `yaml:"nameserver"`
|
||||||
Fallback []string `yaml:"fallback"`
|
Fallback []string `yaml:"fallback"`
|
||||||
FallbackFilter RawFallbackFilter `yaml:"fallback-filter"`
|
FallbackFilter RawFallbackFilter `yaml:"fallback-filter"`
|
||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen"`
|
||||||
EnhancedMode C.DNSMode `yaml:"enhanced-mode"`
|
EnhancedMode C.DNSMode `yaml:"enhanced-mode"`
|
||||||
FakeIPRange string `yaml:"fake-ip-range"`
|
FakeIPRange string `yaml:"fake-ip-range"`
|
||||||
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
||||||
DefaultNameserver []string `yaml:"default-nameserver"`
|
DefaultNameserver []string `yaml:"default-nameserver"`
|
||||||
NameServerPolicy map[string]string `yaml:"nameserver-policy"`
|
NameServerPolicy map[string]string `yaml:"nameserver-policy"`
|
||||||
ProxyServerNameserver []string `yaml:"proxy-server-nameserver"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawFallbackFilter struct {
|
type RawFallbackFilter struct {
|
||||||
@ -166,15 +120,6 @@ type RawFallbackFilter struct {
|
|||||||
GeoIPCode string `yaml:"geoip-code"`
|
GeoIPCode string `yaml:"geoip-code"`
|
||||||
IPCIDR []string `yaml:"ipcidr"`
|
IPCIDR []string `yaml:"ipcidr"`
|
||||||
Domain []string `yaml:"domain"`
|
Domain []string `yaml:"domain"`
|
||||||
GeoSite []string `yaml:"geosite"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type RawTun struct {
|
|
||||||
Enable bool `yaml:"enable" json:"enable"`
|
|
||||||
Device string `yaml:"device" json:"device"`
|
|
||||||
Stack C.TUNStack `yaml:"stack" json:"stack"`
|
|
||||||
DNSHijack []string `yaml:"dns-hijack" json:"dns-hijack"`
|
|
||||||
AutoRoute bool `yaml:"auto-route" json:"auto-route"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type RawConfig struct {
|
type RawConfig struct {
|
||||||
@ -187,7 +132,6 @@ type RawConfig struct {
|
|||||||
AllowLan bool `yaml:"allow-lan"`
|
AllowLan bool `yaml:"allow-lan"`
|
||||||
BindAddress string `yaml:"bind-address"`
|
BindAddress string `yaml:"bind-address"`
|
||||||
Mode T.TunnelMode `yaml:"mode"`
|
Mode T.TunnelMode `yaml:"mode"`
|
||||||
UnifiedDelay bool `yaml:"unified-delay"`
|
|
||||||
LogLevel log.LogLevel `yaml:"log-level"`
|
LogLevel log.LogLevel `yaml:"log-level"`
|
||||||
IPv6 bool `yaml:"ipv6"`
|
IPv6 bool `yaml:"ipv6"`
|
||||||
ExternalController string `yaml:"external-controller"`
|
ExternalController string `yaml:"external-controller"`
|
||||||
@ -195,15 +139,10 @@ type RawConfig struct {
|
|||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
Interface string `yaml:"interface-name"`
|
Interface string `yaml:"interface-name"`
|
||||||
RoutingMark int `yaml:"routing-mark"`
|
RoutingMark int `yaml:"routing-mark"`
|
||||||
GeodataMode bool `yaml:"geodata-mode"`
|
|
||||||
GeodataLoader string `yaml:"geodata-loader"`
|
|
||||||
|
|
||||||
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
ProxyProvider map[string]map[string]any `yaml:"proxy-providers"`
|
||||||
RuleProvider map[string]map[string]any `yaml:"rule-providers"`
|
|
||||||
Hosts map[string]string `yaml:"hosts"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
DNS RawDNS `yaml:"dns"`
|
DNS RawDNS `yaml:"dns"`
|
||||||
Tun RawTun `yaml:"tun"`
|
|
||||||
IPTables IPTables `yaml:"iptables"`
|
|
||||||
Experimental Experimental `yaml:"experimental"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
Profile Profile `yaml:"profile"`
|
Profile Profile `yaml:"profile"`
|
||||||
Proxy []map[string]any `yaml:"proxies"`
|
Proxy []map[string]any `yaml:"proxies"`
|
||||||
@ -227,52 +166,24 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
AllowLan: false,
|
AllowLan: false,
|
||||||
BindAddress: "*",
|
BindAddress: "*",
|
||||||
Mode: T.Rule,
|
Mode: T.Rule,
|
||||||
GeodataMode: C.GeodataMode,
|
|
||||||
GeodataLoader: "memconservative",
|
|
||||||
UnifiedDelay: false,
|
|
||||||
Authentication: []string{},
|
Authentication: []string{},
|
||||||
LogLevel: log.INFO,
|
LogLevel: log.INFO,
|
||||||
Hosts: map[string]string{},
|
Hosts: map[string]string{},
|
||||||
Rule: []string{},
|
Rule: []string{},
|
||||||
Proxy: []map[string]any{},
|
Proxy: []map[string]any{},
|
||||||
ProxyGroup: []map[string]any{},
|
ProxyGroup: []map[string]any{},
|
||||||
Tun: RawTun{
|
|
||||||
Enable: false,
|
|
||||||
Device: "",
|
|
||||||
Stack: C.TunGvisor,
|
|
||||||
DNSHijack: []string{"0.0.0.0:53"}, // default hijack all dns query
|
|
||||||
AutoRoute: true,
|
|
||||||
},
|
|
||||||
IPTables: IPTables{
|
|
||||||
Enable: false,
|
|
||||||
InboundInterface: "lo",
|
|
||||||
Bypass: []string{},
|
|
||||||
},
|
|
||||||
DNS: RawDNS{
|
DNS: RawDNS{
|
||||||
Enable: false,
|
Enable: false,
|
||||||
UseHosts: true,
|
UseHosts: true,
|
||||||
EnhancedMode: C.DNSMapping,
|
FakeIPRange: "198.18.0.1/16",
|
||||||
FakeIPRange: "198.18.0.1/16",
|
|
||||||
FallbackFilter: RawFallbackFilter{
|
FallbackFilter: RawFallbackFilter{
|
||||||
GeoIP: true,
|
GeoIP: true,
|
||||||
GeoIPCode: "CN",
|
GeoIPCode: "CN",
|
||||||
IPCIDR: []string{},
|
IPCIDR: []string{},
|
||||||
GeoSite: []string{},
|
|
||||||
},
|
},
|
||||||
DefaultNameserver: []string{
|
DefaultNameserver: []string{
|
||||||
"114.114.114.114",
|
"114.114.114.114",
|
||||||
"223.5.5.5",
|
|
||||||
"8.8.8.8",
|
"8.8.8.8",
|
||||||
"1.0.0.1",
|
|
||||||
},
|
|
||||||
NameServer: []string{
|
|
||||||
"https://doh.pub/dns-query",
|
|
||||||
"tls://223.5.5.5:853",
|
|
||||||
},
|
|
||||||
FakeIPFilter: []string{
|
|
||||||
"dns.msftnsci.com",
|
|
||||||
"www.msftnsci.com",
|
|
||||||
"www.msftconnecttest.com",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Profile: Profile{
|
Profile: Profile{
|
||||||
@ -289,11 +200,9 @@ func UnmarshalRawConfig(buf []byte) (*RawConfig, error) {
|
|||||||
|
|
||||||
func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
||||||
config := &Config{}
|
config := &Config{}
|
||||||
log.Infoln("Start initial configuration in progress") //Segment finished in xxm
|
|
||||||
startTime := time.Now()
|
|
||||||
config.Experimental = &rawCfg.Experimental
|
config.Experimental = &rawCfg.Experimental
|
||||||
config.Profile = &rawCfg.Profile
|
config.Profile = &rawCfg.Profile
|
||||||
config.IPTables = &rawCfg.IPTables
|
|
||||||
|
|
||||||
general, err := parseGeneral(rawCfg)
|
general, err := parseGeneral(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -301,14 +210,6 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.General = general
|
config.General = general
|
||||||
|
|
||||||
tunCfg, err := parseTun(rawCfg.Tun, config.General)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
config.Tun = tunCfg
|
|
||||||
|
|
||||||
dialer.DefaultInterface.Store(config.General.Interface)
|
|
||||||
|
|
||||||
proxies, providers, err := parseProxies(rawCfg)
|
proxies, providers, err := parseProxies(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -316,12 +217,11 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
config.Providers = providers
|
config.Providers = providers
|
||||||
|
|
||||||
rules, ruleProviders, err := parseRules(rawCfg, proxies)
|
rules, err := parseRules(rawCfg, proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Rules = rules
|
config.Rules = rules
|
||||||
config.RuleProviders = ruleProviders
|
|
||||||
|
|
||||||
hosts, err := parseHosts(rawCfg)
|
hosts, err := parseHosts(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -329,7 +229,7 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.Hosts = hosts
|
config.Hosts = hosts
|
||||||
|
|
||||||
dnsCfg, err := parseDNS(rawCfg, hosts, rules)
|
dnsCfg, err := parseDNS(rawCfg, hosts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -337,14 +237,12 @@ func ParseRawConfig(rawCfg *RawConfig) (*Config, error) {
|
|||||||
|
|
||||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
elapsedTime := time.Since(startTime) / time.Millisecond // duration in ms
|
|
||||||
log.Infoln("Initial configuration complete, total time: %dms", elapsedTime) //Segment finished in xxm
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseGeneral(cfg *RawConfig) (*General, error) {
|
func parseGeneral(cfg *RawConfig) (*General, error) {
|
||||||
externalUI := cfg.ExternalUI
|
externalUI := cfg.ExternalUI
|
||||||
geodata.SetLoader(cfg.GeodataLoader)
|
|
||||||
// checkout externalUI exist
|
// checkout externalUI exist
|
||||||
if externalUI != "" {
|
if externalUI != "" {
|
||||||
externalUI = C.Path.Resolve(externalUI)
|
externalUI = C.Path.Resolve(externalUI)
|
||||||
@ -369,32 +267,24 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
|
|||||||
ExternalUI: cfg.ExternalUI,
|
ExternalUI: cfg.ExternalUI,
|
||||||
Secret: cfg.Secret,
|
Secret: cfg.Secret,
|
||||||
},
|
},
|
||||||
UnifiedDelay: cfg.UnifiedDelay,
|
Mode: cfg.Mode,
|
||||||
Mode: cfg.Mode,
|
LogLevel: cfg.LogLevel,
|
||||||
LogLevel: cfg.LogLevel,
|
IPv6: cfg.IPv6,
|
||||||
IPv6: cfg.IPv6,
|
Interface: cfg.Interface,
|
||||||
Interface: cfg.Interface,
|
RoutingMark: cfg.RoutingMark,
|
||||||
RoutingMark: cfg.RoutingMark,
|
|
||||||
GeodataMode: cfg.GeodataMode,
|
|
||||||
GeodataLoader: cfg.GeodataLoader,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) {
|
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) {
|
||||||
proxies = make(map[string]C.Proxy)
|
proxies = make(map[string]C.Proxy)
|
||||||
providersMap = make(map[string]providerTypes.ProxyProvider)
|
providersMap = make(map[string]providerTypes.ProxyProvider)
|
||||||
|
proxyList := []string{}
|
||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
providersConfig := cfg.ProxyProvider
|
providersConfig := cfg.ProxyProvider
|
||||||
|
|
||||||
var proxyList []string
|
|
||||||
_proxiesList := list.New()
|
|
||||||
_groupsList := list.New()
|
|
||||||
|
|
||||||
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
|
||||||
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
|
||||||
proxies["COMPATIBLE"] = adapter.NewProxy(outbound.NewCompatible())
|
|
||||||
proxies["PASS"] = adapter.NewProxy(outbound.NewPass())
|
|
||||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||||
|
|
||||||
// parse proxy
|
// parse proxy
|
||||||
@ -409,7 +299,6 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
}
|
}
|
||||||
proxies[proxy.Name()] = proxy
|
proxies[proxy.Name()] = proxy
|
||||||
proxyList = append(proxyList, proxy.Name())
|
proxyList = append(proxyList, proxy.Name())
|
||||||
_proxiesList.PushBack(mapping)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// keep the original order of ProxyGroups in config file
|
// keep the original order of ProxyGroups in config file
|
||||||
@ -419,7 +308,6 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
return nil, nil, fmt.Errorf("proxy group %d: missing name", idx)
|
||||||
}
|
}
|
||||||
proxyList = append(proxyList, groupName)
|
proxyList = append(proxyList, groupName)
|
||||||
_groupsList.PushBack(mapping)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if any loop exists and sort the ProxyGroups
|
// check if any loop exists and sort the ProxyGroups
|
||||||
@ -441,6 +329,13 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
providersMap[name] = pd
|
providersMap[name] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, provider := range providersMap {
|
||||||
|
log.Infoln("Start initial provider %s", provider.Name())
|
||||||
|
if err := provider.Initial(); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("initial proxy provider %s error: %w", provider.Name(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// parse proxy group
|
// parse proxy group
|
||||||
for idx, mapping := range groupsConfig {
|
for idx, mapping := range groupsConfig {
|
||||||
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
||||||
@ -456,11 +351,20 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
proxies[groupName] = adapter.NewProxy(group)
|
proxies[groupName] = adapter.NewProxy(group)
|
||||||
}
|
}
|
||||||
|
|
||||||
var ps []C.Proxy
|
// initial compatible provider
|
||||||
for _, v := range proxyList {
|
for _, pd := range providersMap {
|
||||||
if proxies[v].Type() == C.Pass {
|
if pd.VehicleType() != providerTypes.Compatible {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Infoln("Start initial compatible provider %s", pd.Name())
|
||||||
|
if err := pd.Initial(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ps := []C.Proxy{}
|
||||||
|
for _, v := range proxyList {
|
||||||
ps = append(ps, proxies[v])
|
ps = append(ps, proxies[v])
|
||||||
}
|
}
|
||||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
hc := provider.NewHealthCheck(ps, "", 0, true)
|
||||||
@ -474,95 +378,52 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
|
|||||||
[]providerTypes.ProxyProvider{pd},
|
[]providerTypes.ProxyProvider{pd},
|
||||||
)
|
)
|
||||||
proxies["GLOBAL"] = adapter.NewProxy(global)
|
proxies["GLOBAL"] = adapter.NewProxy(global)
|
||||||
ProxiesList = _proxiesList
|
|
||||||
GroupsList = _groupsList
|
|
||||||
if ParsingProxiesCallback != nil {
|
|
||||||
// refresh tray menu
|
|
||||||
go ParsingProxiesCallback(GroupsList, ProxiesList)
|
|
||||||
}
|
|
||||||
return proxies, providersMap, nil
|
return proxies, providersMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, map[string]*providerTypes.RuleProvider, error) {
|
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
||||||
ruleProviders := map[string]*providerTypes.RuleProvider{}
|
rules := []C.Rule{}
|
||||||
log.Infoln("Geodata Loader mode: %s", geodata.LoaderName())
|
|
||||||
// parse rule provider
|
|
||||||
for name, mapping := range cfg.RuleProvider {
|
|
||||||
rp, err := RP.ParseRuleProvider(name, mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
ruleProviders[name] = &rp
|
|
||||||
RP.SetRuleProvider(rp)
|
|
||||||
}
|
|
||||||
|
|
||||||
var rules []C.Rule
|
|
||||||
rulesConfig := cfg.Rule
|
rulesConfig := cfg.Rule
|
||||||
mode := cfg.Mode
|
|
||||||
|
|
||||||
// parse rules
|
// parse rules
|
||||||
for idx, line := range rulesConfig {
|
for idx, line := range rulesConfig {
|
||||||
rule := trimArr(strings.Split(line, ","))
|
rule := trimArr(strings.Split(line, ","))
|
||||||
var (
|
var (
|
||||||
payload string
|
payload string
|
||||||
target string
|
target string
|
||||||
params []string
|
params = []string{}
|
||||||
ruleName = strings.ToUpper(rule[0])
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if mode == T.Script && ruleName != "GEOSITE" {
|
switch l := len(rule); {
|
||||||
continue
|
case l == 2:
|
||||||
|
target = rule[1]
|
||||||
|
case l == 3:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
case l >= 4:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
params = rule[3:]
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
||||||
}
|
}
|
||||||
|
|
||||||
l := len(rule)
|
if _, ok := proxies[target]; !ok {
|
||||||
|
return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
||||||
if ruleName == "NOT" || ruleName == "OR" || ruleName == "AND" {
|
|
||||||
target = rule[l-1]
|
|
||||||
payload = strings.Join(rule[1:l-1], ",")
|
|
||||||
} else {
|
|
||||||
if l < 2 {
|
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
|
|
||||||
}
|
|
||||||
if l < 4 {
|
|
||||||
rule = append(rule, make([]string, 4-l)...)
|
|
||||||
}
|
|
||||||
if ruleName == "MATCH" {
|
|
||||||
l = 2
|
|
||||||
}
|
|
||||||
if l >= 3 {
|
|
||||||
l = 3
|
|
||||||
payload = rule[1]
|
|
||||||
}
|
|
||||||
target = rule[l-1]
|
|
||||||
params = rule[l:]
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := proxies[target]; mode != T.Script && !ok {
|
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
rule = trimArr(rule)
|
||||||
params = trimArr(params)
|
params = trimArr(params)
|
||||||
|
|
||||||
if ruleName == "GEOSITE" {
|
parsed, parseErr := R.ParseRule(rule[0], payload, target, params)
|
||||||
if err := initGeoSite(); err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
|
||||||
}
|
|
||||||
initMode = false
|
|
||||||
}
|
|
||||||
parsed, parseErr := R.ParseRule(ruleName, payload, target, params)
|
|
||||||
if parseErr != nil {
|
if parseErr != nil {
|
||||||
return nil, nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
return nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if mode != T.Script {
|
rules = append(rules, parsed)
|
||||||
rules = append(rules, parsed)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
runtime.GC()
|
return rules, nil
|
||||||
|
|
||||||
return rules, ruleProviders, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseHosts(cfg *RawConfig) (*trie.DomainTrie, error) {
|
func parseHosts(cfg *RawConfig) (*trie.DomainTrie, error) {
|
||||||
@ -579,7 +440,7 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie, error) {
|
|||||||
if ip == nil {
|
if ip == nil {
|
||||||
return nil, fmt.Errorf("%s is not a valid IP", ipStr)
|
return nil, fmt.Errorf("%s is not a valid IP", ipStr)
|
||||||
}
|
}
|
||||||
_ = tree.Insert(domain, ip)
|
tree.Insert(domain, ip)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -604,7 +465,7 @@ func hostWithDefaultPort(host string, defPort string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
||||||
var nameservers []dns.NameServer
|
nameservers := []dns.NameServer{}
|
||||||
|
|
||||||
for idx, server := range servers {
|
for idx, server := range servers {
|
||||||
// parse without scheme .e.g 8.8.8.8:53
|
// parse without scheme .e.g 8.8.8.8:53
|
||||||
@ -616,6 +477,10 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
return nil, fmt.Errorf("DNS NameServer[%d] format error: %s", idx, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parse with specific interface
|
||||||
|
// .e.g 10.0.0.1#en0
|
||||||
|
interfaceName := u.Fragment
|
||||||
|
|
||||||
var addr, dnsNetType string
|
var addr, dnsNetType string
|
||||||
switch u.Scheme {
|
switch u.Scheme {
|
||||||
case "udp":
|
case "udp":
|
||||||
@ -634,9 +499,6 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
case "dhcp":
|
case "dhcp":
|
||||||
addr = u.Host
|
addr = u.Host
|
||||||
dnsNetType = "dhcp" // UDP from DHCP
|
dnsNetType = "dhcp" // UDP from DHCP
|
||||||
case "quic":
|
|
||||||
addr, err = hostWithDefaultPort(u.Host, "784")
|
|
||||||
dnsNetType = "quic" // DNS over QUIC
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
return nil, fmt.Errorf("DNS NameServer[%d] unsupport scheme: %s", idx, u.Scheme)
|
||||||
}
|
}
|
||||||
@ -648,10 +510,9 @@ func parseNameServer(servers []string) ([]dns.NameServer, error) {
|
|||||||
nameservers = append(
|
nameservers = append(
|
||||||
nameservers,
|
nameservers,
|
||||||
dns.NameServer{
|
dns.NameServer{
|
||||||
Net: dnsNetType,
|
Net: dnsNetType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
ProxyAdapter: u.Fragment,
|
Interface: interfaceName,
|
||||||
Interface: dialer.DefaultInterface.Load(),
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -676,7 +537,7 @@ func parseNameServerPolicy(nsPolicy map[string]string) (map[string]dns.NameServe
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
|
func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
|
||||||
var ipNets []*net.IPNet
|
ipNets := []*net.IPNet{}
|
||||||
|
|
||||||
for idx, ip := range ips {
|
for idx, ip := range ips {
|
||||||
_, ipnet, err := net.ParseCIDR(ip)
|
_, ipnet, err := net.ParseCIDR(ip)
|
||||||
@ -689,42 +550,7 @@ func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
|
|||||||
return ipNets, nil
|
return ipNets, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
|
func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie) (*DNS, error) {
|
||||||
var sites []*router.DomainMatcher
|
|
||||||
if len(countries) > 0 {
|
|
||||||
if err := initGeoSite(); err != nil {
|
|
||||||
return nil, fmt.Errorf("can't initial GeoSite: %s", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, country := range countries {
|
|
||||||
found := false
|
|
||||||
for _, rule := range rules {
|
|
||||||
if rule.RuleType() == C.GEOSITE {
|
|
||||||
if strings.EqualFold(country, rule.Payload()) {
|
|
||||||
found = true
|
|
||||||
sites = append(sites, rule.(C.RuleGeoSite).GetDomainMatcher())
|
|
||||||
log.Infoln("Start initial GeoSite dns fallback filter from rule `%s`", country)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !found {
|
|
||||||
matcher, recordsCount, err := geodata.LoadGeoSiteMatcher(country)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
sites = append(sites, matcher)
|
|
||||||
|
|
||||||
log.Infoln("Start initial GeoSite dns fallback filter `%s`, records: %d", country, recordsCount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
runtime.GC()
|
|
||||||
return sites, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS, error) {
|
|
||||||
cfg := rawCfg.DNS
|
cfg := rawCfg.DNS
|
||||||
if cfg.Enable && len(cfg.NameServer) == 0 {
|
if cfg.Enable && len(cfg.NameServer) == 0 {
|
||||||
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty")
|
||||||
@ -736,8 +562,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
|
|||||||
IPv6: cfg.IPv6,
|
IPv6: cfg.IPv6,
|
||||||
EnhancedMode: cfg.EnhancedMode,
|
EnhancedMode: cfg.EnhancedMode,
|
||||||
FallbackFilter: FallbackFilter{
|
FallbackFilter: FallbackFilter{
|
||||||
IPCIDR: []*net.IPNet{},
|
IPCIDR: []*net.IPNet{},
|
||||||
GeoSite: []*router.DomainMatcher{},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
@ -753,10 +578,6 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if dnsCfg.ProxyServerNameserver, err = parseNameServer(cfg.ProxyServerNameserver); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(cfg.DefaultNameserver) == 0 {
|
if len(cfg.DefaultNameserver) == 0 {
|
||||||
return nil, errors.New("default nameserver should have at least one nameserver")
|
return nil, errors.New("default nameserver should have at least one nameserver")
|
||||||
}
|
}
|
||||||
@ -782,19 +603,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
|
|||||||
if len(cfg.FakeIPFilter) != 0 {
|
if len(cfg.FakeIPFilter) != 0 {
|
||||||
host = trie.New()
|
host = trie.New()
|
||||||
for _, domain := range cfg.FakeIPFilter {
|
for _, domain := range cfg.FakeIPFilter {
|
||||||
_ = host.Insert(domain, true)
|
host.Insert(domain, true)
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(dnsCfg.Fallback) != 0 {
|
|
||||||
if host == nil {
|
|
||||||
host = trie.New()
|
|
||||||
}
|
|
||||||
for _, fb := range dnsCfg.Fallback {
|
|
||||||
if net.ParseIP(fb.Addr) != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
_ = host.Insert(fb.Addr, true)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -811,19 +620,12 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
|
|||||||
dnsCfg.FakeIPRange = pool
|
dnsCfg.FakeIPRange = pool
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cfg.Fallback) != 0 {
|
dnsCfg.FallbackFilter.GeoIP = cfg.FallbackFilter.GeoIP
|
||||||
dnsCfg.FallbackFilter.GeoIP = cfg.FallbackFilter.GeoIP
|
dnsCfg.FallbackFilter.GeoIPCode = cfg.FallbackFilter.GeoIPCode
|
||||||
dnsCfg.FallbackFilter.GeoIPCode = cfg.FallbackFilter.GeoIPCode
|
if fallbackip, err := parseFallbackIPCIDR(cfg.FallbackFilter.IPCIDR); err == nil {
|
||||||
if fallbackip, err := parseFallbackIPCIDR(cfg.FallbackFilter.IPCIDR); err == nil {
|
dnsCfg.FallbackFilter.IPCIDR = fallbackip
|
||||||
dnsCfg.FallbackFilter.IPCIDR = fallbackip
|
|
||||||
}
|
|
||||||
dnsCfg.FallbackFilter.Domain = cfg.FallbackFilter.Domain
|
|
||||||
fallbackGeoSite, err := parseFallbackGeoSite(cfg.FallbackFilter.GeoSite, rules)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("load GeoSite dns fallback filter error, %w", err)
|
|
||||||
}
|
|
||||||
dnsCfg.FallbackFilter.GeoSite = fallbackGeoSite
|
|
||||||
}
|
}
|
||||||
|
dnsCfg.FallbackFilter.Domain = cfg.FallbackFilter.Domain
|
||||||
|
|
||||||
if cfg.UseHosts {
|
if cfg.UseHosts {
|
||||||
dnsCfg.Hosts = hosts
|
dnsCfg.Hosts = hosts
|
||||||
@ -833,7 +635,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
||||||
var users []auth.AuthUser
|
users := []auth.AuthUser{}
|
||||||
for _, line := range rawRecords {
|
for _, line := range rawRecords {
|
||||||
if user, pass, found := strings.Cut(line, ":"); found {
|
if user, pass, found := strings.Cut(line, ":"); found {
|
||||||
users = append(users, auth.AuthUser{User: user, Pass: pass})
|
users = append(users, auth.AuthUser{User: user, Pass: pass})
|
||||||
@ -841,39 +643,3 @@ func parseAuthentication(rawRecords []string) []auth.AuthUser {
|
|||||||
}
|
}
|
||||||
return users
|
return users
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTun(rawTun RawTun, general *General) (*Tun, error) {
|
|
||||||
if (rawTun.Enable || general.TProxyPort != 0) && general.Interface == "" {
|
|
||||||
autoDetectInterfaceName, err := commons.GetAutoDetectInterface()
|
|
||||||
if err != nil || autoDetectInterfaceName == "" {
|
|
||||||
log.Warnln("Can not find auto detect interface.[%s]", err)
|
|
||||||
} else {
|
|
||||||
log.Warnln("Auto detect interface: %s", autoDetectInterfaceName)
|
|
||||||
}
|
|
||||||
|
|
||||||
general.Interface = autoDetectInterfaceName
|
|
||||||
}
|
|
||||||
|
|
||||||
var dnsHijack []netip.AddrPort
|
|
||||||
|
|
||||||
for _, d := range rawTun.DNSHijack {
|
|
||||||
if _, after, ok := strings.Cut(d, "://"); ok {
|
|
||||||
d = after
|
|
||||||
}
|
|
||||||
|
|
||||||
addrPort, err := netip.ParseAddrPort(d)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("parse dns-hijack url error: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dnsHijack = append(dnsHijack, addrPort)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Tun{
|
|
||||||
Enable: rawTun.Enable,
|
|
||||||
Device: rawTun.Device,
|
|
||||||
Stack: rawTun.Stack,
|
|
||||||
DNSHijack: dnsHijack,
|
|
||||||
AutoRoute: rawTun.AutoRoute,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
@ -2,20 +2,17 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/Dreamacro/clash/component/geodata"
|
|
||||||
"github.com/Dreamacro/clash/component/mmdb"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/mmdb"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var initMode = true
|
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
func downloadMMDB(path string) (err error) {
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/geoip/release/Country.mmdb")
|
resp, err := http.Get("https://cdn.jsdelivr.net/gh/Dreamacro/maxmind-geoip@release/Country.mmdb")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -31,84 +28,7 @@ func downloadMMDB(path string) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadGeoIP(path string) (err error) {
|
func initMMDB() error {
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geoip.dat")
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, resp.Body)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadGeoSite(path string) (err error) {
|
|
||||||
resp, err := http.Get("https://raw.githubusercontents.com/Loyalsoldier/v2ray-rules-dat/release/geosite.dat")
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
_, err = io.Copy(f, resp.Body)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func initGeoSite() error {
|
|
||||||
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
|
||||||
log.Infoln("Can't find GeoSite.dat, start download")
|
|
||||||
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
log.Infoln("Download GeoSite.dat finish")
|
|
||||||
}
|
|
||||||
if initMode {
|
|
||||||
if !geodata.Verify(C.GeositeName) {
|
|
||||||
log.Warnln("GeoSite.dat invalid, remove and download")
|
|
||||||
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initGeoIP() error {
|
|
||||||
if C.GeodataMode {
|
|
||||||
if _, err := os.Stat(C.Path.GeoIP()); os.IsNotExist(err) {
|
|
||||||
log.Infoln("Can't find GeoIP.dat, start download")
|
|
||||||
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
log.Infoln("Download GeoIP.dat finish")
|
|
||||||
}
|
|
||||||
|
|
||||||
if !geodata.Verify(C.GeoipName) {
|
|
||||||
log.Warnln("GeoIP.dat invalid, remove and download")
|
|
||||||
if err := os.Remove(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't remove invalid GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
if err := downloadGeoIP(C.Path.GeoIP()); err != nil {
|
|
||||||
return fmt.Errorf("can't download GeoIP.dat: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
log.Infoln("Can't find MMDB, start download")
|
log.Infoln("Can't find MMDB, start download")
|
||||||
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
if err := downloadMMDB(C.Path.MMDB()); err != nil {
|
||||||
@ -149,20 +69,10 @@ func Init(dir string) error {
|
|||||||
f.Write([]byte(`mixed-port: 7890`))
|
f.Write([]byte(`mixed-port: 7890`))
|
||||||
f.Close()
|
f.Close()
|
||||||
}
|
}
|
||||||
buf, _ := os.ReadFile(C.Path.Config())
|
|
||||||
rawCfg, err := UnmarshalRawConfig(buf)
|
|
||||||
if err != nil {
|
|
||||||
log.Errorln(err.Error())
|
|
||||||
fmt.Printf("configuration file %s test failed\n", C.Path.Config())
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if !C.GeodataMode {
|
|
||||||
C.GeodataMode = rawCfg.GeodataMode
|
|
||||||
}
|
|
||||||
// initial GeoIP
|
|
||||||
if err := initGeoIP(); err != nil {
|
|
||||||
return fmt.Errorf("can't initial GeoIP: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// initial mmdb
|
||||||
|
if err := initMMDB(); err != nil {
|
||||||
|
return fmt.Errorf("can't initial MMDB: %w", err)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -13,14 +13,6 @@ import (
|
|||||||
const (
|
const (
|
||||||
Direct AdapterType = iota
|
Direct AdapterType = iota
|
||||||
Reject
|
Reject
|
||||||
Compatible
|
|
||||||
Pass
|
|
||||||
|
|
||||||
Relay
|
|
||||||
Selector
|
|
||||||
Fallback
|
|
||||||
URLTest
|
|
||||||
LoadBalance
|
|
||||||
|
|
||||||
Shadowsocks
|
Shadowsocks
|
||||||
ShadowsocksR
|
ShadowsocksR
|
||||||
@ -28,8 +20,13 @@ const (
|
|||||||
Socks5
|
Socks5
|
||||||
Http
|
Http
|
||||||
Vmess
|
Vmess
|
||||||
Vless
|
|
||||||
Trojan
|
Trojan
|
||||||
|
|
||||||
|
Relay
|
||||||
|
Selector
|
||||||
|
Fallback
|
||||||
|
URLTest
|
||||||
|
LoadBalance
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -131,10 +128,7 @@ func (at AdapterType) String() string {
|
|||||||
return "Direct"
|
return "Direct"
|
||||||
case Reject:
|
case Reject:
|
||||||
return "Reject"
|
return "Reject"
|
||||||
case Compatible:
|
|
||||||
return "Compatible"
|
|
||||||
case Pass:
|
|
||||||
return "Pass"
|
|
||||||
case Shadowsocks:
|
case Shadowsocks:
|
||||||
return "Shadowsocks"
|
return "Shadowsocks"
|
||||||
case ShadowsocksR:
|
case ShadowsocksR:
|
||||||
@ -147,8 +141,6 @@ func (at AdapterType) String() string {
|
|||||||
return "Http"
|
return "Http"
|
||||||
case Vmess:
|
case Vmess:
|
||||||
return "Vmess"
|
return "Vmess"
|
||||||
case Vless:
|
|
||||||
return "Vless"
|
|
||||||
case Trojan:
|
case Trojan:
|
||||||
return "Trojan"
|
return "Trojan"
|
||||||
|
|
||||||
|
@ -1,3 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
var GeodataMode bool
|
|
@ -2,20 +2,16 @@ package constant
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Socks addr type
|
// Socks addr type
|
||||||
const (
|
const (
|
||||||
AtypIPv4 = 1
|
|
||||||
AtypDomainName = 3
|
|
||||||
AtypIPv6 = 4
|
|
||||||
|
|
||||||
TCP NetWork = iota
|
TCP NetWork = iota
|
||||||
UDP
|
UDP
|
||||||
ALLNet
|
|
||||||
|
|
||||||
HTTP Type = iota
|
HTTP Type = iota
|
||||||
HTTPCONNECT
|
HTTPCONNECT
|
||||||
@ -23,8 +19,6 @@ const (
|
|||||||
SOCKS5
|
SOCKS5
|
||||||
REDIR
|
REDIR
|
||||||
TPROXY
|
TPROXY
|
||||||
TUN
|
|
||||||
INNER
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type NetWork int
|
type NetWork int
|
||||||
@ -32,10 +26,8 @@ type NetWork int
|
|||||||
func (n NetWork) String() string {
|
func (n NetWork) String() string {
|
||||||
if n == TCP {
|
if n == TCP {
|
||||||
return "tcp"
|
return "tcp"
|
||||||
} else if n == UDP {
|
|
||||||
return "udp"
|
|
||||||
}
|
}
|
||||||
return "all"
|
return "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n NetWork) MarshalJSON() ([]byte, error) {
|
func (n NetWork) MarshalJSON() ([]byte, error) {
|
||||||
@ -58,10 +50,6 @@ func (t Type) String() string {
|
|||||||
return "Redir"
|
return "Redir"
|
||||||
case TPROXY:
|
case TPROXY:
|
||||||
return "TProxy"
|
return "TProxy"
|
||||||
case TUN:
|
|
||||||
return "Tun"
|
|
||||||
case INNER:
|
|
||||||
return "Inner"
|
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
@ -79,10 +67,8 @@ type Metadata struct {
|
|||||||
DstIP net.IP `json:"destinationIP"`
|
DstIP net.IP `json:"destinationIP"`
|
||||||
SrcPort string `json:"sourcePort"`
|
SrcPort string `json:"sourcePort"`
|
||||||
DstPort string `json:"destinationPort"`
|
DstPort string `json:"destinationPort"`
|
||||||
AddrType int `json:"-"`
|
|
||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
DNSMode DNSMode `json:"dnsMode"`
|
DNSMode DNSMode `json:"dnsMode"`
|
||||||
Process string `json:"process"`
|
|
||||||
ProcessPath string `json:"processPath"`
|
ProcessPath string `json:"processPath"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -94,15 +80,14 @@ func (m *Metadata) SourceAddress() string {
|
|||||||
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
return net.JoinHostPort(m.SrcIP.String(), m.SrcPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Metadata) SourceDetail() string {
|
func (m *Metadata) AddrType() int {
|
||||||
if m.Process != "" {
|
switch true {
|
||||||
return fmt.Sprintf("%s(%s)", m.SourceAddress(), m.Process)
|
case m.Host != "" || m.DstIP == nil:
|
||||||
} else {
|
return socks5.AtypDomainName
|
||||||
if m.Type == INNER {
|
case m.DstIP.To4() != nil:
|
||||||
return fmt.Sprintf("[Clash]")
|
return socks5.AtypIPv4
|
||||||
}
|
default:
|
||||||
|
return socks5.AtypIPv6
|
||||||
return fmt.Sprintf("%s", m.SourceAddress())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,11 +101,6 @@ func (m *Metadata) Pure() *Metadata {
|
|||||||
if m.DNSMode == DNSMapping && m.DstIP != nil {
|
if m.DNSMode == DNSMapping && m.DstIP != nil {
|
||||||
copy := *m
|
copy := *m
|
||||||
copy.Host = ""
|
copy.Host = ""
|
||||||
if copy.DstIP.To4() != nil {
|
|
||||||
copy.AddrType = AtypIPv4
|
|
||||||
} else {
|
|
||||||
copy.AddrType = AtypIPv6
|
|
||||||
}
|
|
||||||
return ©
|
return ©
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,20 +1,13 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
P "path"
|
P "path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const Name = "clash"
|
const Name = "clash"
|
||||||
|
|
||||||
var (
|
|
||||||
GeositeName = "GeoSite.dat"
|
|
||||||
GeoipName = "GeoIP.dat"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Path is used to get the configuration path
|
// Path is used to get the configuration path
|
||||||
var Path = func() *path {
|
var Path = func() *path {
|
||||||
homeDir, err := os.UserHomeDir()
|
homeDir, err := os.UserHomeDir()
|
||||||
@ -29,7 +22,6 @@ var Path = func() *path {
|
|||||||
type path struct {
|
type path struct {
|
||||||
homeDir string
|
homeDir string
|
||||||
configFile string
|
configFile string
|
||||||
scriptDir string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHomeDir is used to set the configuration path
|
// SetHomeDir is used to set the configuration path
|
||||||
@ -55,25 +47,11 @@ func (p *path) Resolve(path string) string {
|
|||||||
if !filepath.IsAbs(path) {
|
if !filepath.IsAbs(path) {
|
||||||
return filepath.Join(p.HomeDir(), path)
|
return filepath.Join(p.HomeDir(), path)
|
||||||
}
|
}
|
||||||
|
|
||||||
return path
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) MMDB() string {
|
func (p *path) MMDB() string {
|
||||||
files, err := ioutil.ReadDir(p.homeDir)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
for _, fi := range files {
|
|
||||||
if fi.IsDir() {
|
|
||||||
// 目录则直接跳过
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
if strings.EqualFold(fi.Name(), "Country.mmdb") {
|
|
||||||
GeoipName = fi.Name()
|
|
||||||
return P.Join(p.homeDir, fi.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return P.Join(p.homeDir, "Country.mmdb")
|
return P.Join(p.homeDir, "Country.mmdb")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -84,71 +62,3 @@ func (p *path) OldCache() string {
|
|||||||
func (p *path) Cache() string {
|
func (p *path) Cache() string {
|
||||||
return P.Join(p.homeDir, "cache.db")
|
return P.Join(p.homeDir, "cache.db")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) GeoIP() string {
|
|
||||||
files, err := ioutil.ReadDir(p.homeDir)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
for _, fi := range files {
|
|
||||||
if fi.IsDir() {
|
|
||||||
// 目录则直接跳过
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
if strings.EqualFold(fi.Name(), "GeoIP.dat") {
|
|
||||||
GeoipName = fi.Name()
|
|
||||||
return P.Join(p.homeDir, fi.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return P.Join(p.homeDir, "GeoIP.dat")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *path) GeoSite() string {
|
|
||||||
files, err := ioutil.ReadDir(p.homeDir)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
for _, fi := range files {
|
|
||||||
if fi.IsDir() {
|
|
||||||
// 目录则直接跳过
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
if strings.EqualFold(fi.Name(), "GeoSite.dat") {
|
|
||||||
GeositeName = fi.Name()
|
|
||||||
return P.Join(p.homeDir, fi.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return P.Join(p.homeDir, "GeoSite.dat")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *path) ScriptDir() string {
|
|
||||||
if len(p.scriptDir) != 0 {
|
|
||||||
return p.scriptDir
|
|
||||||
}
|
|
||||||
if dir, err := os.MkdirTemp("", Name+"-"); err == nil {
|
|
||||||
p.scriptDir = dir
|
|
||||||
} else {
|
|
||||||
p.scriptDir = P.Join(os.TempDir(), Name)
|
|
||||||
_ = os.MkdirAll(p.scriptDir, 0o644)
|
|
||||||
}
|
|
||||||
return p.scriptDir
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *path) Script() string {
|
|
||||||
return P.Join(p.ScriptDir(), "clash_script.py")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *path) GetAssetLocation(file string) string {
|
|
||||||
return P.Join(p.homeDir, file)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *path) GetExecutableFullPath() string {
|
|
||||||
exePath, err := os.Executable()
|
|
||||||
if err != nil {
|
|
||||||
return "clash"
|
|
||||||
}
|
|
||||||
res, _ := filepath.EvalSymlinks(exePath)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
@ -5,7 +5,6 @@ const (
|
|||||||
Domain RuleType = iota
|
Domain RuleType = iota
|
||||||
DomainSuffix
|
DomainSuffix
|
||||||
DomainKeyword
|
DomainKeyword
|
||||||
GEOSITE
|
|
||||||
GEOIP
|
GEOIP
|
||||||
IPCIDR
|
IPCIDR
|
||||||
SrcIPCIDR
|
SrcIPCIDR
|
||||||
@ -13,13 +12,7 @@ const (
|
|||||||
DstPort
|
DstPort
|
||||||
Process
|
Process
|
||||||
ProcessPath
|
ProcessPath
|
||||||
Script
|
|
||||||
RuleSet
|
|
||||||
Network
|
|
||||||
MATCH
|
MATCH
|
||||||
AND
|
|
||||||
OR
|
|
||||||
NOT
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type RuleType int
|
type RuleType int
|
||||||
@ -32,8 +25,6 @@ func (rt RuleType) String() string {
|
|||||||
return "DomainSuffix"
|
return "DomainSuffix"
|
||||||
case DomainKeyword:
|
case DomainKeyword:
|
||||||
return "DomainKeyword"
|
return "DomainKeyword"
|
||||||
case GEOSITE:
|
|
||||||
return "GeoSite"
|
|
||||||
case GEOIP:
|
case GEOIP:
|
||||||
return "GeoIP"
|
return "GeoIP"
|
||||||
case IPCIDR:
|
case IPCIDR:
|
||||||
@ -48,20 +39,8 @@ func (rt RuleType) String() string {
|
|||||||
return "Process"
|
return "Process"
|
||||||
case ProcessPath:
|
case ProcessPath:
|
||||||
return "ProcessPath"
|
return "ProcessPath"
|
||||||
case Script:
|
|
||||||
return "Script"
|
|
||||||
case MATCH:
|
case MATCH:
|
||||||
return "Match"
|
return "Match"
|
||||||
case RuleSet:
|
|
||||||
return "RuleSet"
|
|
||||||
case Network:
|
|
||||||
return "Network"
|
|
||||||
case AND:
|
|
||||||
return "AND"
|
|
||||||
case OR:
|
|
||||||
return "OR"
|
|
||||||
case NOT:
|
|
||||||
return "NOT"
|
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
@ -74,6 +53,4 @@ type Rule interface {
|
|||||||
Payload() string
|
Payload() string
|
||||||
ShouldResolveIP() bool
|
ShouldResolveIP() bool
|
||||||
ShouldFindProcess() bool
|
ShouldFindProcess() bool
|
||||||
RuleExtra() *RuleExtra
|
|
||||||
SetRuleExtra(re *RuleExtra)
|
|
||||||
}
|
}
|
||||||
|
@ -1,48 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
|
||||||
)
|
|
||||||
|
|
||||||
type RuleExtra struct {
|
|
||||||
Network NetWork
|
|
||||||
SourceIPs []*net.IPNet
|
|
||||||
ProcessNames []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (re *RuleExtra) NotMatchNetwork(network NetWork) bool {
|
|
||||||
return re.Network != ALLNet && re.Network != network
|
|
||||||
}
|
|
||||||
|
|
||||||
func (re *RuleExtra) NotMatchSourceIP(srcIP net.IP) bool {
|
|
||||||
if re.SourceIPs == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, ips := range re.SourceIPs {
|
|
||||||
if ips.Contains(srcIP) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (re *RuleExtra) NotMatchProcessName(processName string) bool {
|
|
||||||
if re.ProcessNames == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, pn := range re.ProcessNames {
|
|
||||||
if strings.EqualFold(pn, processName) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleGeoSite interface {
|
|
||||||
GetDomainMatcher() *router.DomainMatcher
|
|
||||||
}
|
|
@ -1,66 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var StackTypeMapping = map[string]TUNStack{
|
|
||||||
strings.ToUpper(TunGvisor.String()): TunGvisor,
|
|
||||||
strings.ToUpper(TunSystem.String()): TunSystem,
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
TunGvisor TUNStack = iota
|
|
||||||
TunSystem
|
|
||||||
)
|
|
||||||
|
|
||||||
type TUNStack int
|
|
||||||
|
|
||||||
// UnmarshalYAML unserialize TUNStack with yaml
|
|
||||||
func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error {
|
|
||||||
var tp string
|
|
||||||
if err := unmarshal(&tp); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
mode, exist := StackTypeMapping[strings.ToUpper(tp)]
|
|
||||||
if !exist {
|
|
||||||
return errors.New("invalid tun stack")
|
|
||||||
}
|
|
||||||
*e = mode
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalYAML serialize TUNStack with yaml
|
|
||||||
func (e TUNStack) MarshalYAML() (any, error) {
|
|
||||||
return e.String(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalJSON unserialize TUNStack with json
|
|
||||||
func (e *TUNStack) UnmarshalJSON(data []byte) error {
|
|
||||||
var tp string
|
|
||||||
json.Unmarshal(data, &tp)
|
|
||||||
mode, exist := StackTypeMapping[strings.ToUpper(tp)]
|
|
||||||
if !exist {
|
|
||||||
return errors.New("invalid tun stack")
|
|
||||||
}
|
|
||||||
*e = mode
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON serialize TUNStack with json
|
|
||||||
func (e TUNStack) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(e.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e TUNStack) String() string {
|
|
||||||
switch e {
|
|
||||||
case TunGvisor:
|
|
||||||
return "gVisor"
|
|
||||||
case TunSystem:
|
|
||||||
return "System"
|
|
||||||
default:
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,8 +1,6 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Meta = true
|
Version = "unknown version"
|
||||||
Version = "1.10.0"
|
|
||||||
BuildTime = "unknown time"
|
BuildTime = "unknown time"
|
||||||
ClashName = "Clash.Meta"
|
|
||||||
)
|
)
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user